compiler-sfc.cjs.js 611 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var CompilerDOM = require('@vue/compiler-dom');
  4. var sourceMapJs = require('source-map-js');
  5. var path$3 = require('path');
  6. var parser$2 = require('@babel/parser');
  7. var shared = require('@vue/shared');
  8. var compilerCore = require('@vue/compiler-core');
  9. var url = require('url');
  10. var CompilerSSR = require('@vue/compiler-ssr');
  11. var require$$2 = require('util');
  12. var require$$0 = require('fs');
  13. var require$$0$1 = require('postcss');
  14. var estreeWalker = require('estree-walker');
  15. var reactivityTransform = require('@vue/reactivity-transform');
  16. var MagicString = require('magic-string');
  17. function _interopNamespaceDefault(e) {
  18. var n = Object.create(null);
  19. if (e) {
  20. for (var k in e) {
  21. n[k] = e[k];
  22. }
  23. }
  24. n.default = e;
  25. return Object.freeze(n);
  26. }
  27. var CompilerDOM__namespace = /*#__PURE__*/_interopNamespaceDefault(CompilerDOM);
  28. var CompilerSSR__namespace = /*#__PURE__*/_interopNamespaceDefault(CompilerSSR);
  29. const UNKNOWN_TYPE = "Unknown";
  30. function resolveObjectKey(node, computed) {
  31. switch (node.type) {
  32. case "StringLiteral":
  33. case "NumericLiteral":
  34. return String(node.value);
  35. case "Identifier":
  36. if (!computed)
  37. return node.name;
  38. }
  39. return void 0;
  40. }
  41. function concatStrings(strs) {
  42. return strs.filter((s) => !!s).join(", ");
  43. }
  44. function isLiteralNode(node) {
  45. return node.type.endsWith("Literal");
  46. }
  47. function unwrapTSNode(node) {
  48. if (CompilerDOM.TS_NODE_TYPES.includes(node.type)) {
  49. return unwrapTSNode(node.expression);
  50. } else {
  51. return node;
  52. }
  53. }
  54. function isCallOf(node, test) {
  55. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  56. }
  57. function toRuntimeTypeString(types) {
  58. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  59. }
  60. function getImportedName(specifier) {
  61. if (specifier.type === "ImportSpecifier")
  62. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  63. else if (specifier.type === "ImportNamespaceSpecifier")
  64. return "*";
  65. return "default";
  66. }
  67. function getId(node) {
  68. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  69. }
  70. const identity = (str) => str;
  71. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  72. const toLowerCase = (str) => str.toLowerCase();
  73. function toFileNameLowerCase(x) {
  74. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  75. }
  76. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  77. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  78. }
  79. const normalize = (path$3.posix || path$3).normalize;
  80. const windowsSlashRE = /\\/g;
  81. function normalizePath(p) {
  82. return normalize(p.replace(windowsSlashRE, "/"));
  83. }
  84. const joinPaths = (path$3.posix || path$3).join;
  85. const escapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g;
  86. function getEscapedKey(key) {
  87. return escapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  88. }
  89. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  90. function getDefaultExportFromCjs (x) {
  91. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  92. }
  93. function pad (hash, len) {
  94. while (hash.length < len) {
  95. hash = '0' + hash;
  96. }
  97. return hash;
  98. }
  99. function fold (hash, text) {
  100. var i;
  101. var chr;
  102. var len;
  103. if (text.length === 0) {
  104. return hash;
  105. }
  106. for (i = 0, len = text.length; i < len; i++) {
  107. chr = text.charCodeAt(i);
  108. hash = ((hash << 5) - hash) + chr;
  109. hash |= 0;
  110. }
  111. return hash < 0 ? hash * -2 : hash;
  112. }
  113. function foldObject (hash, o, seen) {
  114. return Object.keys(o).sort().reduce(foldKey, hash);
  115. function foldKey (hash, key) {
  116. return foldValue(hash, o[key], key, seen);
  117. }
  118. }
  119. function foldValue (input, value, key, seen) {
  120. var hash = fold(fold(fold(input, key), toString$1(value)), typeof value);
  121. if (value === null) {
  122. return fold(hash, 'null');
  123. }
  124. if (value === undefined) {
  125. return fold(hash, 'undefined');
  126. }
  127. if (typeof value === 'object' || typeof value === 'function') {
  128. if (seen.indexOf(value) !== -1) {
  129. return fold(hash, '[Circular]' + key);
  130. }
  131. seen.push(value);
  132. var objHash = foldObject(hash, value, seen);
  133. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  134. return objHash;
  135. }
  136. try {
  137. return fold(objHash, String(value.valueOf()))
  138. } catch (err) {
  139. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  140. }
  141. }
  142. return fold(hash, value.toString());
  143. }
  144. function toString$1 (o) {
  145. return Object.prototype.toString.call(o);
  146. }
  147. function sum (o) {
  148. return pad(foldValue(0, o, '', []).toString(16), 8);
  149. }
  150. var hashSum = sum;
  151. var hash$1 = hashSum;
  152. const CSS_VARS_HELPER = `useCssVars`;
  153. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  154. return `{
  155. ${vars.map(
  156. (key) => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd)}": (${key})`
  157. ).join(",\n ")}
  158. }`;
  159. }
  160. function genVarName(id, raw, isProd) {
  161. if (isProd) {
  162. return hash$1(id + raw);
  163. } else {
  164. return `${id}-${raw.replace(escapeSymbolsRE, (s) => `\\${s}`)}`;
  165. }
  166. }
  167. function normalizeExpression(exp) {
  168. exp = exp.trim();
  169. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  170. return exp.slice(1, -1);
  171. }
  172. return exp;
  173. }
  174. const vBindRE = /v-bind\s*\(/g;
  175. function parseCssVars(sfc) {
  176. const vars = [];
  177. sfc.styles.forEach((style) => {
  178. let match;
  179. const content = style.content.replace(/\/\*([\s\S]*?)\*\//g, "");
  180. while (match = vBindRE.exec(content)) {
  181. const start = match.index + match[0].length;
  182. const end = lexBinding(content, start);
  183. if (end !== null) {
  184. const variable = normalizeExpression(content.slice(start, end));
  185. if (!vars.includes(variable)) {
  186. vars.push(variable);
  187. }
  188. }
  189. }
  190. });
  191. return vars;
  192. }
  193. function lexBinding(content, start) {
  194. let state = 0 /* inParens */;
  195. let parenDepth = 0;
  196. for (let i = start; i < content.length; i++) {
  197. const char = content.charAt(i);
  198. switch (state) {
  199. case 0 /* inParens */:
  200. if (char === `'`) {
  201. state = 1 /* inSingleQuoteString */;
  202. } else if (char === `"`) {
  203. state = 2 /* inDoubleQuoteString */;
  204. } else if (char === `(`) {
  205. parenDepth++;
  206. } else if (char === `)`) {
  207. if (parenDepth > 0) {
  208. parenDepth--;
  209. } else {
  210. return i;
  211. }
  212. }
  213. break;
  214. case 1 /* inSingleQuoteString */:
  215. if (char === `'`) {
  216. state = 0 /* inParens */;
  217. }
  218. break;
  219. case 2 /* inDoubleQuoteString */:
  220. if (char === `"`) {
  221. state = 0 /* inParens */;
  222. }
  223. break;
  224. }
  225. }
  226. return null;
  227. }
  228. const cssVarsPlugin = (opts) => {
  229. const { id, isProd } = opts;
  230. return {
  231. postcssPlugin: "vue-sfc-vars",
  232. Declaration(decl) {
  233. const value = decl.value;
  234. if (vBindRE.test(value)) {
  235. vBindRE.lastIndex = 0;
  236. let transformed = "";
  237. let lastIndex = 0;
  238. let match;
  239. while (match = vBindRE.exec(value)) {
  240. const start = match.index + match[0].length;
  241. const end = lexBinding(value, start);
  242. if (end !== null) {
  243. const variable = normalizeExpression(value.slice(start, end));
  244. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  245. lastIndex = end + 1;
  246. }
  247. }
  248. decl.value = transformed + value.slice(lastIndex);
  249. }
  250. }
  251. };
  252. };
  253. cssVarsPlugin.postcss = true;
  254. function genCssVarsCode(vars, bindings, id, isProd) {
  255. const varsExp = genCssVarsFromList(vars, id, isProd);
  256. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  257. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  258. prefixIdentifiers: true,
  259. inline: true,
  260. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  261. });
  262. const transformed = CompilerDOM.processExpression(exp, context);
  263. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  264. return typeof c === "string" ? c : c.content;
  265. }).join("");
  266. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  267. }
  268. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  269. return `
  270. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  271. const __injectCSSVars__ = () => {
  272. ${genCssVarsCode(
  273. cssVars,
  274. bindings,
  275. id,
  276. isProd
  277. )}}
  278. const __setup__ = ${defaultVar}.setup
  279. ${defaultVar}.setup = __setup__
  280. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  281. : __injectCSSVars__
  282. `;
  283. }
  284. var iterator;
  285. var hasRequiredIterator;
  286. function requireIterator () {
  287. if (hasRequiredIterator) return iterator;
  288. hasRequiredIterator = 1;
  289. iterator = function (Yallist) {
  290. Yallist.prototype[Symbol.iterator] = function* () {
  291. for (let walker = this.head; walker; walker = walker.next) {
  292. yield walker.value;
  293. }
  294. };
  295. };
  296. return iterator;
  297. }
  298. var yallist = Yallist$1;
  299. Yallist$1.Node = Node;
  300. Yallist$1.create = Yallist$1;
  301. function Yallist$1 (list) {
  302. var self = this;
  303. if (!(self instanceof Yallist$1)) {
  304. self = new Yallist$1();
  305. }
  306. self.tail = null;
  307. self.head = null;
  308. self.length = 0;
  309. if (list && typeof list.forEach === 'function') {
  310. list.forEach(function (item) {
  311. self.push(item);
  312. });
  313. } else if (arguments.length > 0) {
  314. for (var i = 0, l = arguments.length; i < l; i++) {
  315. self.push(arguments[i]);
  316. }
  317. }
  318. return self
  319. }
  320. Yallist$1.prototype.removeNode = function (node) {
  321. if (node.list !== this) {
  322. throw new Error('removing node which does not belong to this list')
  323. }
  324. var next = node.next;
  325. var prev = node.prev;
  326. if (next) {
  327. next.prev = prev;
  328. }
  329. if (prev) {
  330. prev.next = next;
  331. }
  332. if (node === this.head) {
  333. this.head = next;
  334. }
  335. if (node === this.tail) {
  336. this.tail = prev;
  337. }
  338. node.list.length--;
  339. node.next = null;
  340. node.prev = null;
  341. node.list = null;
  342. return next
  343. };
  344. Yallist$1.prototype.unshiftNode = function (node) {
  345. if (node === this.head) {
  346. return
  347. }
  348. if (node.list) {
  349. node.list.removeNode(node);
  350. }
  351. var head = this.head;
  352. node.list = this;
  353. node.next = head;
  354. if (head) {
  355. head.prev = node;
  356. }
  357. this.head = node;
  358. if (!this.tail) {
  359. this.tail = node;
  360. }
  361. this.length++;
  362. };
  363. Yallist$1.prototype.pushNode = function (node) {
  364. if (node === this.tail) {
  365. return
  366. }
  367. if (node.list) {
  368. node.list.removeNode(node);
  369. }
  370. var tail = this.tail;
  371. node.list = this;
  372. node.prev = tail;
  373. if (tail) {
  374. tail.next = node;
  375. }
  376. this.tail = node;
  377. if (!this.head) {
  378. this.head = node;
  379. }
  380. this.length++;
  381. };
  382. Yallist$1.prototype.push = function () {
  383. for (var i = 0, l = arguments.length; i < l; i++) {
  384. push(this, arguments[i]);
  385. }
  386. return this.length
  387. };
  388. Yallist$1.prototype.unshift = function () {
  389. for (var i = 0, l = arguments.length; i < l; i++) {
  390. unshift(this, arguments[i]);
  391. }
  392. return this.length
  393. };
  394. Yallist$1.prototype.pop = function () {
  395. if (!this.tail) {
  396. return undefined
  397. }
  398. var res = this.tail.value;
  399. this.tail = this.tail.prev;
  400. if (this.tail) {
  401. this.tail.next = null;
  402. } else {
  403. this.head = null;
  404. }
  405. this.length--;
  406. return res
  407. };
  408. Yallist$1.prototype.shift = function () {
  409. if (!this.head) {
  410. return undefined
  411. }
  412. var res = this.head.value;
  413. this.head = this.head.next;
  414. if (this.head) {
  415. this.head.prev = null;
  416. } else {
  417. this.tail = null;
  418. }
  419. this.length--;
  420. return res
  421. };
  422. Yallist$1.prototype.forEach = function (fn, thisp) {
  423. thisp = thisp || this;
  424. for (var walker = this.head, i = 0; walker !== null; i++) {
  425. fn.call(thisp, walker.value, i, this);
  426. walker = walker.next;
  427. }
  428. };
  429. Yallist$1.prototype.forEachReverse = function (fn, thisp) {
  430. thisp = thisp || this;
  431. for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
  432. fn.call(thisp, walker.value, i, this);
  433. walker = walker.prev;
  434. }
  435. };
  436. Yallist$1.prototype.get = function (n) {
  437. for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
  438. // abort out of the list early if we hit a cycle
  439. walker = walker.next;
  440. }
  441. if (i === n && walker !== null) {
  442. return walker.value
  443. }
  444. };
  445. Yallist$1.prototype.getReverse = function (n) {
  446. for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
  447. // abort out of the list early if we hit a cycle
  448. walker = walker.prev;
  449. }
  450. if (i === n && walker !== null) {
  451. return walker.value
  452. }
  453. };
  454. Yallist$1.prototype.map = function (fn, thisp) {
  455. thisp = thisp || this;
  456. var res = new Yallist$1();
  457. for (var walker = this.head; walker !== null;) {
  458. res.push(fn.call(thisp, walker.value, this));
  459. walker = walker.next;
  460. }
  461. return res
  462. };
  463. Yallist$1.prototype.mapReverse = function (fn, thisp) {
  464. thisp = thisp || this;
  465. var res = new Yallist$1();
  466. for (var walker = this.tail; walker !== null;) {
  467. res.push(fn.call(thisp, walker.value, this));
  468. walker = walker.prev;
  469. }
  470. return res
  471. };
  472. Yallist$1.prototype.reduce = function (fn, initial) {
  473. var acc;
  474. var walker = this.head;
  475. if (arguments.length > 1) {
  476. acc = initial;
  477. } else if (this.head) {
  478. walker = this.head.next;
  479. acc = this.head.value;
  480. } else {
  481. throw new TypeError('Reduce of empty list with no initial value')
  482. }
  483. for (var i = 0; walker !== null; i++) {
  484. acc = fn(acc, walker.value, i);
  485. walker = walker.next;
  486. }
  487. return acc
  488. };
  489. Yallist$1.prototype.reduceReverse = function (fn, initial) {
  490. var acc;
  491. var walker = this.tail;
  492. if (arguments.length > 1) {
  493. acc = initial;
  494. } else if (this.tail) {
  495. walker = this.tail.prev;
  496. acc = this.tail.value;
  497. } else {
  498. throw new TypeError('Reduce of empty list with no initial value')
  499. }
  500. for (var i = this.length - 1; walker !== null; i--) {
  501. acc = fn(acc, walker.value, i);
  502. walker = walker.prev;
  503. }
  504. return acc
  505. };
  506. Yallist$1.prototype.toArray = function () {
  507. var arr = new Array(this.length);
  508. for (var i = 0, walker = this.head; walker !== null; i++) {
  509. arr[i] = walker.value;
  510. walker = walker.next;
  511. }
  512. return arr
  513. };
  514. Yallist$1.prototype.toArrayReverse = function () {
  515. var arr = new Array(this.length);
  516. for (var i = 0, walker = this.tail; walker !== null; i++) {
  517. arr[i] = walker.value;
  518. walker = walker.prev;
  519. }
  520. return arr
  521. };
  522. Yallist$1.prototype.slice = function (from, to) {
  523. to = to || this.length;
  524. if (to < 0) {
  525. to += this.length;
  526. }
  527. from = from || 0;
  528. if (from < 0) {
  529. from += this.length;
  530. }
  531. var ret = new Yallist$1();
  532. if (to < from || to < 0) {
  533. return ret
  534. }
  535. if (from < 0) {
  536. from = 0;
  537. }
  538. if (to > this.length) {
  539. to = this.length;
  540. }
  541. for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
  542. walker = walker.next;
  543. }
  544. for (; walker !== null && i < to; i++, walker = walker.next) {
  545. ret.push(walker.value);
  546. }
  547. return ret
  548. };
  549. Yallist$1.prototype.sliceReverse = function (from, to) {
  550. to = to || this.length;
  551. if (to < 0) {
  552. to += this.length;
  553. }
  554. from = from || 0;
  555. if (from < 0) {
  556. from += this.length;
  557. }
  558. var ret = new Yallist$1();
  559. if (to < from || to < 0) {
  560. return ret
  561. }
  562. if (from < 0) {
  563. from = 0;
  564. }
  565. if (to > this.length) {
  566. to = this.length;
  567. }
  568. for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
  569. walker = walker.prev;
  570. }
  571. for (; walker !== null && i > from; i--, walker = walker.prev) {
  572. ret.push(walker.value);
  573. }
  574. return ret
  575. };
  576. Yallist$1.prototype.splice = function (start, deleteCount /*, ...nodes */) {
  577. if (start > this.length) {
  578. start = this.length - 1;
  579. }
  580. if (start < 0) {
  581. start = this.length + start;
  582. }
  583. for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
  584. walker = walker.next;
  585. }
  586. var ret = [];
  587. for (var i = 0; walker && i < deleteCount; i++) {
  588. ret.push(walker.value);
  589. walker = this.removeNode(walker);
  590. }
  591. if (walker === null) {
  592. walker = this.tail;
  593. }
  594. if (walker !== this.head && walker !== this.tail) {
  595. walker = walker.prev;
  596. }
  597. for (var i = 2; i < arguments.length; i++) {
  598. walker = insert(this, walker, arguments[i]);
  599. }
  600. return ret;
  601. };
  602. Yallist$1.prototype.reverse = function () {
  603. var head = this.head;
  604. var tail = this.tail;
  605. for (var walker = head; walker !== null; walker = walker.prev) {
  606. var p = walker.prev;
  607. walker.prev = walker.next;
  608. walker.next = p;
  609. }
  610. this.head = tail;
  611. this.tail = head;
  612. return this
  613. };
  614. function insert (self, node, value) {
  615. var inserted = node === self.head ?
  616. new Node(value, null, node, self) :
  617. new Node(value, node, node.next, self);
  618. if (inserted.next === null) {
  619. self.tail = inserted;
  620. }
  621. if (inserted.prev === null) {
  622. self.head = inserted;
  623. }
  624. self.length++;
  625. return inserted
  626. }
  627. function push (self, item) {
  628. self.tail = new Node(item, self.tail, null, self);
  629. if (!self.head) {
  630. self.head = self.tail;
  631. }
  632. self.length++;
  633. }
  634. function unshift (self, item) {
  635. self.head = new Node(item, null, self.head, self);
  636. if (!self.tail) {
  637. self.tail = self.head;
  638. }
  639. self.length++;
  640. }
  641. function Node (value, prev, next, list) {
  642. if (!(this instanceof Node)) {
  643. return new Node(value, prev, next, list)
  644. }
  645. this.list = list;
  646. this.value = value;
  647. if (prev) {
  648. prev.next = this;
  649. this.prev = prev;
  650. } else {
  651. this.prev = null;
  652. }
  653. if (next) {
  654. next.prev = this;
  655. this.next = next;
  656. } else {
  657. this.next = null;
  658. }
  659. }
  660. try {
  661. // add if support for Symbol.iterator is present
  662. requireIterator()(Yallist$1);
  663. } catch (er) {}
  664. // A linked list to keep track of recently-used-ness
  665. const Yallist = yallist;
  666. const MAX = Symbol('max');
  667. const LENGTH = Symbol('length');
  668. const LENGTH_CALCULATOR = Symbol('lengthCalculator');
  669. const ALLOW_STALE = Symbol('allowStale');
  670. const MAX_AGE = Symbol('maxAge');
  671. const DISPOSE = Symbol('dispose');
  672. const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet');
  673. const LRU_LIST = Symbol('lruList');
  674. const CACHE = Symbol('cache');
  675. const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet');
  676. const naiveLength = () => 1;
  677. // lruList is a yallist where the head is the youngest
  678. // item, and the tail is the oldest. the list contains the Hit
  679. // objects as the entries.
  680. // Each Hit object has a reference to its Yallist.Node. This
  681. // never changes.
  682. //
  683. // cache is a Map (or PseudoMap) that matches the keys to
  684. // the Yallist.Node object.
  685. class LRUCache {
  686. constructor (options) {
  687. if (typeof options === 'number')
  688. options = { max: options };
  689. if (!options)
  690. options = {};
  691. if (options.max && (typeof options.max !== 'number' || options.max < 0))
  692. throw new TypeError('max must be a non-negative number')
  693. // Kind of weird to have a default max of Infinity, but oh well.
  694. this[MAX] = options.max || Infinity;
  695. const lc = options.length || naiveLength;
  696. this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc;
  697. this[ALLOW_STALE] = options.stale || false;
  698. if (options.maxAge && typeof options.maxAge !== 'number')
  699. throw new TypeError('maxAge must be a number')
  700. this[MAX_AGE] = options.maxAge || 0;
  701. this[DISPOSE] = options.dispose;
  702. this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
  703. this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false;
  704. this.reset();
  705. }
  706. // resize the cache when the max changes.
  707. set max (mL) {
  708. if (typeof mL !== 'number' || mL < 0)
  709. throw new TypeError('max must be a non-negative number')
  710. this[MAX] = mL || Infinity;
  711. trim(this);
  712. }
  713. get max () {
  714. return this[MAX]
  715. }
  716. set allowStale (allowStale) {
  717. this[ALLOW_STALE] = !!allowStale;
  718. }
  719. get allowStale () {
  720. return this[ALLOW_STALE]
  721. }
  722. set maxAge (mA) {
  723. if (typeof mA !== 'number')
  724. throw new TypeError('maxAge must be a non-negative number')
  725. this[MAX_AGE] = mA;
  726. trim(this);
  727. }
  728. get maxAge () {
  729. return this[MAX_AGE]
  730. }
  731. // resize the cache when the lengthCalculator changes.
  732. set lengthCalculator (lC) {
  733. if (typeof lC !== 'function')
  734. lC = naiveLength;
  735. if (lC !== this[LENGTH_CALCULATOR]) {
  736. this[LENGTH_CALCULATOR] = lC;
  737. this[LENGTH] = 0;
  738. this[LRU_LIST].forEach(hit => {
  739. hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
  740. this[LENGTH] += hit.length;
  741. });
  742. }
  743. trim(this);
  744. }
  745. get lengthCalculator () { return this[LENGTH_CALCULATOR] }
  746. get length () { return this[LENGTH] }
  747. get itemCount () { return this[LRU_LIST].length }
  748. rforEach (fn, thisp) {
  749. thisp = thisp || this;
  750. for (let walker = this[LRU_LIST].tail; walker !== null;) {
  751. const prev = walker.prev;
  752. forEachStep(this, fn, walker, thisp);
  753. walker = prev;
  754. }
  755. }
  756. forEach (fn, thisp) {
  757. thisp = thisp || this;
  758. for (let walker = this[LRU_LIST].head; walker !== null;) {
  759. const next = walker.next;
  760. forEachStep(this, fn, walker, thisp);
  761. walker = next;
  762. }
  763. }
  764. keys () {
  765. return this[LRU_LIST].toArray().map(k => k.key)
  766. }
  767. values () {
  768. return this[LRU_LIST].toArray().map(k => k.value)
  769. }
  770. reset () {
  771. if (this[DISPOSE] &&
  772. this[LRU_LIST] &&
  773. this[LRU_LIST].length) {
  774. this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value));
  775. }
  776. this[CACHE] = new Map(); // hash of items by key
  777. this[LRU_LIST] = new Yallist(); // list of items in order of use recency
  778. this[LENGTH] = 0; // length of items in the list
  779. }
  780. dump () {
  781. return this[LRU_LIST].map(hit =>
  782. isStale(this, hit) ? false : {
  783. k: hit.key,
  784. v: hit.value,
  785. e: hit.now + (hit.maxAge || 0)
  786. }).toArray().filter(h => h)
  787. }
  788. dumpLru () {
  789. return this[LRU_LIST]
  790. }
  791. set (key, value, maxAge) {
  792. maxAge = maxAge || this[MAX_AGE];
  793. if (maxAge && typeof maxAge !== 'number')
  794. throw new TypeError('maxAge must be a number')
  795. const now = maxAge ? Date.now() : 0;
  796. const len = this[LENGTH_CALCULATOR](value, key);
  797. if (this[CACHE].has(key)) {
  798. if (len > this[MAX]) {
  799. del(this, this[CACHE].get(key));
  800. return false
  801. }
  802. const node = this[CACHE].get(key);
  803. const item = node.value;
  804. // dispose of the old one before overwriting
  805. // split out into 2 ifs for better coverage tracking
  806. if (this[DISPOSE]) {
  807. if (!this[NO_DISPOSE_ON_SET])
  808. this[DISPOSE](key, item.value);
  809. }
  810. item.now = now;
  811. item.maxAge = maxAge;
  812. item.value = value;
  813. this[LENGTH] += len - item.length;
  814. item.length = len;
  815. this.get(key);
  816. trim(this);
  817. return true
  818. }
  819. const hit = new Entry(key, value, len, now, maxAge);
  820. // oversized objects fall out of cache automatically.
  821. if (hit.length > this[MAX]) {
  822. if (this[DISPOSE])
  823. this[DISPOSE](key, value);
  824. return false
  825. }
  826. this[LENGTH] += hit.length;
  827. this[LRU_LIST].unshift(hit);
  828. this[CACHE].set(key, this[LRU_LIST].head);
  829. trim(this);
  830. return true
  831. }
  832. has (key) {
  833. if (!this[CACHE].has(key)) return false
  834. const hit = this[CACHE].get(key).value;
  835. return !isStale(this, hit)
  836. }
  837. get (key) {
  838. return get(this, key, true)
  839. }
  840. peek (key) {
  841. return get(this, key, false)
  842. }
  843. pop () {
  844. const node = this[LRU_LIST].tail;
  845. if (!node)
  846. return null
  847. del(this, node);
  848. return node.value
  849. }
  850. del (key) {
  851. del(this, this[CACHE].get(key));
  852. }
  853. load (arr) {
  854. // reset the cache
  855. this.reset();
  856. const now = Date.now();
  857. // A previous serialized cache has the most recent items first
  858. for (let l = arr.length - 1; l >= 0; l--) {
  859. const hit = arr[l];
  860. const expiresAt = hit.e || 0;
  861. if (expiresAt === 0)
  862. // the item was created without expiration in a non aged cache
  863. this.set(hit.k, hit.v);
  864. else {
  865. const maxAge = expiresAt - now;
  866. // dont add already expired items
  867. if (maxAge > 0) {
  868. this.set(hit.k, hit.v, maxAge);
  869. }
  870. }
  871. }
  872. }
  873. prune () {
  874. this[CACHE].forEach((value, key) => get(this, key, false));
  875. }
  876. }
  877. const get = (self, key, doUse) => {
  878. const node = self[CACHE].get(key);
  879. if (node) {
  880. const hit = node.value;
  881. if (isStale(self, hit)) {
  882. del(self, node);
  883. if (!self[ALLOW_STALE])
  884. return undefined
  885. } else {
  886. if (doUse) {
  887. if (self[UPDATE_AGE_ON_GET])
  888. node.value.now = Date.now();
  889. self[LRU_LIST].unshiftNode(node);
  890. }
  891. }
  892. return hit.value
  893. }
  894. };
  895. const isStale = (self, hit) => {
  896. if (!hit || (!hit.maxAge && !self[MAX_AGE]))
  897. return false
  898. const diff = Date.now() - hit.now;
  899. return hit.maxAge ? diff > hit.maxAge
  900. : self[MAX_AGE] && (diff > self[MAX_AGE])
  901. };
  902. const trim = self => {
  903. if (self[LENGTH] > self[MAX]) {
  904. for (let walker = self[LRU_LIST].tail;
  905. self[LENGTH] > self[MAX] && walker !== null;) {
  906. // We know that we're about to delete this one, and also
  907. // what the next least recently used key will be, so just
  908. // go ahead and set it now.
  909. const prev = walker.prev;
  910. del(self, walker);
  911. walker = prev;
  912. }
  913. }
  914. };
  915. const del = (self, node) => {
  916. if (node) {
  917. const hit = node.value;
  918. if (self[DISPOSE])
  919. self[DISPOSE](hit.key, hit.value);
  920. self[LENGTH] -= hit.length;
  921. self[CACHE].delete(hit.key);
  922. self[LRU_LIST].removeNode(node);
  923. }
  924. };
  925. class Entry {
  926. constructor (key, value, length, now, maxAge) {
  927. this.key = key;
  928. this.value = value;
  929. this.length = length;
  930. this.now = now;
  931. this.maxAge = maxAge || 0;
  932. }
  933. }
  934. const forEachStep = (self, fn, node, thisp) => {
  935. let hit = node.value;
  936. if (isStale(self, hit)) {
  937. del(self, node);
  938. if (!self[ALLOW_STALE])
  939. hit = undefined;
  940. }
  941. if (hit)
  942. fn.call(thisp, hit.value, hit.key, self);
  943. };
  944. var lruCache = LRUCache;
  945. var LRU = lruCache;
  946. function createCache(size = 500) {
  947. const cache = new LRU(size);
  948. cache.delete = cache.del.bind(cache);
  949. return cache;
  950. }
  951. function isImportUsed(local, sfc) {
  952. return new RegExp(
  953. // #4274 escape $ since it's a special char in regex
  954. // (and is the only regex special char that is valid in identifiers)
  955. `[^\\w$_]${local.replace(/\$/g, "\\$")}[^\\w$_]`
  956. ).test(resolveTemplateUsageCheckString(sfc));
  957. }
  958. const templateUsageCheckCache = createCache();
  959. function resolveTemplateUsageCheckString(sfc) {
  960. const { content, ast } = sfc.template;
  961. const cached = templateUsageCheckCache.get(content);
  962. if (cached) {
  963. return cached;
  964. }
  965. let code = "";
  966. CompilerDOM.transform(CompilerDOM.createRoot([ast]), {
  967. nodeTransforms: [
  968. (node) => {
  969. if (node.type === 1) {
  970. if (!CompilerDOM.parserOptions.isNativeTag(node.tag) && !CompilerDOM.parserOptions.isBuiltInComponent(node.tag)) {
  971. code += `,${shared.camelize(node.tag)},${shared.capitalize(shared.camelize(node.tag))}`;
  972. }
  973. for (let i = 0; i < node.props.length; i++) {
  974. const prop = node.props[i];
  975. if (prop.type === 7) {
  976. if (!shared.isBuiltInDirective(prop.name)) {
  977. code += `,v${shared.capitalize(shared.camelize(prop.name))}`;
  978. }
  979. if (prop.exp) {
  980. code += `,${processExp(
  981. prop.exp.content,
  982. prop.name
  983. )}`;
  984. }
  985. }
  986. }
  987. } else if (node.type === 5) {
  988. code += `,${processExp(
  989. node.content.content
  990. )}`;
  991. }
  992. }
  993. ]
  994. });
  995. code += ";";
  996. templateUsageCheckCache.set(content, code);
  997. return code;
  998. }
  999. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  1000. function processExp(exp, dir) {
  1001. if (/ as\s+\w|<.*>|:/.test(exp)) {
  1002. if (dir === "slot") {
  1003. exp = `(${exp})=>{}`;
  1004. } else if (dir === "on") {
  1005. exp = `()=>{return ${exp}}`;
  1006. } else if (dir === "for") {
  1007. const inMatch = exp.match(forAliasRE);
  1008. if (inMatch) {
  1009. let [, LHS, RHS] = inMatch;
  1010. LHS = LHS.trim().replace(/^\(|\)$/g, "");
  1011. return processExp(`(${LHS})=>{}`) + processExp(RHS);
  1012. }
  1013. }
  1014. let ret = "";
  1015. const ast = parser$2.parseExpression(exp, { plugins: ["typescript"] });
  1016. CompilerDOM.walkIdentifiers(ast, (node) => {
  1017. ret += `,` + node.name;
  1018. });
  1019. return ret;
  1020. }
  1021. return stripStrings(exp);
  1022. }
  1023. function stripStrings(exp) {
  1024. return exp.replace(/'[^']*'|"[^"]*"/g, "").replace(/`[^`]+`/g, stripTemplateString);
  1025. }
  1026. function stripTemplateString(str) {
  1027. const interpMatch = str.match(/\${[^}]+}/g);
  1028. if (interpMatch) {
  1029. return interpMatch.map((m) => m.slice(2, -1)).join(",");
  1030. }
  1031. return "";
  1032. }
  1033. const DEFAULT_FILENAME = "anonymous.vue";
  1034. const parseCache = createCache();
  1035. function parse$2(source, {
  1036. sourceMap = true,
  1037. filename = DEFAULT_FILENAME,
  1038. sourceRoot = "",
  1039. pad = false,
  1040. ignoreEmpty = true,
  1041. compiler = CompilerDOM__namespace
  1042. } = {}) {
  1043. const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
  1044. const cache = parseCache.get(sourceKey);
  1045. if (cache) {
  1046. return cache;
  1047. }
  1048. const descriptor = {
  1049. filename,
  1050. source,
  1051. template: null,
  1052. script: null,
  1053. scriptSetup: null,
  1054. styles: [],
  1055. customBlocks: [],
  1056. cssVars: [],
  1057. slotted: false,
  1058. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1059. };
  1060. const errors = [];
  1061. const ast = compiler.parse(source, {
  1062. // there are no components at SFC parsing level
  1063. isNativeTag: () => true,
  1064. // preserve all whitespaces
  1065. isPreTag: () => true,
  1066. getTextMode: ({ tag, props }, parent) => {
  1067. if (!parent && tag !== "template" || // <template lang="xxx"> should also be treated as raw text
  1068. tag === "template" && props.some(
  1069. (p) => p.type === 6 && p.name === "lang" && p.value && p.value.content && p.value.content !== "html"
  1070. )) {
  1071. return 2;
  1072. } else {
  1073. return 0;
  1074. }
  1075. },
  1076. onError: (e) => {
  1077. errors.push(e);
  1078. }
  1079. });
  1080. ast.children.forEach((node) => {
  1081. if (node.type !== 1) {
  1082. return;
  1083. }
  1084. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1085. return;
  1086. }
  1087. switch (node.tag) {
  1088. case "template":
  1089. if (!descriptor.template) {
  1090. const templateBlock = descriptor.template = createBlock(
  1091. node,
  1092. source,
  1093. false
  1094. );
  1095. templateBlock.ast = node;
  1096. if (templateBlock.attrs.functional) {
  1097. const err = new SyntaxError(
  1098. `<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.`
  1099. );
  1100. err.loc = node.props.find((p) => p.name === "functional").loc;
  1101. errors.push(err);
  1102. }
  1103. } else {
  1104. errors.push(createDuplicateBlockError(node));
  1105. }
  1106. break;
  1107. case "script":
  1108. const scriptBlock = createBlock(node, source, pad);
  1109. const isSetup = !!scriptBlock.attrs.setup;
  1110. if (isSetup && !descriptor.scriptSetup) {
  1111. descriptor.scriptSetup = scriptBlock;
  1112. break;
  1113. }
  1114. if (!isSetup && !descriptor.script) {
  1115. descriptor.script = scriptBlock;
  1116. break;
  1117. }
  1118. errors.push(createDuplicateBlockError(node, isSetup));
  1119. break;
  1120. case "style":
  1121. const styleBlock = createBlock(node, source, pad);
  1122. if (styleBlock.attrs.vars) {
  1123. errors.push(
  1124. new SyntaxError(
  1125. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1126. )
  1127. );
  1128. }
  1129. descriptor.styles.push(styleBlock);
  1130. break;
  1131. default:
  1132. descriptor.customBlocks.push(createBlock(node, source, pad));
  1133. break;
  1134. }
  1135. });
  1136. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1137. errors.push(
  1138. new SyntaxError(
  1139. `At least one <template> or <script> is required in a single file component.`
  1140. )
  1141. );
  1142. }
  1143. if (descriptor.scriptSetup) {
  1144. if (descriptor.scriptSetup.src) {
  1145. errors.push(
  1146. new SyntaxError(
  1147. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1148. )
  1149. );
  1150. descriptor.scriptSetup = null;
  1151. }
  1152. if (descriptor.script && descriptor.script.src) {
  1153. errors.push(
  1154. new SyntaxError(
  1155. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1156. )
  1157. );
  1158. descriptor.script = null;
  1159. }
  1160. }
  1161. if (sourceMap) {
  1162. const genMap = (block) => {
  1163. if (block && !block.src) {
  1164. block.map = generateSourceMap(
  1165. filename,
  1166. source,
  1167. block.content,
  1168. sourceRoot,
  1169. !pad || block.type === "template" ? block.loc.start.line - 1 : 0
  1170. );
  1171. }
  1172. };
  1173. genMap(descriptor.template);
  1174. genMap(descriptor.script);
  1175. descriptor.styles.forEach(genMap);
  1176. descriptor.customBlocks.forEach(genMap);
  1177. }
  1178. descriptor.cssVars = parseCssVars(descriptor);
  1179. const slottedRE = /(?:::v-|:)slotted\(/;
  1180. descriptor.slotted = descriptor.styles.some(
  1181. (s) => s.scoped && slottedRE.test(s.content)
  1182. );
  1183. const result = {
  1184. descriptor,
  1185. errors
  1186. };
  1187. parseCache.set(sourceKey, result);
  1188. return result;
  1189. }
  1190. function createDuplicateBlockError(node, isScriptSetup = false) {
  1191. const err = new SyntaxError(
  1192. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1193. );
  1194. err.loc = node.loc;
  1195. return err;
  1196. }
  1197. function createBlock(node, source, pad) {
  1198. const type = node.tag;
  1199. let { start, end } = node.loc;
  1200. let content = "";
  1201. if (node.children.length) {
  1202. start = node.children[0].loc.start;
  1203. end = node.children[node.children.length - 1].loc.end;
  1204. content = source.slice(start.offset, end.offset);
  1205. } else {
  1206. const offset = node.loc.source.indexOf(`</`);
  1207. if (offset > -1) {
  1208. start = {
  1209. line: start.line,
  1210. column: start.column + offset,
  1211. offset: start.offset + offset
  1212. };
  1213. }
  1214. end = { ...start };
  1215. }
  1216. const loc = {
  1217. source: content,
  1218. start,
  1219. end
  1220. };
  1221. const attrs = {};
  1222. const block = {
  1223. type,
  1224. content,
  1225. loc,
  1226. attrs
  1227. };
  1228. if (pad) {
  1229. block.content = padContent(source, block, pad) + block.content;
  1230. }
  1231. node.props.forEach((p) => {
  1232. if (p.type === 6) {
  1233. attrs[p.name] = p.value ? p.value.content || true : true;
  1234. if (p.name === "lang") {
  1235. block.lang = p.value && p.value.content;
  1236. } else if (p.name === "src") {
  1237. block.src = p.value && p.value.content;
  1238. } else if (type === "style") {
  1239. if (p.name === "scoped") {
  1240. block.scoped = true;
  1241. } else if (p.name === "module") {
  1242. block.module = attrs[p.name];
  1243. }
  1244. } else if (type === "script" && p.name === "setup") {
  1245. block.setup = attrs.setup;
  1246. }
  1247. }
  1248. });
  1249. return block;
  1250. }
  1251. const splitRE = /\r?\n/g;
  1252. const emptyRE = /^(?:\/\/)?\s*$/;
  1253. const replaceRE = /./g;
  1254. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
  1255. const map = new sourceMapJs.SourceMapGenerator({
  1256. file: filename.replace(/\\/g, "/"),
  1257. sourceRoot: sourceRoot.replace(/\\/g, "/")
  1258. });
  1259. map.setSourceContent(filename, source);
  1260. generated.split(splitRE).forEach((line, index) => {
  1261. if (!emptyRE.test(line)) {
  1262. const originalLine = index + 1 + lineOffset;
  1263. const generatedLine = index + 1;
  1264. for (let i = 0; i < line.length; i++) {
  1265. if (!/\s/.test(line[i])) {
  1266. map.addMapping({
  1267. source: filename,
  1268. original: {
  1269. line: originalLine,
  1270. column: i
  1271. },
  1272. generated: {
  1273. line: generatedLine,
  1274. column: i
  1275. }
  1276. });
  1277. }
  1278. }
  1279. }
  1280. });
  1281. return JSON.parse(map.toString());
  1282. }
  1283. function padContent(content, block, pad) {
  1284. content = content.slice(0, block.loc.start.offset);
  1285. if (pad === "space") {
  1286. return content.replace(replaceRE, " ");
  1287. } else {
  1288. const offset = content.split(splitRE).length;
  1289. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  1290. return Array(offset).join(padChar);
  1291. }
  1292. }
  1293. function hasSrc(node) {
  1294. return node.props.some((p) => {
  1295. if (p.type !== 6) {
  1296. return false;
  1297. }
  1298. return p.name === "src";
  1299. });
  1300. }
  1301. function isEmpty(node) {
  1302. for (let i = 0; i < node.children.length; i++) {
  1303. const child = node.children[i];
  1304. if (child.type !== 2 || child.content.trim() !== "") {
  1305. return false;
  1306. }
  1307. }
  1308. return true;
  1309. }
  1310. function hmrShouldReload(prevImports, next) {
  1311. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  1312. return false;
  1313. }
  1314. for (const key in prevImports) {
  1315. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  1316. return true;
  1317. }
  1318. }
  1319. return false;
  1320. }
  1321. function isRelativeUrl(url) {
  1322. const firstChar = url.charAt(0);
  1323. return firstChar === "." || firstChar === "~" || firstChar === "@";
  1324. }
  1325. const externalRE = /^(https?:)?\/\//;
  1326. function isExternalUrl(url) {
  1327. return externalRE.test(url);
  1328. }
  1329. const dataUrlRE = /^\s*data:/i;
  1330. function isDataUrl(url) {
  1331. return dataUrlRE.test(url);
  1332. }
  1333. function parseUrl(url) {
  1334. const firstChar = url.charAt(0);
  1335. if (firstChar === "~") {
  1336. const secondChar = url.charAt(1);
  1337. url = url.slice(secondChar === "/" ? 2 : 1);
  1338. }
  1339. return parseUriParts(url);
  1340. }
  1341. function parseUriParts(urlString) {
  1342. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  1343. }
  1344. const defaultAssetUrlOptions = {
  1345. base: null,
  1346. includeAbsolute: false,
  1347. tags: {
  1348. video: ["src", "poster"],
  1349. source: ["src"],
  1350. img: ["src"],
  1351. image: ["xlink:href", "href"],
  1352. use: ["xlink:href", "href"]
  1353. }
  1354. };
  1355. const normalizeOptions = (options) => {
  1356. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  1357. return {
  1358. ...defaultAssetUrlOptions,
  1359. tags: options
  1360. };
  1361. }
  1362. return {
  1363. ...defaultAssetUrlOptions,
  1364. ...options
  1365. };
  1366. };
  1367. const createAssetUrlTransformWithOptions = (options) => {
  1368. return (node, context) => transformAssetUrl(node, context, options);
  1369. };
  1370. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  1371. if (node.type === 1) {
  1372. if (!node.props.length) {
  1373. return;
  1374. }
  1375. const tags = options.tags || defaultAssetUrlOptions.tags;
  1376. const attrs = tags[node.tag];
  1377. const wildCardAttrs = tags["*"];
  1378. if (!attrs && !wildCardAttrs) {
  1379. return;
  1380. }
  1381. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  1382. node.props.forEach((attr, index) => {
  1383. 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)) {
  1384. return;
  1385. }
  1386. const url = parseUrl(attr.value.content);
  1387. if (options.base && attr.value.content[0] === ".") {
  1388. const base = parseUrl(options.base);
  1389. const protocol = base.protocol || "";
  1390. const host = base.host ? protocol + "//" + base.host : "";
  1391. const basePath = base.path || "/";
  1392. attr.value.content = host + (path$3.posix || path$3).join(basePath, url.path + (url.hash || ""));
  1393. return;
  1394. }
  1395. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  1396. node.props[index] = {
  1397. type: 7,
  1398. name: "bind",
  1399. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  1400. exp,
  1401. modifiers: [],
  1402. loc: attr.loc
  1403. };
  1404. });
  1405. }
  1406. };
  1407. function getImportsExpressionExp(path2, hash, loc, context) {
  1408. if (path2) {
  1409. let name;
  1410. let exp;
  1411. const existingIndex = context.imports.findIndex((i) => i.path === path2);
  1412. if (existingIndex > -1) {
  1413. name = `_imports_${existingIndex}`;
  1414. exp = context.imports[existingIndex].exp;
  1415. } else {
  1416. name = `_imports_${context.imports.length}`;
  1417. exp = compilerCore.createSimpleExpression(
  1418. name,
  1419. false,
  1420. loc,
  1421. 3
  1422. );
  1423. context.imports.push({ exp, path: path2 });
  1424. }
  1425. if (!hash) {
  1426. return exp;
  1427. }
  1428. const hashExp = `${name} + '${hash}'`;
  1429. const finalExp = compilerCore.createSimpleExpression(
  1430. hashExp,
  1431. false,
  1432. loc,
  1433. 3
  1434. );
  1435. if (!context.hoistStatic) {
  1436. return finalExp;
  1437. }
  1438. const existingHoistIndex = context.hoists.findIndex((h) => {
  1439. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  1440. });
  1441. if (existingHoistIndex > -1) {
  1442. return compilerCore.createSimpleExpression(
  1443. `_hoisted_${existingHoistIndex + 1}`,
  1444. false,
  1445. loc,
  1446. 3
  1447. );
  1448. }
  1449. return context.hoist(finalExp);
  1450. } else {
  1451. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  1452. }
  1453. }
  1454. const srcsetTags = ["img", "source"];
  1455. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  1456. const createSrcsetTransformWithOptions = (options) => {
  1457. return (node, context) => transformSrcset(node, context, options);
  1458. };
  1459. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  1460. if (node.type === 1) {
  1461. if (srcsetTags.includes(node.tag) && node.props.length) {
  1462. node.props.forEach((attr, index) => {
  1463. if (attr.name === "srcset" && attr.type === 6) {
  1464. if (!attr.value)
  1465. return;
  1466. const value = attr.value.content;
  1467. if (!value)
  1468. return;
  1469. const imageCandidates = value.split(",").map((s) => {
  1470. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  1471. return { url, descriptor };
  1472. });
  1473. for (let i = 0; i < imageCandidates.length; i++) {
  1474. const { url } = imageCandidates[i];
  1475. if (isDataUrl(url)) {
  1476. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  1477. imageCandidates.splice(i, 1);
  1478. }
  1479. }
  1480. const shouldProcessUrl = (url) => {
  1481. return !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  1482. };
  1483. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  1484. return;
  1485. }
  1486. if (options.base) {
  1487. const base = options.base;
  1488. const set = [];
  1489. let needImportTransform = false;
  1490. imageCandidates.forEach((candidate) => {
  1491. let { url, descriptor } = candidate;
  1492. descriptor = descriptor ? ` ${descriptor}` : ``;
  1493. if (url[0] === ".") {
  1494. candidate.url = (path$3.posix || path$3).join(base, url);
  1495. set.push(candidate.url + descriptor);
  1496. } else if (shouldProcessUrl(url)) {
  1497. needImportTransform = true;
  1498. } else {
  1499. set.push(url + descriptor);
  1500. }
  1501. });
  1502. if (!needImportTransform) {
  1503. attr.value.content = set.join(", ");
  1504. return;
  1505. }
  1506. }
  1507. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  1508. imageCandidates.forEach(({ url, descriptor }, index2) => {
  1509. if (shouldProcessUrl(url)) {
  1510. const { path: path2 } = parseUrl(url);
  1511. let exp2;
  1512. if (path2) {
  1513. const existingImportsIndex = context.imports.findIndex(
  1514. (i) => i.path === path2
  1515. );
  1516. if (existingImportsIndex > -1) {
  1517. exp2 = compilerCore.createSimpleExpression(
  1518. `_imports_${existingImportsIndex}`,
  1519. false,
  1520. attr.loc,
  1521. 3
  1522. );
  1523. } else {
  1524. exp2 = compilerCore.createSimpleExpression(
  1525. `_imports_${context.imports.length}`,
  1526. false,
  1527. attr.loc,
  1528. 3
  1529. );
  1530. context.imports.push({ exp: exp2, path: path2 });
  1531. }
  1532. compoundExpression.children.push(exp2);
  1533. }
  1534. } else {
  1535. const exp2 = compilerCore.createSimpleExpression(
  1536. `"${url}"`,
  1537. false,
  1538. attr.loc,
  1539. 3
  1540. );
  1541. compoundExpression.children.push(exp2);
  1542. }
  1543. const isNotLast = imageCandidates.length - 1 > index2;
  1544. if (descriptor && isNotLast) {
  1545. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  1546. } else if (descriptor) {
  1547. compoundExpression.children.push(` + ' ${descriptor}'`);
  1548. } else if (isNotLast) {
  1549. compoundExpression.children.push(` + ', ' + `);
  1550. }
  1551. });
  1552. let exp = compoundExpression;
  1553. if (context.hoistStatic) {
  1554. exp = context.hoist(compoundExpression);
  1555. exp.constType = 3;
  1556. }
  1557. node.props[index] = {
  1558. type: 7,
  1559. name: "bind",
  1560. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  1561. exp,
  1562. modifiers: [],
  1563. loc: attr.loc
  1564. };
  1565. }
  1566. });
  1567. }
  1568. }
  1569. };
  1570. var consolidateExports$1 = {};
  1571. var consolidate$2 = {
  1572. get exports(){ return consolidateExports$1; },
  1573. set exports(v){ consolidateExports$1 = v; },
  1574. };
  1575. function commonjsRequire(path) {
  1576. 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.');
  1577. }
  1578. var consolidateExports = {};
  1579. var consolidate$1 = {
  1580. get exports(){ return consolidateExports; },
  1581. set exports(v){ consolidateExports = v; },
  1582. };
  1583. (function (module, exports) {
  1584. /*
  1585. * Engines which do not support caching of their file contents
  1586. * should use the `read()` function defined in consolidate.js
  1587. * On top of this, when an engine compiles to a `Function`,
  1588. * these functions should either be cached within consolidate.js
  1589. * or the engine itself via `options.cache`. This will allow
  1590. * users and frameworks to pass `options.cache = true` for
  1591. * `NODE_ENV=production`, however edit the file(s) without
  1592. * re-loading the application in development.
  1593. */
  1594. /**
  1595. * Module dependencies.
  1596. */
  1597. var fs = require$$0;
  1598. var path = path$3;
  1599. var util = require$$2;
  1600. var join = path.join;
  1601. var resolve = path.resolve;
  1602. var extname = path.extname;
  1603. var dirname = path.dirname;
  1604. var isAbsolute = path.isAbsolute;
  1605. var readCache = {};
  1606. /**
  1607. * Require cache.
  1608. */
  1609. var cacheStore = {};
  1610. /**
  1611. * Require cache.
  1612. */
  1613. var requires = {};
  1614. /**
  1615. * Clear the cache.
  1616. *
  1617. * @api public
  1618. */
  1619. exports.clearCache = function() {
  1620. readCache = {};
  1621. cacheStore = {};
  1622. };
  1623. /**
  1624. * Conditionally cache `compiled` template based
  1625. * on the `options` filename and `.cache` boolean.
  1626. *
  1627. * @param {Object} options
  1628. * @param {Function} compiled
  1629. * @return {Function}
  1630. * @api private
  1631. */
  1632. function cache(options, compiled) {
  1633. // cachable
  1634. if (compiled && options.filename && options.cache) {
  1635. delete readCache[options.filename];
  1636. cacheStore[options.filename] = compiled;
  1637. return compiled;
  1638. }
  1639. // check cache
  1640. if (options.filename && options.cache) {
  1641. return cacheStore[options.filename];
  1642. }
  1643. return compiled;
  1644. }
  1645. /**
  1646. * Read `path` with `options` with
  1647. * callback `(err, str)`. When `options.cache`
  1648. * is true the template string will be cached.
  1649. *
  1650. * @param {String} options
  1651. * @param {Function} cb
  1652. * @api private
  1653. */
  1654. function read(path, options, cb) {
  1655. var str = readCache[path];
  1656. var cached = options.cache && str && typeof str === 'string';
  1657. // cached (only if cached is a string and not a compiled template function)
  1658. if (cached) return cb(null, str);
  1659. // read
  1660. fs.readFile(path, 'utf8', function(err, str) {
  1661. if (err) return cb(err);
  1662. // remove extraneous utf8 BOM marker
  1663. str = str.replace(/^\uFEFF/, '');
  1664. if (options.cache) readCache[path] = str;
  1665. cb(null, str);
  1666. });
  1667. }
  1668. /**
  1669. * Read `path` with `options` with
  1670. * callback `(err, str)`. When `options.cache`
  1671. * is true the partial string will be cached.
  1672. *
  1673. * @param {String} options
  1674. * @param {Function} fn
  1675. * @api private
  1676. */
  1677. function readPartials(path, options, cb) {
  1678. if (!options.partials) return cb();
  1679. var keys = Object.keys(options.partials);
  1680. var partials = {};
  1681. function next(index) {
  1682. if (index === keys.length) return cb(null, partials);
  1683. var key = keys[index];
  1684. var partialPath = options.partials[key];
  1685. if (partialPath === undefined || partialPath === null || partialPath === false) {
  1686. return next(++index);
  1687. }
  1688. var file;
  1689. if (isAbsolute(partialPath)) {
  1690. if (extname(partialPath) !== '') {
  1691. file = partialPath;
  1692. } else {
  1693. file = join(partialPath + extname(path));
  1694. }
  1695. } else {
  1696. file = join(dirname(path), partialPath + extname(path));
  1697. }
  1698. read(file, options, function(err, str) {
  1699. if (err) return cb(err);
  1700. partials[key] = str;
  1701. next(++index);
  1702. });
  1703. }
  1704. next(0);
  1705. }
  1706. /**
  1707. * promisify
  1708. */
  1709. function promisify(cb, fn) {
  1710. return new Promise(function(resolve, reject) {
  1711. cb = cb || function(err, html) {
  1712. if (err) {
  1713. return reject(err);
  1714. }
  1715. resolve(html);
  1716. };
  1717. fn(cb);
  1718. });
  1719. }
  1720. /**
  1721. * fromStringRenderer
  1722. */
  1723. function fromStringRenderer(name) {
  1724. return function(path, options, cb) {
  1725. options.filename = path;
  1726. return promisify(cb, function(cb) {
  1727. readPartials(path, options, function(err, partials) {
  1728. var extend = (requires.extend || (requires.extend = require$$2._extend));
  1729. var opts = extend({}, options);
  1730. opts.partials = partials;
  1731. if (err) return cb(err);
  1732. if (cache(opts)) {
  1733. exports[name].render('', opts, cb);
  1734. } else {
  1735. read(path, opts, function(err, str) {
  1736. if (err) return cb(err);
  1737. exports[name].render(str, opts, cb);
  1738. });
  1739. }
  1740. });
  1741. });
  1742. };
  1743. }
  1744. /**
  1745. * velocity support.
  1746. */
  1747. exports.velocityjs = fromStringRenderer('velocityjs');
  1748. /**
  1749. * velocity string support.
  1750. */
  1751. exports.velocityjs.render = function(str, options, cb) {
  1752. return promisify(cb, function(cb) {
  1753. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  1754. try {
  1755. options.locals = options;
  1756. cb(null, engine.render(str, options).trimLeft());
  1757. } catch (err) {
  1758. cb(err);
  1759. }
  1760. });
  1761. };
  1762. /**
  1763. * Liquid support.
  1764. */
  1765. exports.liquid = fromStringRenderer('liquid');
  1766. /**
  1767. * Liquid string support.
  1768. */
  1769. /**
  1770. * Note that in order to get filters and custom tags we've had to push
  1771. * all user-defined locals down into @locals. However, just to make things
  1772. * backwards-compatible, any property of `options` that is left after
  1773. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  1774. * `includeDir` will also become a local.
  1775. */
  1776. function _renderTinyliquid(engine, str, options, cb) {
  1777. var context = engine.newContext();
  1778. var k;
  1779. /**
  1780. * Note that there's a bug in the library that doesn't allow us to pass
  1781. * the locals to newContext(), hence looping through the keys:
  1782. */
  1783. if (options.locals) {
  1784. for (k in options.locals) {
  1785. context.setLocals(k, options.locals[k]);
  1786. }
  1787. delete options.locals;
  1788. }
  1789. if (options.meta) {
  1790. context.setLocals('page', options.meta);
  1791. delete options.meta;
  1792. }
  1793. /**
  1794. * Add any defined filters:
  1795. */
  1796. if (options.filters) {
  1797. for (k in options.filters) {
  1798. context.setFilter(k, options.filters[k]);
  1799. }
  1800. delete options.filters;
  1801. }
  1802. /**
  1803. * Set up a callback for the include directory:
  1804. */
  1805. var includeDir = options.includeDir || process.cwd();
  1806. context.onInclude(function(name, callback) {
  1807. var extname = path.extname(name) ? '' : '.liquid';
  1808. var filename = path.resolve(includeDir, name + extname);
  1809. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  1810. if (err) return callback(err);
  1811. callback(null, engine.parse(data));
  1812. });
  1813. });
  1814. delete options.includeDir;
  1815. /**
  1816. * The custom tag functions need to have their results pushed back
  1817. * through the parser, so set up a shim before calling the provided
  1818. * callback:
  1819. */
  1820. var compileOptions = {
  1821. customTags: {}
  1822. };
  1823. if (options.customTags) {
  1824. var tagFunctions = options.customTags;
  1825. for (k in options.customTags) {
  1826. /*Tell jshint there's no problem with having this function in the loop */
  1827. /*jshint -W083 */
  1828. compileOptions.customTags[k] = function(context, name, body) {
  1829. var tpl = tagFunctions[name](body.trim());
  1830. context.astStack.push(engine.parse(tpl));
  1831. };
  1832. /*jshint +W083 */
  1833. }
  1834. delete options.customTags;
  1835. }
  1836. /**
  1837. * Now anything left in `options` becomes a local:
  1838. */
  1839. for (k in options) {
  1840. context.setLocals(k, options[k]);
  1841. }
  1842. /**
  1843. * Finally, execute the template:
  1844. */
  1845. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  1846. tmpl(context, cb);
  1847. }
  1848. exports.liquid.render = function(str, options, cb) {
  1849. return promisify(cb, function(cb) {
  1850. var engine = requires.liquid;
  1851. var Liquid;
  1852. try {
  1853. // set up tinyliquid engine
  1854. engine = requires.liquid = require('tinyliquid');
  1855. // use tinyliquid engine
  1856. _renderTinyliquid(engine, str, options, cb);
  1857. return;
  1858. } catch (err) {
  1859. // set up liquid-node engine
  1860. try {
  1861. Liquid = requires.liquid = require('liquid-node');
  1862. engine = new Liquid.Engine();
  1863. } catch (err) {
  1864. throw err;
  1865. }
  1866. }
  1867. // use liquid-node engine
  1868. try {
  1869. var locals = options.locals || {};
  1870. if (options.meta) {
  1871. locals.pages = options.meta;
  1872. delete options.meta;
  1873. }
  1874. /**
  1875. * Add any defined filters:
  1876. */
  1877. if (options.filters) {
  1878. engine.registerFilters(options.filters);
  1879. delete options.filters;
  1880. }
  1881. /**
  1882. * Set up a callback for the include directory:
  1883. */
  1884. var includeDir = options.includeDir || process.cwd();
  1885. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  1886. delete options.includeDir;
  1887. /**
  1888. * The custom tag functions need to have their results pushed back
  1889. * through the parser, so set up a shim before calling the provided
  1890. * callback:
  1891. */
  1892. if (options.customTags) {
  1893. var tagFunctions = options.customTags;
  1894. for (k in options.customTags) {
  1895. engine.registerTag(k, tagFunctions[k]);
  1896. }
  1897. delete options.customTags;
  1898. }
  1899. /**
  1900. * Now anything left in `options` becomes a local:
  1901. */
  1902. for (var k in options) {
  1903. locals[k] = options[k];
  1904. }
  1905. /**
  1906. * Finally, execute the template:
  1907. */
  1908. return engine
  1909. .parseAndRender(str, locals)
  1910. .nodeify(function(err, result) {
  1911. if (err) {
  1912. throw new Error(err);
  1913. } else {
  1914. return cb(null, result);
  1915. }
  1916. });
  1917. } catch (err) {
  1918. cb(err);
  1919. }
  1920. });
  1921. };
  1922. /**
  1923. * Jade support.
  1924. */
  1925. exports.jade = function(path, options, cb) {
  1926. return promisify(cb, function(cb) {
  1927. var engine = requires.jade;
  1928. if (!engine) {
  1929. try {
  1930. engine = requires.jade = require('jade');
  1931. } catch (err) {
  1932. try {
  1933. engine = requires.jade = require('then-jade');
  1934. } catch (otherError) {
  1935. throw err;
  1936. }
  1937. }
  1938. }
  1939. try {
  1940. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  1941. cb(null, tmpl(options));
  1942. } catch (err) {
  1943. cb(err);
  1944. }
  1945. });
  1946. };
  1947. /**
  1948. * Jade string support.
  1949. */
  1950. exports.jade.render = function(str, options, cb) {
  1951. return promisify(cb, function(cb) {
  1952. var engine = requires.jade;
  1953. if (!engine) {
  1954. try {
  1955. engine = requires.jade = require('jade');
  1956. } catch (err) {
  1957. try {
  1958. engine = requires.jade = require('then-jade');
  1959. } catch (otherError) {
  1960. throw err;
  1961. }
  1962. }
  1963. }
  1964. try {
  1965. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  1966. cb(null, tmpl(options));
  1967. } catch (err) {
  1968. cb(err);
  1969. }
  1970. });
  1971. };
  1972. /**
  1973. * Dust support.
  1974. */
  1975. exports.dust = fromStringRenderer('dust');
  1976. /**
  1977. * Dust string support.
  1978. */
  1979. exports.dust.render = function(str, options, cb) {
  1980. return promisify(cb, function(cb) {
  1981. var engine = requires.dust;
  1982. if (!engine) {
  1983. try {
  1984. engine = requires.dust = require('dust');
  1985. } catch (err) {
  1986. try {
  1987. engine = requires.dust = require('dustjs-helpers');
  1988. } catch (err) {
  1989. engine = requires.dust = require('dustjs-linkedin');
  1990. }
  1991. }
  1992. }
  1993. var ext = 'dust';
  1994. var views = '.';
  1995. if (options) {
  1996. if (options.ext) ext = options.ext;
  1997. if (options.views) views = options.views;
  1998. if (options.settings && options.settings.views) views = options.settings.views;
  1999. }
  2000. if (!options || (options && !options.cache)) engine.cache = {};
  2001. engine.onLoad = function(path, callback) {
  2002. if (extname(path) === '') path += '.' + ext;
  2003. if (path[0] !== '/') path = views + '/' + path;
  2004. read(path, options, callback);
  2005. };
  2006. try {
  2007. var templateName;
  2008. if (options.filename) {
  2009. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2010. }
  2011. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2012. tmpl(options, cb);
  2013. } catch (err) {
  2014. cb(err);
  2015. }
  2016. });
  2017. };
  2018. /**
  2019. * Swig support.
  2020. */
  2021. exports.swig = fromStringRenderer('swig');
  2022. /**
  2023. * Swig string support.
  2024. */
  2025. exports.swig.render = function(str, options, cb) {
  2026. return promisify(cb, function(cb) {
  2027. var engine = requires.swig;
  2028. if (!engine) {
  2029. try {
  2030. engine = requires.swig = require('swig');
  2031. } catch (err) {
  2032. try {
  2033. engine = requires.swig = require('swig-templates');
  2034. } catch (otherError) {
  2035. throw err;
  2036. }
  2037. }
  2038. }
  2039. try {
  2040. if (options.cache === true) options.cache = 'memory';
  2041. engine.setDefaults({ cache: options.cache });
  2042. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2043. cb(null, tmpl(options));
  2044. } catch (err) {
  2045. cb(err);
  2046. }
  2047. });
  2048. };
  2049. /**
  2050. * Razor support.
  2051. */
  2052. exports.razor = function(path, options, cb) {
  2053. return promisify(cb, function(cb) {
  2054. var engine = requires.razor;
  2055. if (!engine) {
  2056. try {
  2057. engine = requires.razor = require('razor-tmpl');
  2058. } catch (err) {
  2059. throw err;
  2060. }
  2061. }
  2062. try {
  2063. var tmpl = cache(options) || cache(options, (locals) => {
  2064. console.log('Rendering razor file', path);
  2065. return engine.renderFileSync(path, locals);
  2066. });
  2067. cb(null, tmpl(options));
  2068. } catch (err) {
  2069. cb(err);
  2070. }
  2071. });
  2072. };
  2073. /**
  2074. * razor string support.
  2075. */
  2076. exports.razor.render = function(str, options, cb) {
  2077. return promisify(cb, function(cb) {
  2078. try {
  2079. var engine = requires.razor = require('razor-tmpl');
  2080. } catch (err) {
  2081. throw err;
  2082. }
  2083. try {
  2084. var tf = engine.compile(str);
  2085. var tmpl = cache(options) || cache(options, tf);
  2086. cb(null, tmpl(options));
  2087. } catch (err) {
  2088. cb(err);
  2089. }
  2090. });
  2091. };
  2092. /**
  2093. * Atpl support.
  2094. */
  2095. exports.atpl = fromStringRenderer('atpl');
  2096. /**
  2097. * Atpl string support.
  2098. */
  2099. exports.atpl.render = function(str, options, cb) {
  2100. return promisify(cb, function(cb) {
  2101. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2102. try {
  2103. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2104. cb(null, tmpl(options));
  2105. } catch (err) {
  2106. cb(err);
  2107. }
  2108. });
  2109. };
  2110. /**
  2111. * Liquor support,
  2112. */
  2113. exports.liquor = fromStringRenderer('liquor');
  2114. /**
  2115. * Liquor string support.
  2116. */
  2117. exports.liquor.render = function(str, options, cb) {
  2118. return promisify(cb, function(cb) {
  2119. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2120. try {
  2121. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2122. cb(null, tmpl(options));
  2123. } catch (err) {
  2124. cb(err);
  2125. }
  2126. });
  2127. };
  2128. /**
  2129. * Twig support.
  2130. */
  2131. exports.twig = fromStringRenderer('twig');
  2132. /**
  2133. * Twig string support.
  2134. */
  2135. exports.twig.render = function(str, options, cb) {
  2136. return promisify(cb, function(cb) {
  2137. var engine = requires.twig || (requires.twig = require('twig').twig);
  2138. var templateData = {
  2139. data: str,
  2140. allowInlineIncludes: options.allowInlineIncludes,
  2141. namespaces: options.namespaces,
  2142. path: options.path
  2143. };
  2144. try {
  2145. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2146. cb(null, tmpl.render(options));
  2147. } catch (err) {
  2148. cb(err);
  2149. }
  2150. });
  2151. };
  2152. /**
  2153. * EJS support.
  2154. */
  2155. exports.ejs = fromStringRenderer('ejs');
  2156. /**
  2157. * EJS string support.
  2158. */
  2159. exports.ejs.render = function(str, options, cb) {
  2160. return promisify(cb, function(cb) {
  2161. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2162. try {
  2163. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2164. cb(null, tmpl(options));
  2165. } catch (err) {
  2166. cb(err);
  2167. }
  2168. });
  2169. };
  2170. /**
  2171. * Eco support.
  2172. */
  2173. exports.eco = fromStringRenderer('eco');
  2174. /**
  2175. * Eco string support.
  2176. */
  2177. exports.eco.render = function(str, options, cb) {
  2178. return promisify(cb, function(cb) {
  2179. var engine = requires.eco || (requires.eco = require('eco'));
  2180. try {
  2181. cb(null, engine.render(str, options));
  2182. } catch (err) {
  2183. cb(err);
  2184. }
  2185. });
  2186. };
  2187. /**
  2188. * Jazz support.
  2189. */
  2190. exports.jazz = fromStringRenderer('jazz');
  2191. /**
  2192. * Jazz string support.
  2193. */
  2194. exports.jazz.render = function(str, options, cb) {
  2195. return promisify(cb, function(cb) {
  2196. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2197. try {
  2198. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2199. tmpl.eval(options, function(str) {
  2200. cb(null, str);
  2201. });
  2202. } catch (err) {
  2203. cb(err);
  2204. }
  2205. });
  2206. };
  2207. /**
  2208. * JQTPL support.
  2209. */
  2210. exports.jqtpl = fromStringRenderer('jqtpl');
  2211. /**
  2212. * JQTPL string support.
  2213. */
  2214. exports.jqtpl.render = function(str, options, cb) {
  2215. return promisify(cb, function(cb) {
  2216. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2217. try {
  2218. engine.template(str, str);
  2219. cb(null, engine.tmpl(str, options));
  2220. } catch (err) {
  2221. cb(err);
  2222. }
  2223. });
  2224. };
  2225. /**
  2226. * Haml support.
  2227. */
  2228. exports.haml = fromStringRenderer('haml');
  2229. /**
  2230. * Haml string support.
  2231. */
  2232. exports.haml.render = function(str, options, cb) {
  2233. return promisify(cb, function(cb) {
  2234. var engine = requires.haml || (requires.haml = require('hamljs'));
  2235. try {
  2236. options.locals = options;
  2237. cb(null, engine.render(str, options).trimLeft());
  2238. } catch (err) {
  2239. cb(err);
  2240. }
  2241. });
  2242. };
  2243. /**
  2244. * Hamlet support.
  2245. */
  2246. exports.hamlet = fromStringRenderer('hamlet');
  2247. /**
  2248. * Hamlet string support.
  2249. */
  2250. exports.hamlet.render = function(str, options, cb) {
  2251. return promisify(cb, function(cb) {
  2252. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  2253. try {
  2254. options.locals = options;
  2255. cb(null, engine.render(str, options).trimLeft());
  2256. } catch (err) {
  2257. cb(err);
  2258. }
  2259. });
  2260. };
  2261. /**
  2262. * Whiskers support.
  2263. */
  2264. exports.whiskers = function(path, options, cb) {
  2265. return promisify(cb, function(cb) {
  2266. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  2267. engine.__express(path, options, cb);
  2268. });
  2269. };
  2270. /**
  2271. * Whiskers string support.
  2272. */
  2273. exports.whiskers.render = function(str, options, cb) {
  2274. return promisify(cb, function(cb) {
  2275. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  2276. try {
  2277. cb(null, engine.render(str, options));
  2278. } catch (err) {
  2279. cb(err);
  2280. }
  2281. });
  2282. };
  2283. /**
  2284. * Coffee-HAML support.
  2285. */
  2286. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  2287. /**
  2288. * Coffee-HAML string support.
  2289. */
  2290. exports['haml-coffee'].render = function(str, options, cb) {
  2291. return promisify(cb, function(cb) {
  2292. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  2293. try {
  2294. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2295. cb(null, tmpl(options));
  2296. } catch (err) {
  2297. cb(err);
  2298. }
  2299. });
  2300. };
  2301. /**
  2302. * Hogan support.
  2303. */
  2304. exports.hogan = fromStringRenderer('hogan');
  2305. /**
  2306. * Hogan string support.
  2307. */
  2308. exports.hogan.render = function(str, options, cb) {
  2309. return promisify(cb, function(cb) {
  2310. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  2311. try {
  2312. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2313. cb(null, tmpl.render(options, options.partials));
  2314. } catch (err) {
  2315. cb(err);
  2316. }
  2317. });
  2318. };
  2319. /**
  2320. * templayed.js support.
  2321. */
  2322. exports.templayed = fromStringRenderer('templayed');
  2323. /**
  2324. * templayed.js string support.
  2325. */
  2326. exports.templayed.render = function(str, options, cb) {
  2327. return promisify(cb, function(cb) {
  2328. var engine = requires.templayed || (requires.templayed = require('templayed'));
  2329. try {
  2330. var tmpl = cache(options) || cache(options, engine(str));
  2331. cb(null, tmpl(options));
  2332. } catch (err) {
  2333. cb(err);
  2334. }
  2335. });
  2336. };
  2337. /**
  2338. * Handlebars support.
  2339. */
  2340. exports.handlebars = fromStringRenderer('handlebars');
  2341. /**
  2342. * Handlebars string support.
  2343. */
  2344. exports.handlebars.render = function(str, options, cb) {
  2345. return promisify(cb, function(cb) {
  2346. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  2347. try {
  2348. for (var partial in options.partials) {
  2349. engine.registerPartial(partial, options.partials[partial]);
  2350. }
  2351. for (var helper in options.helpers) {
  2352. engine.registerHelper(helper, options.helpers[helper]);
  2353. }
  2354. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2355. cb(null, tmpl(options));
  2356. } catch (err) {
  2357. cb(err);
  2358. }
  2359. });
  2360. };
  2361. /**
  2362. * Underscore support.
  2363. */
  2364. exports.underscore = fromStringRenderer('underscore');
  2365. /**
  2366. * Underscore string support.
  2367. */
  2368. exports.underscore.render = function(str, options, cb) {
  2369. return promisify(cb, function(cb) {
  2370. var engine = requires.underscore || (requires.underscore = require('underscore'));
  2371. try {
  2372. const partials = {};
  2373. for (var partial in options.partials) {
  2374. partials[partial] = engine.template(options.partials[partial]);
  2375. }
  2376. options.partials = partials;
  2377. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  2378. cb(null, tmpl(options).replace(/\n$/, ''));
  2379. } catch (err) {
  2380. cb(err);
  2381. }
  2382. });
  2383. };
  2384. /**
  2385. * Lodash support.
  2386. */
  2387. exports.lodash = fromStringRenderer('lodash');
  2388. /**
  2389. * Lodash string support.
  2390. */
  2391. exports.lodash.render = function(str, options, cb) {
  2392. return promisify(cb, function(cb) {
  2393. var engine = requires.lodash || (requires.lodash = require('lodash'));
  2394. try {
  2395. var tmpl = cache(options) || cache(options, engine.template(str, options));
  2396. cb(null, tmpl(options).replace(/\n$/, ''));
  2397. } catch (err) {
  2398. cb(err);
  2399. }
  2400. });
  2401. };
  2402. /**
  2403. * Pug support. (formerly Jade)
  2404. */
  2405. exports.pug = function(path, options, cb) {
  2406. return promisify(cb, function(cb) {
  2407. var engine = requires.pug;
  2408. if (!engine) {
  2409. try {
  2410. engine = requires.pug = require('pug');
  2411. } catch (err) {
  2412. try {
  2413. engine = requires.pug = require('then-pug');
  2414. } catch (otherError) {
  2415. throw err;
  2416. }
  2417. }
  2418. }
  2419. try {
  2420. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2421. cb(null, tmpl(options));
  2422. } catch (err) {
  2423. cb(err);
  2424. }
  2425. });
  2426. };
  2427. /**
  2428. * Pug string support.
  2429. */
  2430. exports.pug.render = function(str, options, cb) {
  2431. return promisify(cb, function(cb) {
  2432. var engine = requires.pug;
  2433. if (!engine) {
  2434. try {
  2435. engine = requires.pug = require('pug');
  2436. } catch (err) {
  2437. try {
  2438. engine = requires.pug = require('then-pug');
  2439. } catch (otherError) {
  2440. throw err;
  2441. }
  2442. }
  2443. }
  2444. try {
  2445. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2446. cb(null, tmpl(options));
  2447. } catch (err) {
  2448. cb(err);
  2449. }
  2450. });
  2451. };
  2452. /**
  2453. * QEJS support.
  2454. */
  2455. exports.qejs = fromStringRenderer('qejs');
  2456. /**
  2457. * QEJS string support.
  2458. */
  2459. exports.qejs.render = function(str, options, cb) {
  2460. return promisify(cb, function(cb) {
  2461. try {
  2462. var engine = requires.qejs || (requires.qejs = require('qejs'));
  2463. engine.render(str, options).then(function(result) {
  2464. cb(null, result);
  2465. }, function(err) {
  2466. cb(err);
  2467. }).done();
  2468. } catch (err) {
  2469. cb(err);
  2470. }
  2471. });
  2472. };
  2473. /**
  2474. * Walrus support.
  2475. */
  2476. exports.walrus = fromStringRenderer('walrus');
  2477. /**
  2478. * Walrus string support.
  2479. */
  2480. exports.walrus.render = function(str, options, cb) {
  2481. return promisify(cb, function(cb) {
  2482. var engine = requires.walrus || (requires.walrus = require('walrus'));
  2483. try {
  2484. var tmpl = cache(options) || cache(options, engine.parse(str));
  2485. cb(null, tmpl.compile(options));
  2486. } catch (err) {
  2487. cb(err);
  2488. }
  2489. });
  2490. };
  2491. /**
  2492. * Mustache support.
  2493. */
  2494. exports.mustache = fromStringRenderer('mustache');
  2495. /**
  2496. * Mustache string support.
  2497. */
  2498. exports.mustache.render = function(str, options, cb) {
  2499. return promisify(cb, function(cb) {
  2500. var engine = requires.mustache || (requires.mustache = require('mustache'));
  2501. try {
  2502. cb(null, engine.render(str, options, options.partials));
  2503. } catch (err) {
  2504. cb(err);
  2505. }
  2506. });
  2507. };
  2508. /**
  2509. * Just support.
  2510. */
  2511. exports.just = function(path, options, cb) {
  2512. return promisify(cb, function(cb) {
  2513. var engine = requires.just;
  2514. if (!engine) {
  2515. var JUST = require('just');
  2516. engine = requires.just = new JUST();
  2517. }
  2518. engine.configure({ useCache: options.cache });
  2519. engine.render(path, options, cb);
  2520. });
  2521. };
  2522. /**
  2523. * Just string support.
  2524. */
  2525. exports.just.render = function(str, options, cb) {
  2526. return promisify(cb, function(cb) {
  2527. var JUST = require('just');
  2528. var engine = new JUST({ root: { page: str }});
  2529. engine.render('page', options, cb);
  2530. });
  2531. };
  2532. /**
  2533. * ECT support.
  2534. */
  2535. exports.ect = function(path, options, cb) {
  2536. return promisify(cb, function(cb) {
  2537. var engine = requires.ect;
  2538. if (!engine) {
  2539. var ECT = require('ect');
  2540. engine = requires.ect = new ECT(options);
  2541. }
  2542. engine.configure({ cache: options.cache });
  2543. engine.render(path, options, cb);
  2544. });
  2545. };
  2546. /**
  2547. * ECT string support.
  2548. */
  2549. exports.ect.render = function(str, options, cb) {
  2550. return promisify(cb, function(cb) {
  2551. var ECT = require('ect');
  2552. var engine = new ECT({ root: { page: str }});
  2553. engine.render('page', options, cb);
  2554. });
  2555. };
  2556. /**
  2557. * mote support.
  2558. */
  2559. exports.mote = fromStringRenderer('mote');
  2560. /**
  2561. * mote string support.
  2562. */
  2563. exports.mote.render = function(str, options, cb) {
  2564. return promisify(cb, function(cb) {
  2565. var engine = requires.mote || (requires.mote = require('mote'));
  2566. try {
  2567. var tmpl = cache(options) || cache(options, engine.compile(str));
  2568. cb(null, tmpl(options));
  2569. } catch (err) {
  2570. cb(err);
  2571. }
  2572. });
  2573. };
  2574. /**
  2575. * Toffee support.
  2576. */
  2577. exports.toffee = function(path, options, cb) {
  2578. return promisify(cb, function(cb) {
  2579. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  2580. toffee.__consolidate_engine_render(path, options, cb);
  2581. });
  2582. };
  2583. /**
  2584. * Toffee string support.
  2585. */
  2586. exports.toffee.render = function(str, options, cb) {
  2587. return promisify(cb, function(cb) {
  2588. var engine = requires.toffee || (requires.toffee = require('toffee'));
  2589. try {
  2590. engine.str_render(str, options, cb);
  2591. } catch (err) {
  2592. cb(err);
  2593. }
  2594. });
  2595. };
  2596. /**
  2597. * doT support.
  2598. */
  2599. exports.dot = fromStringRenderer('dot');
  2600. /**
  2601. * doT string support.
  2602. */
  2603. exports.dot.render = function(str, options, cb) {
  2604. return promisify(cb, function(cb) {
  2605. var engine = requires.dot || (requires.dot = require('dot'));
  2606. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2607. try {
  2608. var settings = {};
  2609. settings = extend(settings, engine.templateSettings);
  2610. settings = extend(settings, options ? options.dot : {});
  2611. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  2612. cb(null, tmpl(options));
  2613. } catch (err) {
  2614. cb(err);
  2615. }
  2616. });
  2617. };
  2618. /**
  2619. * bracket support.
  2620. */
  2621. exports.bracket = fromStringRenderer('bracket');
  2622. /**
  2623. * bracket string support.
  2624. */
  2625. exports.bracket.render = function(str, options, cb) {
  2626. return promisify(cb, function(cb) {
  2627. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  2628. try {
  2629. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  2630. cb(null, tmpl(options));
  2631. } catch (err) {
  2632. cb(err);
  2633. }
  2634. });
  2635. };
  2636. /**
  2637. * Ractive support.
  2638. */
  2639. exports.ractive = fromStringRenderer('ractive');
  2640. /**
  2641. * Ractive string support.
  2642. */
  2643. exports.ractive.render = function(str, options, cb) {
  2644. return promisify(cb, function(cb) {
  2645. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  2646. var template = cache(options) || cache(options, Engine.parse(str));
  2647. options.template = template;
  2648. if (options.data === null || options.data === undefined) {
  2649. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2650. // Shallow clone the options object
  2651. options.data = extend({}, options);
  2652. // Remove consolidate-specific properties from the clone
  2653. var i;
  2654. var length;
  2655. var properties = ['template', 'filename', 'cache', 'partials'];
  2656. for (i = 0, length = properties.length; i < length; i++) {
  2657. var property = properties[i];
  2658. delete options.data[property];
  2659. }
  2660. }
  2661. try {
  2662. cb(null, new Engine(options).toHTML());
  2663. } catch (err) {
  2664. cb(err);
  2665. }
  2666. });
  2667. };
  2668. /**
  2669. * Nunjucks support.
  2670. */
  2671. exports.nunjucks = fromStringRenderer('nunjucks');
  2672. /**
  2673. * Nunjucks string support.
  2674. */
  2675. exports.nunjucks.render = function(str, options, cb) {
  2676. return promisify(cb, function(cb) {
  2677. try {
  2678. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  2679. var env = engine;
  2680. // deprecated fallback support for express
  2681. // <https://github.com/tj/consolidate.js/pull/152>
  2682. // <https://github.com/tj/consolidate.js/pull/224>
  2683. if (options.settings && options.settings.views) {
  2684. env = engine.configure(options.settings.views);
  2685. } else if (options.nunjucks && options.nunjucks.configure) {
  2686. env = engine.configure.apply(engine, options.nunjucks.configure);
  2687. }
  2688. //
  2689. // because `renderString` does not initiate loaders
  2690. // we must manually create a loader for it based off
  2691. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  2692. //
  2693. // <https://github.com/mozilla/nunjucks/issues/730>
  2694. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  2695. //
  2696. // so instead we simply check if we passed a custom loader
  2697. // otherwise we create a simple file based loader
  2698. if (options.loader) {
  2699. env = new engine.Environment(options.loader);
  2700. } else if (options.settings && options.settings.views) {
  2701. env = new engine.Environment(
  2702. new engine.FileSystemLoader(options.settings.views)
  2703. );
  2704. } else if (options.nunjucks && options.nunjucks.loader) {
  2705. if (typeof options.nunjucks.loader === 'string') {
  2706. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  2707. } else {
  2708. env = new engine.Environment(
  2709. new engine.FileSystemLoader(
  2710. options.nunjucks.loader[0],
  2711. options.nunjucks.loader[1]
  2712. )
  2713. );
  2714. }
  2715. }
  2716. env.renderString(str, options, cb);
  2717. } catch (err) {
  2718. throw cb(err);
  2719. }
  2720. });
  2721. };
  2722. /**
  2723. * HTMLing support.
  2724. */
  2725. exports.htmling = fromStringRenderer('htmling');
  2726. /**
  2727. * HTMLing string support.
  2728. */
  2729. exports.htmling.render = function(str, options, cb) {
  2730. return promisify(cb, function(cb) {
  2731. var engine = requires.htmling || (requires.htmling = require('htmling'));
  2732. try {
  2733. var tmpl = cache(options) || cache(options, engine.string(str));
  2734. cb(null, tmpl.render(options));
  2735. } catch (err) {
  2736. cb(err);
  2737. }
  2738. });
  2739. };
  2740. /**
  2741. * Rendering function
  2742. */
  2743. function requireReact(module, filename) {
  2744. var babel = requires.babel || (requires.babel = require('babel-core'));
  2745. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  2746. return module._compile(compiled, filename);
  2747. }
  2748. exports.requireReact = requireReact;
  2749. /**
  2750. * Converting a string into a node module.
  2751. */
  2752. function requireReactString(src, filename) {
  2753. var babel = requires.babel || (requires.babel = require('babel-core'));
  2754. if (!filename) filename = '';
  2755. var m = new module.constructor();
  2756. filename = filename || '';
  2757. // Compile Using React
  2758. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  2759. // Compile as a module
  2760. m.paths = module.paths;
  2761. m._compile(compiled, filename);
  2762. return m.exports;
  2763. }
  2764. /**
  2765. * A naive helper to replace {{tags}} with options.tags content
  2766. */
  2767. function reactBaseTmpl(data, options) {
  2768. var exp;
  2769. var regex;
  2770. // Iterates through the keys in file object
  2771. // and interpolate / replace {{key}} with it's value
  2772. for (var k in options) {
  2773. if (options.hasOwnProperty(k)) {
  2774. exp = '{{' + k + '}}';
  2775. regex = new RegExp(exp, 'g');
  2776. if (data.match(regex)) {
  2777. data = data.replace(regex, options[k]);
  2778. }
  2779. }
  2780. }
  2781. return data;
  2782. }
  2783. /**
  2784. * Plates Support.
  2785. */
  2786. exports.plates = fromStringRenderer('plates');
  2787. /**
  2788. * Plates string support.
  2789. */
  2790. exports.plates.render = function(str, options, cb) {
  2791. return promisify(cb, function(cb) {
  2792. var engine = requires.plates || (requires.plates = require('plates'));
  2793. var map = options.map || undefined;
  2794. try {
  2795. var tmpl = engine.bind(str, options, map);
  2796. cb(null, tmpl);
  2797. } catch (err) {
  2798. cb(err);
  2799. }
  2800. });
  2801. };
  2802. /**
  2803. * The main render parser for React bsaed templates
  2804. */
  2805. function reactRenderer(type) {
  2806. if (commonjsRequire.extensions) {
  2807. // Ensure JSX is transformed on require
  2808. if (!commonjsRequire.extensions['.jsx']) {
  2809. commonjsRequire.extensions['.jsx'] = requireReact;
  2810. }
  2811. // Supporting .react extension as well as test cases
  2812. // Using .react extension is not recommended.
  2813. if (!commonjsRequire.extensions['.react']) {
  2814. commonjsRequire.extensions['.react'] = requireReact;
  2815. }
  2816. }
  2817. // Return rendering fx
  2818. return function(str, options, cb) {
  2819. return promisify(cb, function(cb) {
  2820. // React Import
  2821. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  2822. var react = requires.react || (requires.react = require('react'));
  2823. // Assign HTML Base
  2824. var base = options.base;
  2825. delete options.base;
  2826. var enableCache = options.cache;
  2827. delete options.cache;
  2828. var isNonStatic = options.isNonStatic;
  2829. delete options.isNonStatic;
  2830. // Start Conversion
  2831. try {
  2832. var Code;
  2833. var Factory;
  2834. var baseStr;
  2835. var content;
  2836. var parsed;
  2837. if (!cache(options)) {
  2838. // Parsing
  2839. if (type === 'path') {
  2840. var path = resolve(str);
  2841. delete require.cache[path];
  2842. Code = commonjsRequire(path);
  2843. } else {
  2844. Code = requireReactString(str);
  2845. }
  2846. Factory = cache(options, react.createFactory(Code));
  2847. } else {
  2848. Factory = cache(options);
  2849. }
  2850. parsed = new Factory(options);
  2851. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  2852. if (base) {
  2853. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  2854. if (enableCache) {
  2855. readCache[str] = baseStr;
  2856. }
  2857. options.content = content;
  2858. content = reactBaseTmpl(baseStr, options);
  2859. }
  2860. cb(null, content);
  2861. } catch (err) {
  2862. cb(err);
  2863. }
  2864. });
  2865. };
  2866. }
  2867. /**
  2868. * React JS Support
  2869. */
  2870. exports.react = reactRenderer('path');
  2871. /**
  2872. * React JS string support.
  2873. */
  2874. exports.react.render = reactRenderer('string');
  2875. /**
  2876. * ARC-templates support.
  2877. */
  2878. exports['arc-templates'] = fromStringRenderer('arc-templates');
  2879. /**
  2880. * ARC-templates string support.
  2881. */
  2882. exports['arc-templates'].render = function(str, options, cb) {
  2883. var readFileWithOptions = util.promisify(read);
  2884. var consolidateFileSystem = {};
  2885. consolidateFileSystem.readFile = function(path) {
  2886. return readFileWithOptions(path, options);
  2887. };
  2888. return promisify(cb, function(cb) {
  2889. try {
  2890. var engine = requires['arc-templates'];
  2891. if (!engine) {
  2892. var Engine = require('arc-templates/dist/es5');
  2893. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  2894. }
  2895. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  2896. compiler.then(function(func) { return func(options); })
  2897. .then(function(result) { cb(null, result.content); })
  2898. .catch(cb);
  2899. } catch (err) {
  2900. cb(err);
  2901. }
  2902. });
  2903. };
  2904. /**
  2905. * Vash support
  2906. */
  2907. exports.vash = fromStringRenderer('vash');
  2908. /**
  2909. * Vash string support
  2910. */
  2911. exports.vash.render = function(str, options, cb) {
  2912. return promisify(cb, function(cb) {
  2913. var engine = requires.vash || (requires.vash = require('vash'));
  2914. try {
  2915. // helper system : https://github.com/kirbysayshi/vash#helper-system
  2916. if (options.helpers) {
  2917. for (var key in options.helpers) {
  2918. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  2919. continue;
  2920. }
  2921. engine.helpers[key] = options.helpers[key];
  2922. }
  2923. }
  2924. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2925. tmpl(options, function sealLayout(err, ctx) {
  2926. if (err) cb(err);
  2927. ctx.finishLayout();
  2928. cb(null, ctx.toString().replace(/\n$/, ''));
  2929. });
  2930. } catch (err) {
  2931. cb(err);
  2932. }
  2933. });
  2934. };
  2935. /**
  2936. * Slm support.
  2937. */
  2938. exports.slm = fromStringRenderer('slm');
  2939. /**
  2940. * Slm string support.
  2941. */
  2942. exports.slm.render = function(str, options, cb) {
  2943. return promisify(cb, function(cb) {
  2944. var engine = requires.slm || (requires.slm = require('slm'));
  2945. try {
  2946. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2947. cb(null, tmpl(options));
  2948. } catch (err) {
  2949. cb(err);
  2950. }
  2951. });
  2952. };
  2953. /**
  2954. * Marko support.
  2955. */
  2956. exports.marko = function(path, options, cb) {
  2957. return promisify(cb, function(cb) {
  2958. var engine = requires.marko || (requires.marko = require('marko'));
  2959. options.writeToDisk = !!options.cache;
  2960. try {
  2961. var tmpl = cache(options) || cache(options, engine.load(path, options));
  2962. tmpl.renderToString(options, cb);
  2963. } catch (err) {
  2964. cb(err);
  2965. }
  2966. });
  2967. };
  2968. /**
  2969. * Marko string support.
  2970. */
  2971. exports.marko.render = function(str, options, cb) {
  2972. return promisify(cb, function(cb) {
  2973. var engine = requires.marko || (requires.marko = require('marko'));
  2974. options.writeToDisk = !!options.cache;
  2975. options.filename = options.filename || 'string.marko';
  2976. try {
  2977. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  2978. tmpl.renderToString(options, cb);
  2979. } catch (err) {
  2980. cb(err);
  2981. }
  2982. });
  2983. };
  2984. /**
  2985. * Teacup support.
  2986. */
  2987. exports.teacup = function(path, options, cb) {
  2988. return promisify(cb, function(cb) {
  2989. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  2990. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  2991. if (path[0] !== '/') {
  2992. path = join(process.cwd(), path);
  2993. }
  2994. if (!options.cache) {
  2995. var callback = cb;
  2996. cb = function() {
  2997. delete require.cache[path];
  2998. callback.apply(this, arguments);
  2999. };
  3000. }
  3001. engine.renderFile(path, options, cb);
  3002. });
  3003. };
  3004. /**
  3005. * Teacup string support.
  3006. */
  3007. exports.teacup.render = function(str, options, cb) {
  3008. var coffee = require('coffee-script');
  3009. var vm = require('vm');
  3010. var sandbox = {
  3011. module: {exports: {}},
  3012. require: commonjsRequire
  3013. };
  3014. return promisify(cb, function(cb) {
  3015. vm.runInNewContext(coffee.compile(str), sandbox);
  3016. var tmpl = sandbox.module.exports;
  3017. cb(null, tmpl(options));
  3018. });
  3019. };
  3020. /**
  3021. * Squirrelly support.
  3022. */
  3023. exports.squirrelly = fromStringRenderer('squirrelly');
  3024. /**
  3025. * Squirrelly string support.
  3026. */
  3027. exports.squirrelly.render = function(str, options, cb) {
  3028. return promisify(cb, function(cb) {
  3029. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3030. try {
  3031. for (var partial in options.partials) {
  3032. engine.definePartial(partial, options.partials[partial]);
  3033. }
  3034. for (var helper in options.helpers) {
  3035. engine.defineHelper(helper, options.helpers[helper]);
  3036. }
  3037. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3038. cb(null, tmpl(options, engine));
  3039. } catch (err) {
  3040. cb(err);
  3041. }
  3042. });
  3043. };
  3044. /**
  3045. * Twing support.
  3046. */
  3047. exports.twing = fromStringRenderer('twing');
  3048. /**
  3049. * Twing string support.
  3050. */
  3051. exports.twing.render = function(str, options, cb) {
  3052. return promisify(cb, function(cb) {
  3053. var engine = requires.twing || (requires.twing = require('twing'));
  3054. try {
  3055. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3056. twingTemplate.render(options).then((rendTmpl) => {
  3057. var tmpl = cache(options) || cache(options, rendTmpl);
  3058. cb(null, tmpl);
  3059. });
  3060. });
  3061. } catch (err) {
  3062. cb(err);
  3063. }
  3064. });
  3065. };
  3066. /**
  3067. * expose the instance of the engine
  3068. */
  3069. exports.requires = requires;
  3070. } (consolidate$1, consolidateExports));
  3071. (function (module) {
  3072. module.exports = consolidateExports;
  3073. } (consolidate$2));
  3074. var consolidate = /*@__PURE__*/getDefaultExportFromCjs(consolidateExports$1);
  3075. const hasWarned = {};
  3076. function warnOnce(msg) {
  3077. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3078. if (!isNodeProd && true && !hasWarned[msg]) {
  3079. hasWarned[msg] = true;
  3080. warn(msg);
  3081. }
  3082. }
  3083. function warn(msg) {
  3084. console.warn(
  3085. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3086. `
  3087. );
  3088. }
  3089. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3090. let res = "";
  3091. let err = null;
  3092. preprocessor.render(
  3093. source,
  3094. { filename, ...preprocessOptions },
  3095. (_err, _res) => {
  3096. if (_err)
  3097. err = _err;
  3098. res = _res;
  3099. }
  3100. );
  3101. if (err)
  3102. throw err;
  3103. return res;
  3104. }
  3105. function compileTemplate(options) {
  3106. const { preprocessLang, preprocessCustomRequire } = options;
  3107. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate[preprocessLang] : false;
  3108. if (preprocessor) {
  3109. try {
  3110. return doCompileTemplate({
  3111. ...options,
  3112. source: preprocess$1(options, preprocessor)
  3113. });
  3114. } catch (e) {
  3115. return {
  3116. code: `export default function render() {}`,
  3117. source: options.source,
  3118. tips: [],
  3119. errors: [e]
  3120. };
  3121. }
  3122. } else if (preprocessLang) {
  3123. return {
  3124. code: `export default function render() {}`,
  3125. source: options.source,
  3126. tips: [
  3127. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3128. ],
  3129. errors: [
  3130. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3131. ]
  3132. };
  3133. } else {
  3134. return doCompileTemplate(options);
  3135. }
  3136. }
  3137. function doCompileTemplate({
  3138. filename,
  3139. id,
  3140. scoped,
  3141. slotted,
  3142. inMap,
  3143. source,
  3144. ssr = false,
  3145. ssrCssVars,
  3146. isProd = false,
  3147. compiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace,
  3148. compilerOptions = {},
  3149. transformAssetUrls
  3150. }) {
  3151. const errors = [];
  3152. const warnings = [];
  3153. let nodeTransforms = [];
  3154. if (shared.isObject(transformAssetUrls)) {
  3155. const assetOptions = normalizeOptions(transformAssetUrls);
  3156. nodeTransforms = [
  3157. createAssetUrlTransformWithOptions(assetOptions),
  3158. createSrcsetTransformWithOptions(assetOptions)
  3159. ];
  3160. } else if (transformAssetUrls !== false) {
  3161. nodeTransforms = [transformAssetUrl, transformSrcset];
  3162. }
  3163. if (ssr && !ssrCssVars) {
  3164. warnOnce(
  3165. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.\`.`
  3166. );
  3167. }
  3168. if (!id) {
  3169. warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
  3170. id = "";
  3171. }
  3172. const shortId = id.replace(/^data-v-/, "");
  3173. const longId = `data-v-${shortId}`;
  3174. let { code, ast, preamble, map } = compiler.compile(source, {
  3175. mode: "module",
  3176. prefixIdentifiers: true,
  3177. hoistStatic: true,
  3178. cacheHandlers: true,
  3179. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3180. scopeId: scoped ? longId : void 0,
  3181. slotted,
  3182. sourceMap: true,
  3183. ...compilerOptions,
  3184. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3185. filename,
  3186. onError: (e) => errors.push(e),
  3187. onWarn: (w) => warnings.push(w)
  3188. });
  3189. if (inMap) {
  3190. if (map) {
  3191. map = mapLines(inMap, map);
  3192. }
  3193. if (errors.length) {
  3194. patchErrors(errors, source, inMap);
  3195. }
  3196. }
  3197. const tips = warnings.map((w) => {
  3198. let msg = w.message;
  3199. if (w.loc) {
  3200. msg += `
  3201. ${shared.generateCodeFrame(
  3202. source,
  3203. w.loc.start.offset,
  3204. w.loc.end.offset
  3205. )}`;
  3206. }
  3207. return msg;
  3208. });
  3209. return { code, ast, preamble, source, errors, tips, map };
  3210. }
  3211. function mapLines(oldMap, newMap) {
  3212. if (!oldMap)
  3213. return newMap;
  3214. if (!newMap)
  3215. return oldMap;
  3216. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  3217. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  3218. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  3219. newMapConsumer.eachMapping((m) => {
  3220. if (m.originalLine == null) {
  3221. return;
  3222. }
  3223. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  3224. line: m.originalLine,
  3225. column: m.originalColumn
  3226. });
  3227. if (origPosInOldMap.source == null) {
  3228. return;
  3229. }
  3230. mergedMapGenerator.addMapping({
  3231. generated: {
  3232. line: m.generatedLine,
  3233. column: m.generatedColumn
  3234. },
  3235. original: {
  3236. line: origPosInOldMap.line,
  3237. // map line
  3238. // use current column, since the oldMap produced by @vue/compiler-sfc
  3239. // does not
  3240. column: m.originalColumn
  3241. },
  3242. source: origPosInOldMap.source,
  3243. name: origPosInOldMap.name
  3244. });
  3245. });
  3246. const generator = mergedMapGenerator;
  3247. oldMapConsumer.sources.forEach((sourceFile) => {
  3248. generator._sources.add(sourceFile);
  3249. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  3250. if (sourceContent != null) {
  3251. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  3252. }
  3253. });
  3254. generator._sourceRoot = oldMap.sourceRoot;
  3255. generator._file = oldMap.file;
  3256. return generator.toJSON();
  3257. }
  3258. function patchErrors(errors, source, inMap) {
  3259. const originalSource = inMap.sourcesContent[0];
  3260. const offset = originalSource.indexOf(source);
  3261. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  3262. errors.forEach((err) => {
  3263. if (err.loc) {
  3264. err.loc.start.line += lineOffset;
  3265. err.loc.start.offset += offset;
  3266. if (err.loc.end !== err.loc.start) {
  3267. err.loc.end.line += lineOffset;
  3268. err.loc.end.offset += offset;
  3269. }
  3270. }
  3271. });
  3272. }
  3273. const trimPlugin = () => {
  3274. return {
  3275. postcssPlugin: "vue-sfc-trim",
  3276. Once(root) {
  3277. root.walk(({ type, raws }) => {
  3278. if (type === "rule" || type === "atrule") {
  3279. if (raws.before)
  3280. raws.before = "\n";
  3281. if ("after" in raws && raws.after)
  3282. raws.after = "\n";
  3283. }
  3284. });
  3285. }
  3286. };
  3287. };
  3288. trimPlugin.postcss = true;
  3289. var trimPlugin$1 = trimPlugin;
  3290. var distExports = {};
  3291. var dist = {
  3292. get exports(){ return distExports; },
  3293. set exports(v){ distExports = v; },
  3294. };
  3295. var processorExports = {};
  3296. var processor = {
  3297. get exports(){ return processorExports; },
  3298. set exports(v){ processorExports = v; },
  3299. };
  3300. var parserExports = {};
  3301. var parser$1 = {
  3302. get exports(){ return parserExports; },
  3303. set exports(v){ parserExports = v; },
  3304. };
  3305. var rootExports = {};
  3306. var root$2 = {
  3307. get exports(){ return rootExports; },
  3308. set exports(v){ rootExports = v; },
  3309. };
  3310. var containerExports = {};
  3311. var container = {
  3312. get exports(){ return containerExports; },
  3313. set exports(v){ containerExports = v; },
  3314. };
  3315. var nodeExports = {};
  3316. var node$1 = {
  3317. get exports(){ return nodeExports; },
  3318. set exports(v){ nodeExports = v; },
  3319. };
  3320. var util$6 = {};
  3321. var unescExports = {};
  3322. var unesc = {
  3323. get exports(){ return unescExports; },
  3324. set exports(v){ unescExports = v; },
  3325. };
  3326. (function (module, exports) {
  3327. exports.__esModule = true;
  3328. exports["default"] = unesc;
  3329. // Many thanks for this post which made this migration much easier.
  3330. // https://mathiasbynens.be/notes/css-escapes
  3331. /**
  3332. *
  3333. * @param {string} str
  3334. * @returns {[string, number]|undefined}
  3335. */
  3336. function gobbleHex(str) {
  3337. var lower = str.toLowerCase();
  3338. var hex = '';
  3339. var spaceTerminated = false;
  3340. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  3341. var code = lower.charCodeAt(i); // check to see if we are dealing with a valid hex char [a-f|0-9]
  3342. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  3343. spaceTerminated = code === 32;
  3344. if (!valid) {
  3345. break;
  3346. }
  3347. hex += lower[i];
  3348. }
  3349. if (hex.length === 0) {
  3350. return undefined;
  3351. }
  3352. var codePoint = parseInt(hex, 16);
  3353. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; // Add special case for
  3354. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  3355. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  3356. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  3357. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  3358. }
  3359. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  3360. }
  3361. var CONTAINS_ESCAPE = /\\/;
  3362. function unesc(str) {
  3363. var needToProcess = CONTAINS_ESCAPE.test(str);
  3364. if (!needToProcess) {
  3365. return str;
  3366. }
  3367. var ret = "";
  3368. for (var i = 0; i < str.length; i++) {
  3369. if (str[i] === "\\") {
  3370. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  3371. if (gobbled !== undefined) {
  3372. ret += gobbled[0];
  3373. i += gobbled[1];
  3374. continue;
  3375. } // Retain a pair of \\ if double escaped `\\\\`
  3376. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  3377. if (str[i + 1] === "\\") {
  3378. ret += "\\";
  3379. i++;
  3380. continue;
  3381. } // if \\ is at the end of the string retain it
  3382. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  3383. if (str.length === i + 1) {
  3384. ret += str[i];
  3385. }
  3386. continue;
  3387. }
  3388. ret += str[i];
  3389. }
  3390. return ret;
  3391. }
  3392. module.exports = exports.default;
  3393. } (unesc, unescExports));
  3394. var getPropExports = {};
  3395. var getProp = {
  3396. get exports(){ return getPropExports; },
  3397. set exports(v){ getPropExports = v; },
  3398. };
  3399. (function (module, exports) {
  3400. exports.__esModule = true;
  3401. exports["default"] = getProp;
  3402. function getProp(obj) {
  3403. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  3404. props[_key - 1] = arguments[_key];
  3405. }
  3406. while (props.length > 0) {
  3407. var prop = props.shift();
  3408. if (!obj[prop]) {
  3409. return undefined;
  3410. }
  3411. obj = obj[prop];
  3412. }
  3413. return obj;
  3414. }
  3415. module.exports = exports.default;
  3416. } (getProp, getPropExports));
  3417. var ensureObjectExports = {};
  3418. var ensureObject = {
  3419. get exports(){ return ensureObjectExports; },
  3420. set exports(v){ ensureObjectExports = v; },
  3421. };
  3422. (function (module, exports) {
  3423. exports.__esModule = true;
  3424. exports["default"] = ensureObject;
  3425. function ensureObject(obj) {
  3426. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  3427. props[_key - 1] = arguments[_key];
  3428. }
  3429. while (props.length > 0) {
  3430. var prop = props.shift();
  3431. if (!obj[prop]) {
  3432. obj[prop] = {};
  3433. }
  3434. obj = obj[prop];
  3435. }
  3436. }
  3437. module.exports = exports.default;
  3438. } (ensureObject, ensureObjectExports));
  3439. var stripCommentsExports = {};
  3440. var stripComments = {
  3441. get exports(){ return stripCommentsExports; },
  3442. set exports(v){ stripCommentsExports = v; },
  3443. };
  3444. (function (module, exports) {
  3445. exports.__esModule = true;
  3446. exports["default"] = stripComments;
  3447. function stripComments(str) {
  3448. var s = "";
  3449. var commentStart = str.indexOf("/*");
  3450. var lastEnd = 0;
  3451. while (commentStart >= 0) {
  3452. s = s + str.slice(lastEnd, commentStart);
  3453. var commentEnd = str.indexOf("*/", commentStart + 2);
  3454. if (commentEnd < 0) {
  3455. return s;
  3456. }
  3457. lastEnd = commentEnd + 2;
  3458. commentStart = str.indexOf("/*", lastEnd);
  3459. }
  3460. s = s + str.slice(lastEnd);
  3461. return s;
  3462. }
  3463. module.exports = exports.default;
  3464. } (stripComments, stripCommentsExports));
  3465. util$6.__esModule = true;
  3466. util$6.stripComments = util$6.ensureObject = util$6.getProp = util$6.unesc = void 0;
  3467. var _unesc = _interopRequireDefault$6(unescExports);
  3468. util$6.unesc = _unesc["default"];
  3469. var _getProp = _interopRequireDefault$6(getPropExports);
  3470. util$6.getProp = _getProp["default"];
  3471. var _ensureObject = _interopRequireDefault$6(ensureObjectExports);
  3472. util$6.ensureObject = _ensureObject["default"];
  3473. var _stripComments = _interopRequireDefault$6(stripCommentsExports);
  3474. util$6.stripComments = _stripComments["default"];
  3475. function _interopRequireDefault$6(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  3476. (function (module, exports) {
  3477. exports.__esModule = true;
  3478. exports["default"] = void 0;
  3479. var _util = util$6;
  3480. 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); } }
  3481. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  3482. var cloneNode = function cloneNode(obj, parent) {
  3483. if (typeof obj !== 'object' || obj === null) {
  3484. return obj;
  3485. }
  3486. var cloned = new obj.constructor();
  3487. for (var i in obj) {
  3488. if (!obj.hasOwnProperty(i)) {
  3489. continue;
  3490. }
  3491. var value = obj[i];
  3492. var type = typeof value;
  3493. if (i === 'parent' && type === 'object') {
  3494. if (parent) {
  3495. cloned[i] = parent;
  3496. }
  3497. } else if (value instanceof Array) {
  3498. cloned[i] = value.map(function (j) {
  3499. return cloneNode(j, cloned);
  3500. });
  3501. } else {
  3502. cloned[i] = cloneNode(value, cloned);
  3503. }
  3504. }
  3505. return cloned;
  3506. };
  3507. var Node = /*#__PURE__*/function () {
  3508. function Node(opts) {
  3509. if (opts === void 0) {
  3510. opts = {};
  3511. }
  3512. Object.assign(this, opts);
  3513. this.spaces = this.spaces || {};
  3514. this.spaces.before = this.spaces.before || '';
  3515. this.spaces.after = this.spaces.after || '';
  3516. }
  3517. var _proto = Node.prototype;
  3518. _proto.remove = function remove() {
  3519. if (this.parent) {
  3520. this.parent.removeChild(this);
  3521. }
  3522. this.parent = undefined;
  3523. return this;
  3524. };
  3525. _proto.replaceWith = function replaceWith() {
  3526. if (this.parent) {
  3527. for (var index in arguments) {
  3528. this.parent.insertBefore(this, arguments[index]);
  3529. }
  3530. this.remove();
  3531. }
  3532. return this;
  3533. };
  3534. _proto.next = function next() {
  3535. return this.parent.at(this.parent.index(this) + 1);
  3536. };
  3537. _proto.prev = function prev() {
  3538. return this.parent.at(this.parent.index(this) - 1);
  3539. };
  3540. _proto.clone = function clone(overrides) {
  3541. if (overrides === void 0) {
  3542. overrides = {};
  3543. }
  3544. var cloned = cloneNode(this);
  3545. for (var name in overrides) {
  3546. cloned[name] = overrides[name];
  3547. }
  3548. return cloned;
  3549. }
  3550. /**
  3551. * Some non-standard syntax doesn't follow normal escaping rules for css.
  3552. * This allows non standard syntax to be appended to an existing property
  3553. * by specifying the escaped value. By specifying the escaped value,
  3554. * illegal characters are allowed to be directly inserted into css output.
  3555. * @param {string} name the property to set
  3556. * @param {any} value the unescaped value of the property
  3557. * @param {string} valueEscaped optional. the escaped value of the property.
  3558. */
  3559. ;
  3560. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  3561. if (!this.raws) {
  3562. this.raws = {};
  3563. }
  3564. var originalValue = this[name];
  3565. var originalEscaped = this.raws[name];
  3566. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  3567. if (originalEscaped || valueEscaped !== value) {
  3568. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  3569. } else {
  3570. delete this.raws[name]; // delete any escaped value that was created by the setter.
  3571. }
  3572. }
  3573. /**
  3574. * Some non-standard syntax doesn't follow normal escaping rules for css.
  3575. * This allows the escaped value to be specified directly, allowing illegal
  3576. * characters to be directly inserted into css output.
  3577. * @param {string} name the property to set
  3578. * @param {any} value the unescaped value of the property
  3579. * @param {string} valueEscaped the escaped value of the property.
  3580. */
  3581. ;
  3582. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  3583. if (!this.raws) {
  3584. this.raws = {};
  3585. }
  3586. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  3587. this.raws[name] = valueEscaped;
  3588. }
  3589. /**
  3590. * When you want a value to passed through to CSS directly. This method
  3591. * deletes the corresponding raw value causing the stringifier to fallback
  3592. * to the unescaped value.
  3593. * @param {string} name the property to set.
  3594. * @param {any} value The value that is both escaped and unescaped.
  3595. */
  3596. ;
  3597. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  3598. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  3599. if (this.raws) {
  3600. delete this.raws[name];
  3601. }
  3602. }
  3603. /**
  3604. *
  3605. * @param {number} line The number (starting with 1)
  3606. * @param {number} column The column number (starting with 1)
  3607. */
  3608. ;
  3609. _proto.isAtPosition = function isAtPosition(line, column) {
  3610. if (this.source && this.source.start && this.source.end) {
  3611. if (this.source.start.line > line) {
  3612. return false;
  3613. }
  3614. if (this.source.end.line < line) {
  3615. return false;
  3616. }
  3617. if (this.source.start.line === line && this.source.start.column > column) {
  3618. return false;
  3619. }
  3620. if (this.source.end.line === line && this.source.end.column < column) {
  3621. return false;
  3622. }
  3623. return true;
  3624. }
  3625. return undefined;
  3626. };
  3627. _proto.stringifyProperty = function stringifyProperty(name) {
  3628. return this.raws && this.raws[name] || this[name];
  3629. };
  3630. _proto.valueToString = function valueToString() {
  3631. return String(this.stringifyProperty("value"));
  3632. };
  3633. _proto.toString = function toString() {
  3634. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  3635. };
  3636. _createClass(Node, [{
  3637. key: "rawSpaceBefore",
  3638. get: function get() {
  3639. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  3640. if (rawSpace === undefined) {
  3641. rawSpace = this.spaces && this.spaces.before;
  3642. }
  3643. return rawSpace || "";
  3644. },
  3645. set: function set(raw) {
  3646. (0, _util.ensureObject)(this, "raws", "spaces");
  3647. this.raws.spaces.before = raw;
  3648. }
  3649. }, {
  3650. key: "rawSpaceAfter",
  3651. get: function get() {
  3652. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  3653. if (rawSpace === undefined) {
  3654. rawSpace = this.spaces.after;
  3655. }
  3656. return rawSpace || "";
  3657. },
  3658. set: function set(raw) {
  3659. (0, _util.ensureObject)(this, "raws", "spaces");
  3660. this.raws.spaces.after = raw;
  3661. }
  3662. }]);
  3663. return Node;
  3664. }();
  3665. exports["default"] = Node;
  3666. module.exports = exports.default;
  3667. } (node$1, nodeExports));
  3668. var types$1 = {};
  3669. types$1.__esModule = true;
  3670. types$1.UNIVERSAL = types$1.ATTRIBUTE = types$1.CLASS = types$1.COMBINATOR = types$1.COMMENT = types$1.ID = types$1.NESTING = types$1.PSEUDO = types$1.ROOT = types$1.SELECTOR = types$1.STRING = types$1.TAG = void 0;
  3671. var TAG = 'tag';
  3672. types$1.TAG = TAG;
  3673. var STRING = 'string';
  3674. types$1.STRING = STRING;
  3675. var SELECTOR = 'selector';
  3676. types$1.SELECTOR = SELECTOR;
  3677. var ROOT = 'root';
  3678. types$1.ROOT = ROOT;
  3679. var PSEUDO = 'pseudo';
  3680. types$1.PSEUDO = PSEUDO;
  3681. var NESTING = 'nesting';
  3682. types$1.NESTING = NESTING;
  3683. var ID = 'id';
  3684. types$1.ID = ID;
  3685. var COMMENT = 'comment';
  3686. types$1.COMMENT = COMMENT;
  3687. var COMBINATOR = 'combinator';
  3688. types$1.COMBINATOR = COMBINATOR;
  3689. var CLASS = 'class';
  3690. types$1.CLASS = CLASS;
  3691. var ATTRIBUTE = 'attribute';
  3692. types$1.ATTRIBUTE = ATTRIBUTE;
  3693. var UNIVERSAL = 'universal';
  3694. types$1.UNIVERSAL = UNIVERSAL;
  3695. (function (module, exports) {
  3696. exports.__esModule = true;
  3697. exports["default"] = void 0;
  3698. var _node = _interopRequireDefault(nodeExports);
  3699. var types = _interopRequireWildcard(types$1);
  3700. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  3701. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }
  3702. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  3703. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }
  3704. 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); }
  3705. 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; }
  3706. 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); } }
  3707. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  3708. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  3709. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  3710. var Container = /*#__PURE__*/function (_Node) {
  3711. _inheritsLoose(Container, _Node);
  3712. function Container(opts) {
  3713. var _this;
  3714. _this = _Node.call(this, opts) || this;
  3715. if (!_this.nodes) {
  3716. _this.nodes = [];
  3717. }
  3718. return _this;
  3719. }
  3720. var _proto = Container.prototype;
  3721. _proto.append = function append(selector) {
  3722. selector.parent = this;
  3723. this.nodes.push(selector);
  3724. return this;
  3725. };
  3726. _proto.prepend = function prepend(selector) {
  3727. selector.parent = this;
  3728. this.nodes.unshift(selector);
  3729. return this;
  3730. };
  3731. _proto.at = function at(index) {
  3732. return this.nodes[index];
  3733. };
  3734. _proto.index = function index(child) {
  3735. if (typeof child === 'number') {
  3736. return child;
  3737. }
  3738. return this.nodes.indexOf(child);
  3739. };
  3740. _proto.removeChild = function removeChild(child) {
  3741. child = this.index(child);
  3742. this.at(child).parent = undefined;
  3743. this.nodes.splice(child, 1);
  3744. var index;
  3745. for (var id in this.indexes) {
  3746. index = this.indexes[id];
  3747. if (index >= child) {
  3748. this.indexes[id] = index - 1;
  3749. }
  3750. }
  3751. return this;
  3752. };
  3753. _proto.removeAll = function removeAll() {
  3754. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  3755. var node = _step.value;
  3756. node.parent = undefined;
  3757. }
  3758. this.nodes = [];
  3759. return this;
  3760. };
  3761. _proto.empty = function empty() {
  3762. return this.removeAll();
  3763. };
  3764. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  3765. newNode.parent = this;
  3766. var oldIndex = this.index(oldNode);
  3767. this.nodes.splice(oldIndex + 1, 0, newNode);
  3768. newNode.parent = this;
  3769. var index;
  3770. for (var id in this.indexes) {
  3771. index = this.indexes[id];
  3772. if (oldIndex <= index) {
  3773. this.indexes[id] = index + 1;
  3774. }
  3775. }
  3776. return this;
  3777. };
  3778. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  3779. newNode.parent = this;
  3780. var oldIndex = this.index(oldNode);
  3781. this.nodes.splice(oldIndex, 0, newNode);
  3782. newNode.parent = this;
  3783. var index;
  3784. for (var id in this.indexes) {
  3785. index = this.indexes[id];
  3786. if (index <= oldIndex) {
  3787. this.indexes[id] = index + 1;
  3788. }
  3789. }
  3790. return this;
  3791. };
  3792. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  3793. var found = undefined;
  3794. this.each(function (node) {
  3795. if (node.atPosition) {
  3796. var foundChild = node.atPosition(line, col);
  3797. if (foundChild) {
  3798. found = foundChild;
  3799. return false;
  3800. }
  3801. } else if (node.isAtPosition(line, col)) {
  3802. found = node;
  3803. return false;
  3804. }
  3805. });
  3806. return found;
  3807. }
  3808. /**
  3809. * Return the most specific node at the line and column number given.
  3810. * The source location is based on the original parsed location, locations aren't
  3811. * updated as selector nodes are mutated.
  3812. *
  3813. * Note that this location is relative to the location of the first character
  3814. * of the selector, and not the location of the selector in the overall document
  3815. * when used in conjunction with postcss.
  3816. *
  3817. * If not found, returns undefined.
  3818. * @param {number} line The line number of the node to find. (1-based index)
  3819. * @param {number} col The column number of the node to find. (1-based index)
  3820. */
  3821. ;
  3822. _proto.atPosition = function atPosition(line, col) {
  3823. if (this.isAtPosition(line, col)) {
  3824. return this._findChildAtPosition(line, col) || this;
  3825. } else {
  3826. return undefined;
  3827. }
  3828. };
  3829. _proto._inferEndPosition = function _inferEndPosition() {
  3830. if (this.last && this.last.source && this.last.source.end) {
  3831. this.source = this.source || {};
  3832. this.source.end = this.source.end || {};
  3833. Object.assign(this.source.end, this.last.source.end);
  3834. }
  3835. };
  3836. _proto.each = function each(callback) {
  3837. if (!this.lastEach) {
  3838. this.lastEach = 0;
  3839. }
  3840. if (!this.indexes) {
  3841. this.indexes = {};
  3842. }
  3843. this.lastEach++;
  3844. var id = this.lastEach;
  3845. this.indexes[id] = 0;
  3846. if (!this.length) {
  3847. return undefined;
  3848. }
  3849. var index, result;
  3850. while (this.indexes[id] < this.length) {
  3851. index = this.indexes[id];
  3852. result = callback(this.at(index), index);
  3853. if (result === false) {
  3854. break;
  3855. }
  3856. this.indexes[id] += 1;
  3857. }
  3858. delete this.indexes[id];
  3859. if (result === false) {
  3860. return false;
  3861. }
  3862. };
  3863. _proto.walk = function walk(callback) {
  3864. return this.each(function (node, i) {
  3865. var result = callback(node, i);
  3866. if (result !== false && node.length) {
  3867. result = node.walk(callback);
  3868. }
  3869. if (result === false) {
  3870. return false;
  3871. }
  3872. });
  3873. };
  3874. _proto.walkAttributes = function walkAttributes(callback) {
  3875. var _this2 = this;
  3876. return this.walk(function (selector) {
  3877. if (selector.type === types.ATTRIBUTE) {
  3878. return callback.call(_this2, selector);
  3879. }
  3880. });
  3881. };
  3882. _proto.walkClasses = function walkClasses(callback) {
  3883. var _this3 = this;
  3884. return this.walk(function (selector) {
  3885. if (selector.type === types.CLASS) {
  3886. return callback.call(_this3, selector);
  3887. }
  3888. });
  3889. };
  3890. _proto.walkCombinators = function walkCombinators(callback) {
  3891. var _this4 = this;
  3892. return this.walk(function (selector) {
  3893. if (selector.type === types.COMBINATOR) {
  3894. return callback.call(_this4, selector);
  3895. }
  3896. });
  3897. };
  3898. _proto.walkComments = function walkComments(callback) {
  3899. var _this5 = this;
  3900. return this.walk(function (selector) {
  3901. if (selector.type === types.COMMENT) {
  3902. return callback.call(_this5, selector);
  3903. }
  3904. });
  3905. };
  3906. _proto.walkIds = function walkIds(callback) {
  3907. var _this6 = this;
  3908. return this.walk(function (selector) {
  3909. if (selector.type === types.ID) {
  3910. return callback.call(_this6, selector);
  3911. }
  3912. });
  3913. };
  3914. _proto.walkNesting = function walkNesting(callback) {
  3915. var _this7 = this;
  3916. return this.walk(function (selector) {
  3917. if (selector.type === types.NESTING) {
  3918. return callback.call(_this7, selector);
  3919. }
  3920. });
  3921. };
  3922. _proto.walkPseudos = function walkPseudos(callback) {
  3923. var _this8 = this;
  3924. return this.walk(function (selector) {
  3925. if (selector.type === types.PSEUDO) {
  3926. return callback.call(_this8, selector);
  3927. }
  3928. });
  3929. };
  3930. _proto.walkTags = function walkTags(callback) {
  3931. var _this9 = this;
  3932. return this.walk(function (selector) {
  3933. if (selector.type === types.TAG) {
  3934. return callback.call(_this9, selector);
  3935. }
  3936. });
  3937. };
  3938. _proto.walkUniversals = function walkUniversals(callback) {
  3939. var _this10 = this;
  3940. return this.walk(function (selector) {
  3941. if (selector.type === types.UNIVERSAL) {
  3942. return callback.call(_this10, selector);
  3943. }
  3944. });
  3945. };
  3946. _proto.split = function split(callback) {
  3947. var _this11 = this;
  3948. var current = [];
  3949. return this.reduce(function (memo, node, index) {
  3950. var split = callback.call(_this11, node);
  3951. current.push(node);
  3952. if (split) {
  3953. memo.push(current);
  3954. current = [];
  3955. } else if (index === _this11.length - 1) {
  3956. memo.push(current);
  3957. }
  3958. return memo;
  3959. }, []);
  3960. };
  3961. _proto.map = function map(callback) {
  3962. return this.nodes.map(callback);
  3963. };
  3964. _proto.reduce = function reduce(callback, memo) {
  3965. return this.nodes.reduce(callback, memo);
  3966. };
  3967. _proto.every = function every(callback) {
  3968. return this.nodes.every(callback);
  3969. };
  3970. _proto.some = function some(callback) {
  3971. return this.nodes.some(callback);
  3972. };
  3973. _proto.filter = function filter(callback) {
  3974. return this.nodes.filter(callback);
  3975. };
  3976. _proto.sort = function sort(callback) {
  3977. return this.nodes.sort(callback);
  3978. };
  3979. _proto.toString = function toString() {
  3980. return this.map(String).join('');
  3981. };
  3982. _createClass(Container, [{
  3983. key: "first",
  3984. get: function get() {
  3985. return this.at(0);
  3986. }
  3987. }, {
  3988. key: "last",
  3989. get: function get() {
  3990. return this.at(this.length - 1);
  3991. }
  3992. }, {
  3993. key: "length",
  3994. get: function get() {
  3995. return this.nodes.length;
  3996. }
  3997. }]);
  3998. return Container;
  3999. }(_node["default"]);
  4000. exports["default"] = Container;
  4001. module.exports = exports.default;
  4002. } (container, containerExports));
  4003. (function (module, exports) {
  4004. exports.__esModule = true;
  4005. exports["default"] = void 0;
  4006. var _container = _interopRequireDefault(containerExports);
  4007. var _types = types$1;
  4008. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4009. 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); } }
  4010. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  4011. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4012. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4013. var Root = /*#__PURE__*/function (_Container) {
  4014. _inheritsLoose(Root, _Container);
  4015. function Root(opts) {
  4016. var _this;
  4017. _this = _Container.call(this, opts) || this;
  4018. _this.type = _types.ROOT;
  4019. return _this;
  4020. }
  4021. var _proto = Root.prototype;
  4022. _proto.toString = function toString() {
  4023. var str = this.reduce(function (memo, selector) {
  4024. memo.push(String(selector));
  4025. return memo;
  4026. }, []).join(',');
  4027. return this.trailingComma ? str + ',' : str;
  4028. };
  4029. _proto.error = function error(message, options) {
  4030. if (this._error) {
  4031. return this._error(message, options);
  4032. } else {
  4033. return new Error(message);
  4034. }
  4035. };
  4036. _createClass(Root, [{
  4037. key: "errorGenerator",
  4038. set: function set(handler) {
  4039. this._error = handler;
  4040. }
  4041. }]);
  4042. return Root;
  4043. }(_container["default"]);
  4044. exports["default"] = Root;
  4045. module.exports = exports.default;
  4046. } (root$2, rootExports));
  4047. var selectorExports = {};
  4048. var selector$1 = {
  4049. get exports(){ return selectorExports; },
  4050. set exports(v){ selectorExports = v; },
  4051. };
  4052. (function (module, exports) {
  4053. exports.__esModule = true;
  4054. exports["default"] = void 0;
  4055. var _container = _interopRequireDefault(containerExports);
  4056. var _types = types$1;
  4057. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4058. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4059. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4060. var Selector = /*#__PURE__*/function (_Container) {
  4061. _inheritsLoose(Selector, _Container);
  4062. function Selector(opts) {
  4063. var _this;
  4064. _this = _Container.call(this, opts) || this;
  4065. _this.type = _types.SELECTOR;
  4066. return _this;
  4067. }
  4068. return Selector;
  4069. }(_container["default"]);
  4070. exports["default"] = Selector;
  4071. module.exports = exports.default;
  4072. } (selector$1, selectorExports));
  4073. var classNameExports = {};
  4074. var className$1 = {
  4075. get exports(){ return classNameExports; },
  4076. set exports(v){ classNameExports = v; },
  4077. };
  4078. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4079. var object = {};
  4080. var hasOwnProperty$1 = object.hasOwnProperty;
  4081. var merge$2 = function merge(options, defaults) {
  4082. if (!options) {
  4083. return defaults;
  4084. }
  4085. var result = {};
  4086. for (var key in defaults) {
  4087. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4088. // only recognized option names are used.
  4089. result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key];
  4090. }
  4091. return result;
  4092. };
  4093. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4094. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4095. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4096. // https://mathiasbynens.be/notes/css-escapes#css
  4097. var cssesc = function cssesc(string, options) {
  4098. options = merge$2(options, cssesc.options);
  4099. if (options.quotes != 'single' && options.quotes != 'double') {
  4100. options.quotes = 'single';
  4101. }
  4102. var quote = options.quotes == 'double' ? '"' : '\'';
  4103. var isIdentifier = options.isIdentifier;
  4104. var firstChar = string.charAt(0);
  4105. var output = '';
  4106. var counter = 0;
  4107. var length = string.length;
  4108. while (counter < length) {
  4109. var character = string.charAt(counter++);
  4110. var codePoint = character.charCodeAt();
  4111. var value = void 0;
  4112. // If it’s not a printable ASCII character…
  4113. if (codePoint < 0x20 || codePoint > 0x7E) {
  4114. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4115. // It’s a high surrogate, and there is a next character.
  4116. var extra = string.charCodeAt(counter++);
  4117. if ((extra & 0xFC00) == 0xDC00) {
  4118. // next character is low surrogate
  4119. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4120. } else {
  4121. // It’s an unmatched surrogate; only append this code unit, in case
  4122. // the next code unit is the high surrogate of a surrogate pair.
  4123. counter--;
  4124. }
  4125. }
  4126. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4127. } else {
  4128. if (options.escapeEverything) {
  4129. if (regexAnySingleEscape.test(character)) {
  4130. value = '\\' + character;
  4131. } else {
  4132. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4133. }
  4134. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4135. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4136. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4137. value = '\\' + character;
  4138. } else {
  4139. value = character;
  4140. }
  4141. }
  4142. output += value;
  4143. }
  4144. if (isIdentifier) {
  4145. if (/^-[-\d]/.test(output)) {
  4146. output = '\\-' + output.slice(1);
  4147. } else if (/\d/.test(firstChar)) {
  4148. output = '\\3' + firstChar + ' ' + output.slice(1);
  4149. }
  4150. }
  4151. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4152. // since they’re redundant. Note that this is only possible if the escape
  4153. // sequence isn’t preceded by an odd number of backslashes.
  4154. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4155. if ($1 && $1.length % 2) {
  4156. // It’s not safe to remove the space, so don’t.
  4157. return $0;
  4158. }
  4159. // Strip the space.
  4160. return ($1 || '') + $2;
  4161. });
  4162. if (!isIdentifier && options.wrap) {
  4163. return quote + output + quote;
  4164. }
  4165. return output;
  4166. };
  4167. // Expose default options (so they can be overridden globally).
  4168. cssesc.options = {
  4169. 'escapeEverything': false,
  4170. 'isIdentifier': false,
  4171. 'quotes': 'single',
  4172. 'wrap': false
  4173. };
  4174. cssesc.version = '3.0.0';
  4175. var cssesc_1 = cssesc;
  4176. (function (module, exports) {
  4177. exports.__esModule = true;
  4178. exports["default"] = void 0;
  4179. var _cssesc = _interopRequireDefault(cssesc_1);
  4180. var _util = util$6;
  4181. var _node = _interopRequireDefault(nodeExports);
  4182. var _types = types$1;
  4183. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4184. 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); } }
  4185. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  4186. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4187. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4188. var ClassName = /*#__PURE__*/function (_Node) {
  4189. _inheritsLoose(ClassName, _Node);
  4190. function ClassName(opts) {
  4191. var _this;
  4192. _this = _Node.call(this, opts) || this;
  4193. _this.type = _types.CLASS;
  4194. _this._constructed = true;
  4195. return _this;
  4196. }
  4197. var _proto = ClassName.prototype;
  4198. _proto.valueToString = function valueToString() {
  4199. return '.' + _Node.prototype.valueToString.call(this);
  4200. };
  4201. _createClass(ClassName, [{
  4202. key: "value",
  4203. get: function get() {
  4204. return this._value;
  4205. },
  4206. set: function set(v) {
  4207. if (this._constructed) {
  4208. var escaped = (0, _cssesc["default"])(v, {
  4209. isIdentifier: true
  4210. });
  4211. if (escaped !== v) {
  4212. (0, _util.ensureObject)(this, "raws");
  4213. this.raws.value = escaped;
  4214. } else if (this.raws) {
  4215. delete this.raws.value;
  4216. }
  4217. }
  4218. this._value = v;
  4219. }
  4220. }]);
  4221. return ClassName;
  4222. }(_node["default"]);
  4223. exports["default"] = ClassName;
  4224. module.exports = exports.default;
  4225. } (className$1, classNameExports));
  4226. var commentExports = {};
  4227. var comment$2 = {
  4228. get exports(){ return commentExports; },
  4229. set exports(v){ commentExports = v; },
  4230. };
  4231. (function (module, exports) {
  4232. exports.__esModule = true;
  4233. exports["default"] = void 0;
  4234. var _node = _interopRequireDefault(nodeExports);
  4235. var _types = types$1;
  4236. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4237. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4238. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4239. var Comment = /*#__PURE__*/function (_Node) {
  4240. _inheritsLoose(Comment, _Node);
  4241. function Comment(opts) {
  4242. var _this;
  4243. _this = _Node.call(this, opts) || this;
  4244. _this.type = _types.COMMENT;
  4245. return _this;
  4246. }
  4247. return Comment;
  4248. }(_node["default"]);
  4249. exports["default"] = Comment;
  4250. module.exports = exports.default;
  4251. } (comment$2, commentExports));
  4252. var idExports = {};
  4253. var id$1 = {
  4254. get exports(){ return idExports; },
  4255. set exports(v){ idExports = v; },
  4256. };
  4257. (function (module, exports) {
  4258. exports.__esModule = true;
  4259. exports["default"] = void 0;
  4260. var _node = _interopRequireDefault(nodeExports);
  4261. var _types = types$1;
  4262. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4263. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4264. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4265. var ID = /*#__PURE__*/function (_Node) {
  4266. _inheritsLoose(ID, _Node);
  4267. function ID(opts) {
  4268. var _this;
  4269. _this = _Node.call(this, opts) || this;
  4270. _this.type = _types.ID;
  4271. return _this;
  4272. }
  4273. var _proto = ID.prototype;
  4274. _proto.valueToString = function valueToString() {
  4275. return '#' + _Node.prototype.valueToString.call(this);
  4276. };
  4277. return ID;
  4278. }(_node["default"]);
  4279. exports["default"] = ID;
  4280. module.exports = exports.default;
  4281. } (id$1, idExports));
  4282. var tagExports = {};
  4283. var tag$1 = {
  4284. get exports(){ return tagExports; },
  4285. set exports(v){ tagExports = v; },
  4286. };
  4287. var namespaceExports = {};
  4288. var namespace = {
  4289. get exports(){ return namespaceExports; },
  4290. set exports(v){ namespaceExports = v; },
  4291. };
  4292. (function (module, exports) {
  4293. exports.__esModule = true;
  4294. exports["default"] = void 0;
  4295. var _cssesc = _interopRequireDefault(cssesc_1);
  4296. var _util = util$6;
  4297. var _node = _interopRequireDefault(nodeExports);
  4298. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4299. 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); } }
  4300. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  4301. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4302. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4303. var Namespace = /*#__PURE__*/function (_Node) {
  4304. _inheritsLoose(Namespace, _Node);
  4305. function Namespace() {
  4306. return _Node.apply(this, arguments) || this;
  4307. }
  4308. var _proto = Namespace.prototype;
  4309. _proto.qualifiedName = function qualifiedName(value) {
  4310. if (this.namespace) {
  4311. return this.namespaceString + "|" + value;
  4312. } else {
  4313. return value;
  4314. }
  4315. };
  4316. _proto.valueToString = function valueToString() {
  4317. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  4318. };
  4319. _createClass(Namespace, [{
  4320. key: "namespace",
  4321. get: function get() {
  4322. return this._namespace;
  4323. },
  4324. set: function set(namespace) {
  4325. if (namespace === true || namespace === "*" || namespace === "&") {
  4326. this._namespace = namespace;
  4327. if (this.raws) {
  4328. delete this.raws.namespace;
  4329. }
  4330. return;
  4331. }
  4332. var escaped = (0, _cssesc["default"])(namespace, {
  4333. isIdentifier: true
  4334. });
  4335. this._namespace = namespace;
  4336. if (escaped !== namespace) {
  4337. (0, _util.ensureObject)(this, "raws");
  4338. this.raws.namespace = escaped;
  4339. } else if (this.raws) {
  4340. delete this.raws.namespace;
  4341. }
  4342. }
  4343. }, {
  4344. key: "ns",
  4345. get: function get() {
  4346. return this._namespace;
  4347. },
  4348. set: function set(namespace) {
  4349. this.namespace = namespace;
  4350. }
  4351. }, {
  4352. key: "namespaceString",
  4353. get: function get() {
  4354. if (this.namespace) {
  4355. var ns = this.stringifyProperty("namespace");
  4356. if (ns === true) {
  4357. return '';
  4358. } else {
  4359. return ns;
  4360. }
  4361. } else {
  4362. return '';
  4363. }
  4364. }
  4365. }]);
  4366. return Namespace;
  4367. }(_node["default"]);
  4368. exports["default"] = Namespace;
  4369. module.exports = exports.default;
  4370. } (namespace, namespaceExports));
  4371. (function (module, exports) {
  4372. exports.__esModule = true;
  4373. exports["default"] = void 0;
  4374. var _namespace = _interopRequireDefault(namespaceExports);
  4375. var _types = types$1;
  4376. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4377. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4378. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4379. var Tag = /*#__PURE__*/function (_Namespace) {
  4380. _inheritsLoose(Tag, _Namespace);
  4381. function Tag(opts) {
  4382. var _this;
  4383. _this = _Namespace.call(this, opts) || this;
  4384. _this.type = _types.TAG;
  4385. return _this;
  4386. }
  4387. return Tag;
  4388. }(_namespace["default"]);
  4389. exports["default"] = Tag;
  4390. module.exports = exports.default;
  4391. } (tag$1, tagExports));
  4392. var stringExports = {};
  4393. var string$1 = {
  4394. get exports(){ return stringExports; },
  4395. set exports(v){ stringExports = v; },
  4396. };
  4397. (function (module, exports) {
  4398. exports.__esModule = true;
  4399. exports["default"] = void 0;
  4400. var _node = _interopRequireDefault(nodeExports);
  4401. var _types = types$1;
  4402. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4403. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4404. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4405. var String = /*#__PURE__*/function (_Node) {
  4406. _inheritsLoose(String, _Node);
  4407. function String(opts) {
  4408. var _this;
  4409. _this = _Node.call(this, opts) || this;
  4410. _this.type = _types.STRING;
  4411. return _this;
  4412. }
  4413. return String;
  4414. }(_node["default"]);
  4415. exports["default"] = String;
  4416. module.exports = exports.default;
  4417. } (string$1, stringExports));
  4418. var pseudoExports = {};
  4419. var pseudo$1 = {
  4420. get exports(){ return pseudoExports; },
  4421. set exports(v){ pseudoExports = v; },
  4422. };
  4423. (function (module, exports) {
  4424. exports.__esModule = true;
  4425. exports["default"] = void 0;
  4426. var _container = _interopRequireDefault(containerExports);
  4427. var _types = types$1;
  4428. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4429. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4430. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4431. var Pseudo = /*#__PURE__*/function (_Container) {
  4432. _inheritsLoose(Pseudo, _Container);
  4433. function Pseudo(opts) {
  4434. var _this;
  4435. _this = _Container.call(this, opts) || this;
  4436. _this.type = _types.PSEUDO;
  4437. return _this;
  4438. }
  4439. var _proto = Pseudo.prototype;
  4440. _proto.toString = function toString() {
  4441. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  4442. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  4443. };
  4444. return Pseudo;
  4445. }(_container["default"]);
  4446. exports["default"] = Pseudo;
  4447. module.exports = exports.default;
  4448. } (pseudo$1, pseudoExports));
  4449. var attribute$1 = {};
  4450. /**
  4451. * For Node.js, simply re-export the core `util.deprecate` function.
  4452. */
  4453. var node = require$$2.deprecate;
  4454. (function (exports) {
  4455. exports.__esModule = true;
  4456. exports.unescapeValue = unescapeValue;
  4457. exports["default"] = void 0;
  4458. var _cssesc = _interopRequireDefault(cssesc_1);
  4459. var _unesc = _interopRequireDefault(unescExports);
  4460. var _namespace = _interopRequireDefault(namespaceExports);
  4461. var _types = types$1;
  4462. var _CSSESC_QUOTE_OPTIONS;
  4463. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4464. 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); } }
  4465. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  4466. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4467. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4468. var deprecate = node;
  4469. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  4470. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  4471. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  4472. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  4473. function unescapeValue(value) {
  4474. var deprecatedUsage = false;
  4475. var quoteMark = null;
  4476. var unescaped = value;
  4477. var m = unescaped.match(WRAPPED_IN_QUOTES);
  4478. if (m) {
  4479. quoteMark = m[1];
  4480. unescaped = m[2];
  4481. }
  4482. unescaped = (0, _unesc["default"])(unescaped);
  4483. if (unescaped !== value) {
  4484. deprecatedUsage = true;
  4485. }
  4486. return {
  4487. deprecatedUsage: deprecatedUsage,
  4488. unescaped: unescaped,
  4489. quoteMark: quoteMark
  4490. };
  4491. }
  4492. function handleDeprecatedContructorOpts(opts) {
  4493. if (opts.quoteMark !== undefined) {
  4494. return opts;
  4495. }
  4496. if (opts.value === undefined) {
  4497. return opts;
  4498. }
  4499. warnOfDeprecatedConstructor();
  4500. var _unescapeValue = unescapeValue(opts.value),
  4501. quoteMark = _unescapeValue.quoteMark,
  4502. unescaped = _unescapeValue.unescaped;
  4503. if (!opts.raws) {
  4504. opts.raws = {};
  4505. }
  4506. if (opts.raws.value === undefined) {
  4507. opts.raws.value = opts.value;
  4508. }
  4509. opts.value = unescaped;
  4510. opts.quoteMark = quoteMark;
  4511. return opts;
  4512. }
  4513. var Attribute = /*#__PURE__*/function (_Namespace) {
  4514. _inheritsLoose(Attribute, _Namespace);
  4515. function Attribute(opts) {
  4516. var _this;
  4517. if (opts === void 0) {
  4518. opts = {};
  4519. }
  4520. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  4521. _this.type = _types.ATTRIBUTE;
  4522. _this.raws = _this.raws || {};
  4523. Object.defineProperty(_this.raws, 'unquoted', {
  4524. get: deprecate(function () {
  4525. return _this.value;
  4526. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  4527. set: deprecate(function () {
  4528. return _this.value;
  4529. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  4530. });
  4531. _this._constructed = true;
  4532. return _this;
  4533. }
  4534. /**
  4535. * Returns the Attribute's value quoted such that it would be legal to use
  4536. * in the value of a css file. The original value's quotation setting
  4537. * used for stringification is left unchanged. See `setValue(value, options)`
  4538. * if you want to control the quote settings of a new value for the attribute.
  4539. *
  4540. * You can also change the quotation used for the current value by setting quoteMark.
  4541. *
  4542. * Options:
  4543. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  4544. * option is not set, the original value for quoteMark will be used. If
  4545. * indeterminate, a double quote is used. The legal values are:
  4546. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  4547. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  4548. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  4549. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  4550. * over the quoteMark option value.
  4551. * * smart {boolean} - if true, will select a quote mark based on the value
  4552. * and the other options specified here. See the `smartQuoteMark()`
  4553. * method.
  4554. **/
  4555. var _proto = Attribute.prototype;
  4556. _proto.getQuotedValue = function getQuotedValue(options) {
  4557. if (options === void 0) {
  4558. options = {};
  4559. }
  4560. var quoteMark = this._determineQuoteMark(options);
  4561. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  4562. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  4563. return escaped;
  4564. };
  4565. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  4566. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  4567. }
  4568. /**
  4569. * Set the unescaped value with the specified quotation options. The value
  4570. * provided must not include any wrapping quote marks -- those quotes will
  4571. * be interpreted as part of the value and escaped accordingly.
  4572. */
  4573. ;
  4574. _proto.setValue = function setValue(value, options) {
  4575. if (options === void 0) {
  4576. options = {};
  4577. }
  4578. this._value = value;
  4579. this._quoteMark = this._determineQuoteMark(options);
  4580. this._syncRawValue();
  4581. }
  4582. /**
  4583. * Intelligently select a quoteMark value based on the value's contents. If
  4584. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  4585. * mark will be picked that minimizes the number of escapes.
  4586. *
  4587. * If there's no clear winner, the quote mark from these options is used,
  4588. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  4589. * true). If the quoteMark is unspecified, a double quote is used.
  4590. *
  4591. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  4592. * from the quoteValue method.
  4593. */
  4594. ;
  4595. _proto.smartQuoteMark = function smartQuoteMark(options) {
  4596. var v = this.value;
  4597. var numSingleQuotes = v.replace(/[^']/g, '').length;
  4598. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  4599. if (numSingleQuotes + numDoubleQuotes === 0) {
  4600. var escaped = (0, _cssesc["default"])(v, {
  4601. isIdentifier: true
  4602. });
  4603. if (escaped === v) {
  4604. return Attribute.NO_QUOTE;
  4605. } else {
  4606. var pref = this.preferredQuoteMark(options);
  4607. if (pref === Attribute.NO_QUOTE) {
  4608. // pick a quote mark that isn't none and see if it's smaller
  4609. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  4610. var opts = CSSESC_QUOTE_OPTIONS[quote];
  4611. var quoteValue = (0, _cssesc["default"])(v, opts);
  4612. if (quoteValue.length < escaped.length) {
  4613. return quote;
  4614. }
  4615. }
  4616. return pref;
  4617. }
  4618. } else if (numDoubleQuotes === numSingleQuotes) {
  4619. return this.preferredQuoteMark(options);
  4620. } else if (numDoubleQuotes < numSingleQuotes) {
  4621. return Attribute.DOUBLE_QUOTE;
  4622. } else {
  4623. return Attribute.SINGLE_QUOTE;
  4624. }
  4625. }
  4626. /**
  4627. * Selects the preferred quote mark based on the options and the current quote mark value.
  4628. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  4629. * instead.
  4630. */
  4631. ;
  4632. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  4633. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  4634. if (quoteMark === undefined) {
  4635. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  4636. }
  4637. if (quoteMark === undefined) {
  4638. quoteMark = Attribute.DOUBLE_QUOTE;
  4639. }
  4640. return quoteMark;
  4641. };
  4642. _proto._syncRawValue = function _syncRawValue() {
  4643. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  4644. if (rawValue === this._value) {
  4645. if (this.raws) {
  4646. delete this.raws.value;
  4647. }
  4648. } else {
  4649. this.raws.value = rawValue;
  4650. }
  4651. };
  4652. _proto._handleEscapes = function _handleEscapes(prop, value) {
  4653. if (this._constructed) {
  4654. var escaped = (0, _cssesc["default"])(value, {
  4655. isIdentifier: true
  4656. });
  4657. if (escaped !== value) {
  4658. this.raws[prop] = escaped;
  4659. } else {
  4660. delete this.raws[prop];
  4661. }
  4662. }
  4663. };
  4664. _proto._spacesFor = function _spacesFor(name) {
  4665. var attrSpaces = {
  4666. before: '',
  4667. after: ''
  4668. };
  4669. var spaces = this.spaces[name] || {};
  4670. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  4671. return Object.assign(attrSpaces, spaces, rawSpaces);
  4672. };
  4673. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  4674. if (spaceName === void 0) {
  4675. spaceName = name;
  4676. }
  4677. if (concat === void 0) {
  4678. concat = defaultAttrConcat;
  4679. }
  4680. var attrSpaces = this._spacesFor(spaceName);
  4681. return concat(this.stringifyProperty(name), attrSpaces);
  4682. }
  4683. /**
  4684. * returns the offset of the attribute part specified relative to the
  4685. * start of the node of the output string.
  4686. *
  4687. * * "ns" - alias for "namespace"
  4688. * * "namespace" - the namespace if it exists.
  4689. * * "attribute" - the attribute name
  4690. * * "attributeNS" - the start of the attribute or its namespace
  4691. * * "operator" - the match operator of the attribute
  4692. * * "value" - The value (string or identifier)
  4693. * * "insensitive" - the case insensitivity flag;
  4694. * @param part One of the possible values inside an attribute.
  4695. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  4696. */
  4697. ;
  4698. _proto.offsetOf = function offsetOf(name) {
  4699. var count = 1;
  4700. var attributeSpaces = this._spacesFor("attribute");
  4701. count += attributeSpaces.before.length;
  4702. if (name === "namespace" || name === "ns") {
  4703. return this.namespace ? count : -1;
  4704. }
  4705. if (name === "attributeNS") {
  4706. return count;
  4707. }
  4708. count += this.namespaceString.length;
  4709. if (this.namespace) {
  4710. count += 1;
  4711. }
  4712. if (name === "attribute") {
  4713. return count;
  4714. }
  4715. count += this.stringifyProperty("attribute").length;
  4716. count += attributeSpaces.after.length;
  4717. var operatorSpaces = this._spacesFor("operator");
  4718. count += operatorSpaces.before.length;
  4719. var operator = this.stringifyProperty("operator");
  4720. if (name === "operator") {
  4721. return operator ? count : -1;
  4722. }
  4723. count += operator.length;
  4724. count += operatorSpaces.after.length;
  4725. var valueSpaces = this._spacesFor("value");
  4726. count += valueSpaces.before.length;
  4727. var value = this.stringifyProperty("value");
  4728. if (name === "value") {
  4729. return value ? count : -1;
  4730. }
  4731. count += value.length;
  4732. count += valueSpaces.after.length;
  4733. var insensitiveSpaces = this._spacesFor("insensitive");
  4734. count += insensitiveSpaces.before.length;
  4735. if (name === "insensitive") {
  4736. return this.insensitive ? count : -1;
  4737. }
  4738. return -1;
  4739. };
  4740. _proto.toString = function toString() {
  4741. var _this2 = this;
  4742. var selector = [this.rawSpaceBefore, '['];
  4743. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  4744. if (this.operator && (this.value || this.value === '')) {
  4745. selector.push(this._stringFor('operator'));
  4746. selector.push(this._stringFor('value'));
  4747. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  4748. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  4749. attrSpaces.before = " ";
  4750. }
  4751. return defaultAttrConcat(attrValue, attrSpaces);
  4752. }));
  4753. }
  4754. selector.push(']');
  4755. selector.push(this.rawSpaceAfter);
  4756. return selector.join('');
  4757. };
  4758. _createClass(Attribute, [{
  4759. key: "quoted",
  4760. get: function get() {
  4761. var qm = this.quoteMark;
  4762. return qm === "'" || qm === '"';
  4763. },
  4764. set: function set(value) {
  4765. warnOfDeprecatedQuotedAssignment();
  4766. }
  4767. /**
  4768. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  4769. * returns `null` if the value is not quoted.
  4770. * returns `undefined` if the quotation state is unknown (this can happen when
  4771. * the attribute is constructed without specifying a quote mark.)
  4772. */
  4773. }, {
  4774. key: "quoteMark",
  4775. get: function get() {
  4776. return this._quoteMark;
  4777. }
  4778. /**
  4779. * Set the quote mark to be used by this attribute's value.
  4780. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  4781. * value is updated accordingly.
  4782. *
  4783. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  4784. */
  4785. ,
  4786. set: function set(quoteMark) {
  4787. if (!this._constructed) {
  4788. this._quoteMark = quoteMark;
  4789. return;
  4790. }
  4791. if (this._quoteMark !== quoteMark) {
  4792. this._quoteMark = quoteMark;
  4793. this._syncRawValue();
  4794. }
  4795. }
  4796. }, {
  4797. key: "qualifiedAttribute",
  4798. get: function get() {
  4799. return this.qualifiedName(this.raws.attribute || this.attribute);
  4800. }
  4801. }, {
  4802. key: "insensitiveFlag",
  4803. get: function get() {
  4804. return this.insensitive ? 'i' : '';
  4805. }
  4806. }, {
  4807. key: "value",
  4808. get: function get() {
  4809. return this._value;
  4810. },
  4811. set:
  4812. /**
  4813. * Before 3.0, the value had to be set to an escaped value including any wrapped
  4814. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  4815. * is unescaped during parsing and any quote marks are removed.
  4816. *
  4817. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  4818. * a deprecation warning is raised when the new value contains any characters that would
  4819. * require escaping (including if it contains wrapped quotes).
  4820. *
  4821. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  4822. * how the new value is quoted.
  4823. */
  4824. function set(v) {
  4825. if (this._constructed) {
  4826. var _unescapeValue2 = unescapeValue(v),
  4827. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  4828. unescaped = _unescapeValue2.unescaped,
  4829. quoteMark = _unescapeValue2.quoteMark;
  4830. if (deprecatedUsage) {
  4831. warnOfDeprecatedValueAssignment();
  4832. }
  4833. if (unescaped === this._value && quoteMark === this._quoteMark) {
  4834. return;
  4835. }
  4836. this._value = unescaped;
  4837. this._quoteMark = quoteMark;
  4838. this._syncRawValue();
  4839. } else {
  4840. this._value = v;
  4841. }
  4842. }
  4843. }, {
  4844. key: "insensitive",
  4845. get: function get() {
  4846. return this._insensitive;
  4847. }
  4848. /**
  4849. * Set the case insensitive flag.
  4850. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  4851. * of the attribute is updated accordingly.
  4852. *
  4853. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  4854. */
  4855. ,
  4856. set: function set(insensitive) {
  4857. if (!insensitive) {
  4858. this._insensitive = false; // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  4859. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  4860. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  4861. this.raws.insensitiveFlag = undefined;
  4862. }
  4863. }
  4864. this._insensitive = insensitive;
  4865. }
  4866. }, {
  4867. key: "attribute",
  4868. get: function get() {
  4869. return this._attribute;
  4870. },
  4871. set: function set(name) {
  4872. this._handleEscapes("attribute", name);
  4873. this._attribute = name;
  4874. }
  4875. }]);
  4876. return Attribute;
  4877. }(_namespace["default"]);
  4878. exports["default"] = Attribute;
  4879. Attribute.NO_QUOTE = null;
  4880. Attribute.SINGLE_QUOTE = "'";
  4881. Attribute.DOUBLE_QUOTE = '"';
  4882. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  4883. "'": {
  4884. quotes: 'single',
  4885. wrap: true
  4886. },
  4887. '"': {
  4888. quotes: 'double',
  4889. wrap: true
  4890. }
  4891. }, _CSSESC_QUOTE_OPTIONS[null] = {
  4892. isIdentifier: true
  4893. }, _CSSESC_QUOTE_OPTIONS);
  4894. function defaultAttrConcat(attrValue, attrSpaces) {
  4895. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  4896. }
  4897. } (attribute$1));
  4898. var universalExports = {};
  4899. var universal$1 = {
  4900. get exports(){ return universalExports; },
  4901. set exports(v){ universalExports = v; },
  4902. };
  4903. (function (module, exports) {
  4904. exports.__esModule = true;
  4905. exports["default"] = void 0;
  4906. var _namespace = _interopRequireDefault(namespaceExports);
  4907. var _types = types$1;
  4908. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4909. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4910. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4911. var Universal = /*#__PURE__*/function (_Namespace) {
  4912. _inheritsLoose(Universal, _Namespace);
  4913. function Universal(opts) {
  4914. var _this;
  4915. _this = _Namespace.call(this, opts) || this;
  4916. _this.type = _types.UNIVERSAL;
  4917. _this.value = '*';
  4918. return _this;
  4919. }
  4920. return Universal;
  4921. }(_namespace["default"]);
  4922. exports["default"] = Universal;
  4923. module.exports = exports.default;
  4924. } (universal$1, universalExports));
  4925. var combinatorExports = {};
  4926. var combinator$2 = {
  4927. get exports(){ return combinatorExports; },
  4928. set exports(v){ combinatorExports = v; },
  4929. };
  4930. (function (module, exports) {
  4931. exports.__esModule = true;
  4932. exports["default"] = void 0;
  4933. var _node = _interopRequireDefault(nodeExports);
  4934. var _types = types$1;
  4935. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4936. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4937. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4938. var Combinator = /*#__PURE__*/function (_Node) {
  4939. _inheritsLoose(Combinator, _Node);
  4940. function Combinator(opts) {
  4941. var _this;
  4942. _this = _Node.call(this, opts) || this;
  4943. _this.type = _types.COMBINATOR;
  4944. return _this;
  4945. }
  4946. return Combinator;
  4947. }(_node["default"]);
  4948. exports["default"] = Combinator;
  4949. module.exports = exports.default;
  4950. } (combinator$2, combinatorExports));
  4951. var nestingExports = {};
  4952. var nesting$1 = {
  4953. get exports(){ return nestingExports; },
  4954. set exports(v){ nestingExports = v; },
  4955. };
  4956. (function (module, exports) {
  4957. exports.__esModule = true;
  4958. exports["default"] = void 0;
  4959. var _node = _interopRequireDefault(nodeExports);
  4960. var _types = types$1;
  4961. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4962. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4963. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4964. var Nesting = /*#__PURE__*/function (_Node) {
  4965. _inheritsLoose(Nesting, _Node);
  4966. function Nesting(opts) {
  4967. var _this;
  4968. _this = _Node.call(this, opts) || this;
  4969. _this.type = _types.NESTING;
  4970. _this.value = '&';
  4971. return _this;
  4972. }
  4973. return Nesting;
  4974. }(_node["default"]);
  4975. exports["default"] = Nesting;
  4976. module.exports = exports.default;
  4977. } (nesting$1, nestingExports));
  4978. var sortAscendingExports = {};
  4979. var sortAscending = {
  4980. get exports(){ return sortAscendingExports; },
  4981. set exports(v){ sortAscendingExports = v; },
  4982. };
  4983. (function (module, exports) {
  4984. exports.__esModule = true;
  4985. exports["default"] = sortAscending;
  4986. function sortAscending(list) {
  4987. return list.sort(function (a, b) {
  4988. return a - b;
  4989. });
  4990. }
  4991. module.exports = exports.default;
  4992. } (sortAscending, sortAscendingExports));
  4993. var tokenize = {};
  4994. var tokenTypes = {};
  4995. tokenTypes.__esModule = true;
  4996. tokenTypes.combinator = tokenTypes.word = tokenTypes.comment = tokenTypes.str = tokenTypes.tab = tokenTypes.newline = tokenTypes.feed = tokenTypes.cr = tokenTypes.backslash = tokenTypes.bang = tokenTypes.slash = tokenTypes.doubleQuote = tokenTypes.singleQuote = tokenTypes.space = tokenTypes.greaterThan = tokenTypes.pipe = tokenTypes.equals = tokenTypes.plus = tokenTypes.caret = tokenTypes.tilde = tokenTypes.dollar = tokenTypes.closeSquare = tokenTypes.openSquare = tokenTypes.closeParenthesis = tokenTypes.openParenthesis = tokenTypes.semicolon = tokenTypes.colon = tokenTypes.comma = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0;
  4997. var ampersand = 38; // `&`.charCodeAt(0);
  4998. tokenTypes.ampersand = ampersand;
  4999. var asterisk = 42; // `*`.charCodeAt(0);
  5000. tokenTypes.asterisk = asterisk;
  5001. var at = 64; // `@`.charCodeAt(0);
  5002. tokenTypes.at = at;
  5003. var comma$1 = 44; // `,`.charCodeAt(0);
  5004. tokenTypes.comma = comma$1;
  5005. var colon$1 = 58; // `:`.charCodeAt(0);
  5006. tokenTypes.colon = colon$1;
  5007. var semicolon = 59; // `;`.charCodeAt(0);
  5008. tokenTypes.semicolon = semicolon;
  5009. var openParenthesis = 40; // `(`.charCodeAt(0);
  5010. tokenTypes.openParenthesis = openParenthesis;
  5011. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5012. tokenTypes.closeParenthesis = closeParenthesis;
  5013. var openSquare = 91; // `[`.charCodeAt(0);
  5014. tokenTypes.openSquare = openSquare;
  5015. var closeSquare = 93; // `]`.charCodeAt(0);
  5016. tokenTypes.closeSquare = closeSquare;
  5017. var dollar = 36; // `$`.charCodeAt(0);
  5018. tokenTypes.dollar = dollar;
  5019. var tilde = 126; // `~`.charCodeAt(0);
  5020. tokenTypes.tilde = tilde;
  5021. var caret = 94; // `^`.charCodeAt(0);
  5022. tokenTypes.caret = caret;
  5023. var plus$1 = 43; // `+`.charCodeAt(0);
  5024. tokenTypes.plus = plus$1;
  5025. var equals = 61; // `=`.charCodeAt(0);
  5026. tokenTypes.equals = equals;
  5027. var pipe = 124; // `|`.charCodeAt(0);
  5028. tokenTypes.pipe = pipe;
  5029. var greaterThan = 62; // `>`.charCodeAt(0);
  5030. tokenTypes.greaterThan = greaterThan;
  5031. var space = 32; // ` `.charCodeAt(0);
  5032. tokenTypes.space = space;
  5033. var singleQuote$1 = 39; // `'`.charCodeAt(0);
  5034. tokenTypes.singleQuote = singleQuote$1;
  5035. var doubleQuote$1 = 34; // `"`.charCodeAt(0);
  5036. tokenTypes.doubleQuote = doubleQuote$1;
  5037. var slash$1 = 47; // `/`.charCodeAt(0);
  5038. tokenTypes.slash = slash$1;
  5039. var bang = 33; // `!`.charCodeAt(0);
  5040. tokenTypes.bang = bang;
  5041. var backslash$1 = 92; // '\\'.charCodeAt(0);
  5042. tokenTypes.backslash = backslash$1;
  5043. var cr = 13; // '\r'.charCodeAt(0);
  5044. tokenTypes.cr = cr;
  5045. var feed = 12; // '\f'.charCodeAt(0);
  5046. tokenTypes.feed = feed;
  5047. var newline = 10; // '\n'.charCodeAt(0);
  5048. tokenTypes.newline = newline;
  5049. var tab = 9; // '\t'.charCodeAt(0);
  5050. // Expose aliases primarily for readability.
  5051. tokenTypes.tab = tab;
  5052. var str = singleQuote$1; // No good single character representation!
  5053. tokenTypes.str = str;
  5054. var comment$1 = -1;
  5055. tokenTypes.comment = comment$1;
  5056. var word = -2;
  5057. tokenTypes.word = word;
  5058. var combinator$1 = -3;
  5059. tokenTypes.combinator = combinator$1;
  5060. (function (exports) {
  5061. exports.__esModule = true;
  5062. exports["default"] = tokenize;
  5063. exports.FIELDS = void 0;
  5064. var t = _interopRequireWildcard(tokenTypes);
  5065. var _unescapable, _wordDelimiters;
  5066. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  5067. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }
  5068. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5069. 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);
  5070. var hex = {};
  5071. var hexChars = "0123456789abcdefABCDEF";
  5072. for (var i = 0; i < hexChars.length; i++) {
  5073. hex[hexChars.charCodeAt(i)] = true;
  5074. }
  5075. /**
  5076. * Returns the last index of the bar css word
  5077. * @param {string} css The string in which the word begins
  5078. * @param {number} start The index into the string where word's first letter occurs
  5079. */
  5080. function consumeWord(css, start) {
  5081. var next = start;
  5082. var code;
  5083. do {
  5084. code = css.charCodeAt(next);
  5085. if (wordDelimiters[code]) {
  5086. return next - 1;
  5087. } else if (code === t.backslash) {
  5088. next = consumeEscape(css, next) + 1;
  5089. } else {
  5090. // All other characters are part of the word
  5091. next++;
  5092. }
  5093. } while (next < css.length);
  5094. return next - 1;
  5095. }
  5096. /**
  5097. * Returns the last index of the escape sequence
  5098. * @param {string} css The string in which the sequence begins
  5099. * @param {number} start The index into the string where escape character (`\`) occurs.
  5100. */
  5101. function consumeEscape(css, start) {
  5102. var next = start;
  5103. var code = css.charCodeAt(next + 1);
  5104. if (unescapable[code]) ; else if (hex[code]) {
  5105. var hexDigits = 0; // consume up to 6 hex chars
  5106. do {
  5107. next++;
  5108. hexDigits++;
  5109. code = css.charCodeAt(next + 1);
  5110. } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape
  5111. if (hexDigits < 6 && code === t.space) {
  5112. next++;
  5113. }
  5114. } else {
  5115. // the next char is part of the current word
  5116. next++;
  5117. }
  5118. return next;
  5119. }
  5120. var FIELDS = {
  5121. TYPE: 0,
  5122. START_LINE: 1,
  5123. START_COL: 2,
  5124. END_LINE: 3,
  5125. END_COL: 4,
  5126. START_POS: 5,
  5127. END_POS: 6
  5128. };
  5129. exports.FIELDS = FIELDS;
  5130. function tokenize(input) {
  5131. var tokens = [];
  5132. var css = input.css.valueOf();
  5133. var _css = css,
  5134. length = _css.length;
  5135. var offset = -1;
  5136. var line = 1;
  5137. var start = 0;
  5138. var end = 0;
  5139. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  5140. function unclosed(what, fix) {
  5141. if (input.safe) {
  5142. // fyi: this is never set to true.
  5143. css += fix;
  5144. next = css.length - 1;
  5145. } else {
  5146. throw input.error('Unclosed ' + what, line, start - offset, start);
  5147. }
  5148. }
  5149. while (start < length) {
  5150. code = css.charCodeAt(start);
  5151. if (code === t.newline) {
  5152. offset = start;
  5153. line += 1;
  5154. }
  5155. switch (code) {
  5156. case t.space:
  5157. case t.tab:
  5158. case t.newline:
  5159. case t.cr:
  5160. case t.feed:
  5161. next = start;
  5162. do {
  5163. next += 1;
  5164. code = css.charCodeAt(next);
  5165. if (code === t.newline) {
  5166. offset = next;
  5167. line += 1;
  5168. }
  5169. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  5170. tokenType = t.space;
  5171. endLine = line;
  5172. endColumn = next - offset - 1;
  5173. end = next;
  5174. break;
  5175. case t.plus:
  5176. case t.greaterThan:
  5177. case t.tilde:
  5178. case t.pipe:
  5179. next = start;
  5180. do {
  5181. next += 1;
  5182. code = css.charCodeAt(next);
  5183. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  5184. tokenType = t.combinator;
  5185. endLine = line;
  5186. endColumn = start - offset;
  5187. end = next;
  5188. break;
  5189. // Consume these characters as single tokens.
  5190. case t.asterisk:
  5191. case t.ampersand:
  5192. case t.bang:
  5193. case t.comma:
  5194. case t.equals:
  5195. case t.dollar:
  5196. case t.caret:
  5197. case t.openSquare:
  5198. case t.closeSquare:
  5199. case t.colon:
  5200. case t.semicolon:
  5201. case t.openParenthesis:
  5202. case t.closeParenthesis:
  5203. next = start;
  5204. tokenType = code;
  5205. endLine = line;
  5206. endColumn = start - offset;
  5207. end = next + 1;
  5208. break;
  5209. case t.singleQuote:
  5210. case t.doubleQuote:
  5211. quote = code === t.singleQuote ? "'" : '"';
  5212. next = start;
  5213. do {
  5214. escaped = false;
  5215. next = css.indexOf(quote, next + 1);
  5216. if (next === -1) {
  5217. unclosed('quote', quote);
  5218. }
  5219. escapePos = next;
  5220. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  5221. escapePos -= 1;
  5222. escaped = !escaped;
  5223. }
  5224. } while (escaped);
  5225. tokenType = t.str;
  5226. endLine = line;
  5227. endColumn = start - offset;
  5228. end = next + 1;
  5229. break;
  5230. default:
  5231. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  5232. next = css.indexOf('*/', start + 2) + 1;
  5233. if (next === 0) {
  5234. unclosed('comment', '*/');
  5235. }
  5236. content = css.slice(start, next + 1);
  5237. lines = content.split('\n');
  5238. last = lines.length - 1;
  5239. if (last > 0) {
  5240. nextLine = line + last;
  5241. nextOffset = next - lines[last].length;
  5242. } else {
  5243. nextLine = line;
  5244. nextOffset = offset;
  5245. }
  5246. tokenType = t.comment;
  5247. line = nextLine;
  5248. endLine = nextLine;
  5249. endColumn = next - nextOffset;
  5250. } else if (code === t.slash) {
  5251. next = start;
  5252. tokenType = code;
  5253. endLine = line;
  5254. endColumn = start - offset;
  5255. end = next + 1;
  5256. } else {
  5257. next = consumeWord(css, start);
  5258. tokenType = t.word;
  5259. endLine = line;
  5260. endColumn = next - offset;
  5261. }
  5262. end = next + 1;
  5263. break;
  5264. } // Ensure that the token structure remains consistent
  5265. tokens.push([tokenType, // [0] Token type
  5266. line, // [1] Starting line
  5267. start - offset, // [2] Starting column
  5268. endLine, // [3] Ending line
  5269. endColumn, // [4] Ending column
  5270. start, // [5] Start position / Source index
  5271. end // [6] End position
  5272. ]); // Reset offset for the next token
  5273. if (nextOffset) {
  5274. offset = nextOffset;
  5275. nextOffset = null;
  5276. }
  5277. start = end;
  5278. }
  5279. return tokens;
  5280. }
  5281. } (tokenize));
  5282. (function (module, exports) {
  5283. exports.__esModule = true;
  5284. exports["default"] = void 0;
  5285. var _root = _interopRequireDefault(rootExports);
  5286. var _selector = _interopRequireDefault(selectorExports);
  5287. var _className = _interopRequireDefault(classNameExports);
  5288. var _comment = _interopRequireDefault(commentExports);
  5289. var _id = _interopRequireDefault(idExports);
  5290. var _tag = _interopRequireDefault(tagExports);
  5291. var _string = _interopRequireDefault(stringExports);
  5292. var _pseudo = _interopRequireDefault(pseudoExports);
  5293. var _attribute = _interopRequireWildcard(attribute$1);
  5294. var _universal = _interopRequireDefault(universalExports);
  5295. var _combinator = _interopRequireDefault(combinatorExports);
  5296. var _nesting = _interopRequireDefault(nestingExports);
  5297. var _sortAscending = _interopRequireDefault(sortAscendingExports);
  5298. var _tokenize = _interopRequireWildcard(tokenize);
  5299. var tokens = _interopRequireWildcard(tokenTypes);
  5300. var types = _interopRequireWildcard(types$1);
  5301. var _util = util$6;
  5302. var _WHITESPACE_TOKENS, _Object$assign;
  5303. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  5304. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }
  5305. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5306. 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); } }
  5307. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  5308. 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);
  5309. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  5310. function tokenStart(token) {
  5311. return {
  5312. line: token[_tokenize.FIELDS.START_LINE],
  5313. column: token[_tokenize.FIELDS.START_COL]
  5314. };
  5315. }
  5316. function tokenEnd(token) {
  5317. return {
  5318. line: token[_tokenize.FIELDS.END_LINE],
  5319. column: token[_tokenize.FIELDS.END_COL]
  5320. };
  5321. }
  5322. function getSource(startLine, startColumn, endLine, endColumn) {
  5323. return {
  5324. start: {
  5325. line: startLine,
  5326. column: startColumn
  5327. },
  5328. end: {
  5329. line: endLine,
  5330. column: endColumn
  5331. }
  5332. };
  5333. }
  5334. function getTokenSource(token) {
  5335. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  5336. }
  5337. function getTokenSourceSpan(startToken, endToken) {
  5338. if (!startToken) {
  5339. return undefined;
  5340. }
  5341. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  5342. }
  5343. function unescapeProp(node, prop) {
  5344. var value = node[prop];
  5345. if (typeof value !== "string") {
  5346. return;
  5347. }
  5348. if (value.indexOf("\\") !== -1) {
  5349. (0, _util.ensureObject)(node, 'raws');
  5350. node[prop] = (0, _util.unesc)(value);
  5351. if (node.raws[prop] === undefined) {
  5352. node.raws[prop] = value;
  5353. }
  5354. }
  5355. return node;
  5356. }
  5357. function indexesOf(array, item) {
  5358. var i = -1;
  5359. var indexes = [];
  5360. while ((i = array.indexOf(item, i + 1)) !== -1) {
  5361. indexes.push(i);
  5362. }
  5363. return indexes;
  5364. }
  5365. function uniqs() {
  5366. var list = Array.prototype.concat.apply([], arguments);
  5367. return list.filter(function (item, i) {
  5368. return i === list.indexOf(item);
  5369. });
  5370. }
  5371. var Parser = /*#__PURE__*/function () {
  5372. function Parser(rule, options) {
  5373. if (options === void 0) {
  5374. options = {};
  5375. }
  5376. this.rule = rule;
  5377. this.options = Object.assign({
  5378. lossy: false,
  5379. safe: false
  5380. }, options);
  5381. this.position = 0;
  5382. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  5383. this.tokens = (0, _tokenize["default"])({
  5384. css: this.css,
  5385. error: this._errorGenerator(),
  5386. safe: this.options.safe
  5387. });
  5388. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  5389. this.root = new _root["default"]({
  5390. source: rootSource
  5391. });
  5392. this.root.errorGenerator = this._errorGenerator();
  5393. var selector = new _selector["default"]({
  5394. source: {
  5395. start: {
  5396. line: 1,
  5397. column: 1
  5398. }
  5399. }
  5400. });
  5401. this.root.append(selector);
  5402. this.current = selector;
  5403. this.loop();
  5404. }
  5405. var _proto = Parser.prototype;
  5406. _proto._errorGenerator = function _errorGenerator() {
  5407. var _this = this;
  5408. return function (message, errorOptions) {
  5409. if (typeof _this.rule === 'string') {
  5410. return new Error(message);
  5411. }
  5412. return _this.rule.error(message, errorOptions);
  5413. };
  5414. };
  5415. _proto.attribute = function attribute() {
  5416. var attr = [];
  5417. var startingToken = this.currToken;
  5418. this.position++;
  5419. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  5420. attr.push(this.currToken);
  5421. this.position++;
  5422. }
  5423. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  5424. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  5425. }
  5426. var len = attr.length;
  5427. var node = {
  5428. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  5429. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  5430. };
  5431. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  5432. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  5433. }
  5434. var pos = 0;
  5435. var spaceBefore = '';
  5436. var commentBefore = '';
  5437. var lastAdded = null;
  5438. var spaceAfterMeaningfulToken = false;
  5439. while (pos < len) {
  5440. var token = attr[pos];
  5441. var content = this.content(token);
  5442. var next = attr[pos + 1];
  5443. switch (token[_tokenize.FIELDS.TYPE]) {
  5444. case tokens.space:
  5445. // if (
  5446. // len === 1 ||
  5447. // pos === 0 && this.content(next) === '|'
  5448. // ) {
  5449. // return this.expected('attribute', token[TOKEN.START_POS], content);
  5450. // }
  5451. spaceAfterMeaningfulToken = true;
  5452. if (this.options.lossy) {
  5453. break;
  5454. }
  5455. if (lastAdded) {
  5456. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  5457. var prevContent = node.spaces[lastAdded].after || '';
  5458. node.spaces[lastAdded].after = prevContent + content;
  5459. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  5460. if (existingComment) {
  5461. node.raws.spaces[lastAdded].after = existingComment + content;
  5462. }
  5463. } else {
  5464. spaceBefore = spaceBefore + content;
  5465. commentBefore = commentBefore + content;
  5466. }
  5467. break;
  5468. case tokens.asterisk:
  5469. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  5470. node.operator = content;
  5471. lastAdded = 'operator';
  5472. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  5473. if (spaceBefore) {
  5474. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  5475. node.spaces.attribute.before = spaceBefore;
  5476. spaceBefore = '';
  5477. }
  5478. if (commentBefore) {
  5479. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  5480. node.raws.spaces.attribute.before = spaceBefore;
  5481. commentBefore = '';
  5482. }
  5483. node.namespace = (node.namespace || "") + content;
  5484. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  5485. if (rawValue) {
  5486. node.raws.namespace += content;
  5487. }
  5488. lastAdded = 'namespace';
  5489. }
  5490. spaceAfterMeaningfulToken = false;
  5491. break;
  5492. case tokens.dollar:
  5493. if (lastAdded === "value") {
  5494. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  5495. node.value += "$";
  5496. if (oldRawValue) {
  5497. node.raws.value = oldRawValue + "$";
  5498. }
  5499. break;
  5500. }
  5501. // Falls through
  5502. case tokens.caret:
  5503. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  5504. node.operator = content;
  5505. lastAdded = 'operator';
  5506. }
  5507. spaceAfterMeaningfulToken = false;
  5508. break;
  5509. case tokens.combinator:
  5510. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  5511. node.operator = content;
  5512. lastAdded = 'operator';
  5513. }
  5514. if (content !== '|') {
  5515. spaceAfterMeaningfulToken = false;
  5516. break;
  5517. }
  5518. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  5519. node.operator = content;
  5520. lastAdded = 'operator';
  5521. } else if (!node.namespace && !node.attribute) {
  5522. node.namespace = true;
  5523. }
  5524. spaceAfterMeaningfulToken = false;
  5525. break;
  5526. case tokens.word:
  5527. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved.
  5528. !node.operator && !node.namespace) {
  5529. node.namespace = content;
  5530. lastAdded = 'namespace';
  5531. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  5532. if (spaceBefore) {
  5533. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  5534. node.spaces.attribute.before = spaceBefore;
  5535. spaceBefore = '';
  5536. }
  5537. if (commentBefore) {
  5538. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  5539. node.raws.spaces.attribute.before = commentBefore;
  5540. commentBefore = '';
  5541. }
  5542. node.attribute = (node.attribute || "") + content;
  5543. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  5544. if (_rawValue) {
  5545. node.raws.attribute += content;
  5546. }
  5547. lastAdded = 'attribute';
  5548. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  5549. var _unescaped = (0, _util.unesc)(content);
  5550. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  5551. var oldValue = node.value || '';
  5552. node.value = oldValue + _unescaped;
  5553. node.quoteMark = null;
  5554. if (_unescaped !== content || _oldRawValue) {
  5555. (0, _util.ensureObject)(node, 'raws');
  5556. node.raws.value = (_oldRawValue || oldValue) + content;
  5557. }
  5558. lastAdded = 'value';
  5559. } else {
  5560. var insensitive = content === 'i' || content === "I";
  5561. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  5562. node.insensitive = insensitive;
  5563. if (!insensitive || content === "I") {
  5564. (0, _util.ensureObject)(node, 'raws');
  5565. node.raws.insensitiveFlag = content;
  5566. }
  5567. lastAdded = 'insensitive';
  5568. if (spaceBefore) {
  5569. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  5570. node.spaces.insensitive.before = spaceBefore;
  5571. spaceBefore = '';
  5572. }
  5573. if (commentBefore) {
  5574. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  5575. node.raws.spaces.insensitive.before = commentBefore;
  5576. commentBefore = '';
  5577. }
  5578. } else if (node.value || node.value === '') {
  5579. lastAdded = 'value';
  5580. node.value += content;
  5581. if (node.raws.value) {
  5582. node.raws.value += content;
  5583. }
  5584. }
  5585. }
  5586. spaceAfterMeaningfulToken = false;
  5587. break;
  5588. case tokens.str:
  5589. if (!node.attribute || !node.operator) {
  5590. return this.error("Expected an attribute followed by an operator preceding the string.", {
  5591. index: token[_tokenize.FIELDS.START_POS]
  5592. });
  5593. }
  5594. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  5595. unescaped = _unescapeValue.unescaped,
  5596. quoteMark = _unescapeValue.quoteMark;
  5597. node.value = unescaped;
  5598. node.quoteMark = quoteMark;
  5599. lastAdded = 'value';
  5600. (0, _util.ensureObject)(node, 'raws');
  5601. node.raws.value = content;
  5602. spaceAfterMeaningfulToken = false;
  5603. break;
  5604. case tokens.equals:
  5605. if (!node.attribute) {
  5606. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  5607. }
  5608. if (node.value) {
  5609. return this.error('Unexpected "=" found; an operator was already defined.', {
  5610. index: token[_tokenize.FIELDS.START_POS]
  5611. });
  5612. }
  5613. node.operator = node.operator ? node.operator + content : content;
  5614. lastAdded = 'operator';
  5615. spaceAfterMeaningfulToken = false;
  5616. break;
  5617. case tokens.comment:
  5618. if (lastAdded) {
  5619. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  5620. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  5621. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  5622. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  5623. node.raws.spaces[lastAdded].after = rawLastComment + content;
  5624. } else {
  5625. var lastValue = node[lastAdded] || '';
  5626. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  5627. (0, _util.ensureObject)(node, 'raws');
  5628. node.raws[lastAdded] = rawLastValue + content;
  5629. }
  5630. } else {
  5631. commentBefore = commentBefore + content;
  5632. }
  5633. break;
  5634. default:
  5635. return this.error("Unexpected \"" + content + "\" found.", {
  5636. index: token[_tokenize.FIELDS.START_POS]
  5637. });
  5638. }
  5639. pos++;
  5640. }
  5641. unescapeProp(node, "attribute");
  5642. unescapeProp(node, "namespace");
  5643. this.newNode(new _attribute["default"](node));
  5644. this.position++;
  5645. }
  5646. /**
  5647. * return a node containing meaningless garbage up to (but not including) the specified token position.
  5648. * if the token position is negative, all remaining tokens are consumed.
  5649. *
  5650. * This returns an array containing a single string node if all whitespace,
  5651. * otherwise an array of comment nodes with space before and after.
  5652. *
  5653. * These tokens are not added to the current selector, the caller can add them or use them to amend
  5654. * a previous node's space metadata.
  5655. *
  5656. * In lossy mode, this returns only comments.
  5657. */
  5658. ;
  5659. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  5660. if (stopPosition < 0) {
  5661. stopPosition = this.tokens.length;
  5662. }
  5663. var startPosition = this.position;
  5664. var nodes = [];
  5665. var space = "";
  5666. var lastComment = undefined;
  5667. do {
  5668. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  5669. if (!this.options.lossy) {
  5670. space += this.content();
  5671. }
  5672. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  5673. var spaces = {};
  5674. if (space) {
  5675. spaces.before = space;
  5676. space = "";
  5677. }
  5678. lastComment = new _comment["default"]({
  5679. value: this.content(),
  5680. source: getTokenSource(this.currToken),
  5681. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  5682. spaces: spaces
  5683. });
  5684. nodes.push(lastComment);
  5685. }
  5686. } while (++this.position < stopPosition);
  5687. if (space) {
  5688. if (lastComment) {
  5689. lastComment.spaces.after = space;
  5690. } else if (!this.options.lossy) {
  5691. var firstToken = this.tokens[startPosition];
  5692. var lastToken = this.tokens[this.position - 1];
  5693. nodes.push(new _string["default"]({
  5694. value: '',
  5695. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  5696. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  5697. spaces: {
  5698. before: space,
  5699. after: ''
  5700. }
  5701. }));
  5702. }
  5703. }
  5704. return nodes;
  5705. }
  5706. /**
  5707. *
  5708. * @param {*} nodes
  5709. */
  5710. ;
  5711. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  5712. var _this2 = this;
  5713. if (requiredSpace === void 0) {
  5714. requiredSpace = false;
  5715. }
  5716. var space = "";
  5717. var rawSpace = "";
  5718. nodes.forEach(function (n) {
  5719. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  5720. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  5721. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  5722. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  5723. });
  5724. if (rawSpace === space) {
  5725. rawSpace = undefined;
  5726. }
  5727. var result = {
  5728. space: space,
  5729. rawSpace: rawSpace
  5730. };
  5731. return result;
  5732. };
  5733. _proto.isNamedCombinator = function isNamedCombinator(position) {
  5734. if (position === void 0) {
  5735. position = this.position;
  5736. }
  5737. 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;
  5738. };
  5739. _proto.namedCombinator = function namedCombinator() {
  5740. if (this.isNamedCombinator()) {
  5741. var nameRaw = this.content(this.tokens[this.position + 1]);
  5742. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  5743. var raws = {};
  5744. if (name !== nameRaw) {
  5745. raws.value = "/" + nameRaw + "/";
  5746. }
  5747. var node = new _combinator["default"]({
  5748. value: "/" + name + "/",
  5749. 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]),
  5750. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  5751. raws: raws
  5752. });
  5753. this.position = this.position + 3;
  5754. return node;
  5755. } else {
  5756. this.unexpected();
  5757. }
  5758. };
  5759. _proto.combinator = function combinator() {
  5760. var _this3 = this;
  5761. if (this.content() === '|') {
  5762. return this.namespace();
  5763. } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  5764. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  5765. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  5766. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  5767. if (nodes.length > 0) {
  5768. var last = this.current.last;
  5769. if (last) {
  5770. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  5771. space = _this$convertWhitespa.space,
  5772. rawSpace = _this$convertWhitespa.rawSpace;
  5773. if (rawSpace !== undefined) {
  5774. last.rawSpaceAfter += rawSpace;
  5775. }
  5776. last.spaces.after += space;
  5777. } else {
  5778. nodes.forEach(function (n) {
  5779. return _this3.newNode(n);
  5780. });
  5781. }
  5782. }
  5783. return;
  5784. }
  5785. var firstToken = this.currToken;
  5786. var spaceOrDescendantSelectorNodes = undefined;
  5787. if (nextSigTokenPos > this.position) {
  5788. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  5789. }
  5790. var node;
  5791. if (this.isNamedCombinator()) {
  5792. node = this.namedCombinator();
  5793. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  5794. node = new _combinator["default"]({
  5795. value: this.content(),
  5796. source: getTokenSource(this.currToken),
  5797. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  5798. });
  5799. this.position++;
  5800. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  5801. this.unexpected();
  5802. }
  5803. if (node) {
  5804. if (spaceOrDescendantSelectorNodes) {
  5805. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  5806. _space = _this$convertWhitespa2.space,
  5807. _rawSpace = _this$convertWhitespa2.rawSpace;
  5808. node.spaces.before = _space;
  5809. node.rawSpaceBefore = _rawSpace;
  5810. }
  5811. } else {
  5812. // descendant combinator
  5813. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  5814. _space2 = _this$convertWhitespa3.space,
  5815. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  5816. if (!_rawSpace2) {
  5817. _rawSpace2 = _space2;
  5818. }
  5819. var spaces = {};
  5820. var raws = {
  5821. spaces: {}
  5822. };
  5823. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  5824. spaces.before = _space2.slice(0, _space2.length - 1);
  5825. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  5826. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  5827. spaces.after = _space2.slice(1);
  5828. raws.spaces.after = _rawSpace2.slice(1);
  5829. } else {
  5830. raws.value = _rawSpace2;
  5831. }
  5832. node = new _combinator["default"]({
  5833. value: ' ',
  5834. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  5835. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  5836. spaces: spaces,
  5837. raws: raws
  5838. });
  5839. }
  5840. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  5841. node.spaces.after = this.optionalSpace(this.content());
  5842. this.position++;
  5843. }
  5844. return this.newNode(node);
  5845. };
  5846. _proto.comma = function comma() {
  5847. if (this.position === this.tokens.length - 1) {
  5848. this.root.trailingComma = true;
  5849. this.position++;
  5850. return;
  5851. }
  5852. this.current._inferEndPosition();
  5853. var selector = new _selector["default"]({
  5854. source: {
  5855. start: tokenStart(this.tokens[this.position + 1])
  5856. }
  5857. });
  5858. this.current.parent.append(selector);
  5859. this.current = selector;
  5860. this.position++;
  5861. };
  5862. _proto.comment = function comment() {
  5863. var current = this.currToken;
  5864. this.newNode(new _comment["default"]({
  5865. value: this.content(),
  5866. source: getTokenSource(current),
  5867. sourceIndex: current[_tokenize.FIELDS.START_POS]
  5868. }));
  5869. this.position++;
  5870. };
  5871. _proto.error = function error(message, opts) {
  5872. throw this.root.error(message, opts);
  5873. };
  5874. _proto.missingBackslash = function missingBackslash() {
  5875. return this.error('Expected a backslash preceding the semicolon.', {
  5876. index: this.currToken[_tokenize.FIELDS.START_POS]
  5877. });
  5878. };
  5879. _proto.missingParenthesis = function missingParenthesis() {
  5880. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  5881. };
  5882. _proto.missingSquareBracket = function missingSquareBracket() {
  5883. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  5884. };
  5885. _proto.unexpected = function unexpected() {
  5886. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  5887. };
  5888. _proto.namespace = function namespace() {
  5889. var before = this.prevToken && this.content(this.prevToken) || true;
  5890. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  5891. this.position++;
  5892. return this.word(before);
  5893. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  5894. this.position++;
  5895. return this.universal(before);
  5896. }
  5897. };
  5898. _proto.nesting = function nesting() {
  5899. if (this.nextToken) {
  5900. var nextContent = this.content(this.nextToken);
  5901. if (nextContent === "|") {
  5902. this.position++;
  5903. return;
  5904. }
  5905. }
  5906. var current = this.currToken;
  5907. this.newNode(new _nesting["default"]({
  5908. value: this.content(),
  5909. source: getTokenSource(current),
  5910. sourceIndex: current[_tokenize.FIELDS.START_POS]
  5911. }));
  5912. this.position++;
  5913. };
  5914. _proto.parentheses = function parentheses() {
  5915. var last = this.current.last;
  5916. var unbalanced = 1;
  5917. this.position++;
  5918. if (last && last.type === types.PSEUDO) {
  5919. var selector = new _selector["default"]({
  5920. source: {
  5921. start: tokenStart(this.tokens[this.position - 1])
  5922. }
  5923. });
  5924. var cache = this.current;
  5925. last.append(selector);
  5926. this.current = selector;
  5927. while (this.position < this.tokens.length && unbalanced) {
  5928. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  5929. unbalanced++;
  5930. }
  5931. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  5932. unbalanced--;
  5933. }
  5934. if (unbalanced) {
  5935. this.parse();
  5936. } else {
  5937. this.current.source.end = tokenEnd(this.currToken);
  5938. this.current.parent.source.end = tokenEnd(this.currToken);
  5939. this.position++;
  5940. }
  5941. }
  5942. this.current = cache;
  5943. } else {
  5944. // I think this case should be an error. It's used to implement a basic parse of media queries
  5945. // but I don't think it's a good idea.
  5946. var parenStart = this.currToken;
  5947. var parenValue = "(";
  5948. var parenEnd;
  5949. while (this.position < this.tokens.length && unbalanced) {
  5950. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  5951. unbalanced++;
  5952. }
  5953. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  5954. unbalanced--;
  5955. }
  5956. parenEnd = this.currToken;
  5957. parenValue += this.parseParenthesisToken(this.currToken);
  5958. this.position++;
  5959. }
  5960. if (last) {
  5961. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  5962. } else {
  5963. this.newNode(new _string["default"]({
  5964. value: parenValue,
  5965. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  5966. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  5967. }));
  5968. }
  5969. }
  5970. if (unbalanced) {
  5971. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  5972. }
  5973. };
  5974. _proto.pseudo = function pseudo() {
  5975. var _this4 = this;
  5976. var pseudoStr = '';
  5977. var startingToken = this.currToken;
  5978. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  5979. pseudoStr += this.content();
  5980. this.position++;
  5981. }
  5982. if (!this.currToken) {
  5983. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  5984. }
  5985. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  5986. this.splitWord(false, function (first, length) {
  5987. pseudoStr += first;
  5988. _this4.newNode(new _pseudo["default"]({
  5989. value: pseudoStr,
  5990. source: getTokenSourceSpan(startingToken, _this4.currToken),
  5991. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  5992. }));
  5993. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  5994. _this4.error('Misplaced parenthesis.', {
  5995. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  5996. });
  5997. }
  5998. });
  5999. } else {
  6000. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6001. }
  6002. };
  6003. _proto.space = function space() {
  6004. var content = this.content(); // Handle space before and after the selector
  6005. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6006. return node.type === 'comment';
  6007. })) {
  6008. this.spaces = this.optionalSpace(content);
  6009. this.position++;
  6010. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6011. this.current.last.spaces.after = this.optionalSpace(content);
  6012. this.position++;
  6013. } else {
  6014. this.combinator();
  6015. }
  6016. };
  6017. _proto.string = function string() {
  6018. var current = this.currToken;
  6019. this.newNode(new _string["default"]({
  6020. value: this.content(),
  6021. source: getTokenSource(current),
  6022. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6023. }));
  6024. this.position++;
  6025. };
  6026. _proto.universal = function universal(namespace) {
  6027. var nextToken = this.nextToken;
  6028. if (nextToken && this.content(nextToken) === '|') {
  6029. this.position++;
  6030. return this.namespace();
  6031. }
  6032. var current = this.currToken;
  6033. this.newNode(new _universal["default"]({
  6034. value: this.content(),
  6035. source: getTokenSource(current),
  6036. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6037. }), namespace);
  6038. this.position++;
  6039. };
  6040. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6041. var _this5 = this;
  6042. var nextToken = this.nextToken;
  6043. var word = this.content();
  6044. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6045. this.position++;
  6046. var current = this.content();
  6047. word += current;
  6048. if (current.lastIndexOf('\\') === current.length - 1) {
  6049. var next = this.nextToken;
  6050. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6051. word += this.requiredSpace(this.content(next));
  6052. this.position++;
  6053. }
  6054. }
  6055. nextToken = this.nextToken;
  6056. }
  6057. var hasClass = indexesOf(word, '.').filter(function (i) {
  6058. // Allow escaped dot within class name
  6059. var escapedDot = word[i - 1] === '\\'; // Allow decimal numbers percent in @keyframes
  6060. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6061. return !escapedDot && !isKeyframesPercent;
  6062. });
  6063. var hasId = indexesOf(word, '#').filter(function (i) {
  6064. return word[i - 1] !== '\\';
  6065. }); // Eliminate Sass interpolations from the list of id indexes
  6066. var interpolations = indexesOf(word, '#{');
  6067. if (interpolations.length) {
  6068. hasId = hasId.filter(function (hashIndex) {
  6069. return !~interpolations.indexOf(hashIndex);
  6070. });
  6071. }
  6072. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6073. indices.forEach(function (ind, i) {
  6074. var index = indices[i + 1] || word.length;
  6075. var value = word.slice(ind, index);
  6076. if (i === 0 && firstCallback) {
  6077. return firstCallback.call(_this5, value, indices.length);
  6078. }
  6079. var node;
  6080. var current = _this5.currToken;
  6081. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6082. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6083. if (~hasClass.indexOf(ind)) {
  6084. var classNameOpts = {
  6085. value: value.slice(1),
  6086. source: source,
  6087. sourceIndex: sourceIndex
  6088. };
  6089. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6090. } else if (~hasId.indexOf(ind)) {
  6091. var idOpts = {
  6092. value: value.slice(1),
  6093. source: source,
  6094. sourceIndex: sourceIndex
  6095. };
  6096. node = new _id["default"](unescapeProp(idOpts, "value"));
  6097. } else {
  6098. var tagOpts = {
  6099. value: value,
  6100. source: source,
  6101. sourceIndex: sourceIndex
  6102. };
  6103. unescapeProp(tagOpts, "value");
  6104. node = new _tag["default"](tagOpts);
  6105. }
  6106. _this5.newNode(node, namespace); // Ensure that the namespace is used only once
  6107. namespace = null;
  6108. });
  6109. this.position++;
  6110. };
  6111. _proto.word = function word(namespace) {
  6112. var nextToken = this.nextToken;
  6113. if (nextToken && this.content(nextToken) === '|') {
  6114. this.position++;
  6115. return this.namespace();
  6116. }
  6117. return this.splitWord(namespace);
  6118. };
  6119. _proto.loop = function loop() {
  6120. while (this.position < this.tokens.length) {
  6121. this.parse(true);
  6122. }
  6123. this.current._inferEndPosition();
  6124. return this.root;
  6125. };
  6126. _proto.parse = function parse(throwOnParenthesis) {
  6127. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  6128. case tokens.space:
  6129. this.space();
  6130. break;
  6131. case tokens.comment:
  6132. this.comment();
  6133. break;
  6134. case tokens.openParenthesis:
  6135. this.parentheses();
  6136. break;
  6137. case tokens.closeParenthesis:
  6138. if (throwOnParenthesis) {
  6139. this.missingParenthesis();
  6140. }
  6141. break;
  6142. case tokens.openSquare:
  6143. this.attribute();
  6144. break;
  6145. case tokens.dollar:
  6146. case tokens.caret:
  6147. case tokens.equals:
  6148. case tokens.word:
  6149. this.word();
  6150. break;
  6151. case tokens.colon:
  6152. this.pseudo();
  6153. break;
  6154. case tokens.comma:
  6155. this.comma();
  6156. break;
  6157. case tokens.asterisk:
  6158. this.universal();
  6159. break;
  6160. case tokens.ampersand:
  6161. this.nesting();
  6162. break;
  6163. case tokens.slash:
  6164. case tokens.combinator:
  6165. this.combinator();
  6166. break;
  6167. case tokens.str:
  6168. this.string();
  6169. break;
  6170. // These cases throw; no break needed.
  6171. case tokens.closeSquare:
  6172. this.missingSquareBracket();
  6173. case tokens.semicolon:
  6174. this.missingBackslash();
  6175. default:
  6176. this.unexpected();
  6177. }
  6178. }
  6179. /**
  6180. * Helpers
  6181. */
  6182. ;
  6183. _proto.expected = function expected(description, index, found) {
  6184. if (Array.isArray(description)) {
  6185. var last = description.pop();
  6186. description = description.join(', ') + " or " + last;
  6187. }
  6188. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  6189. if (!found) {
  6190. return this.error("Expected " + an + " " + description + ".", {
  6191. index: index
  6192. });
  6193. }
  6194. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  6195. index: index
  6196. });
  6197. };
  6198. _proto.requiredSpace = function requiredSpace(space) {
  6199. return this.options.lossy ? ' ' : space;
  6200. };
  6201. _proto.optionalSpace = function optionalSpace(space) {
  6202. return this.options.lossy ? '' : space;
  6203. };
  6204. _proto.lossySpace = function lossySpace(space, required) {
  6205. if (this.options.lossy) {
  6206. return required ? ' ' : '';
  6207. } else {
  6208. return space;
  6209. }
  6210. };
  6211. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  6212. var content = this.content(token);
  6213. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  6214. return this.requiredSpace(content);
  6215. } else {
  6216. return content;
  6217. }
  6218. };
  6219. _proto.newNode = function newNode(node, namespace) {
  6220. if (namespace) {
  6221. if (/^ +$/.test(namespace)) {
  6222. if (!this.options.lossy) {
  6223. this.spaces = (this.spaces || '') + namespace;
  6224. }
  6225. namespace = true;
  6226. }
  6227. node.namespace = namespace;
  6228. unescapeProp(node, "namespace");
  6229. }
  6230. if (this.spaces) {
  6231. node.spaces.before = this.spaces;
  6232. this.spaces = '';
  6233. }
  6234. return this.current.append(node);
  6235. };
  6236. _proto.content = function content(token) {
  6237. if (token === void 0) {
  6238. token = this.currToken;
  6239. }
  6240. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  6241. };
  6242. /**
  6243. * returns the index of the next non-whitespace, non-comment token.
  6244. * returns -1 if no meaningful token is found.
  6245. */
  6246. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  6247. if (startPosition === void 0) {
  6248. startPosition = this.position + 1;
  6249. }
  6250. var searchPosition = startPosition;
  6251. while (searchPosition < this.tokens.length) {
  6252. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  6253. searchPosition++;
  6254. continue;
  6255. } else {
  6256. return searchPosition;
  6257. }
  6258. }
  6259. return -1;
  6260. };
  6261. _createClass(Parser, [{
  6262. key: "currToken",
  6263. get: function get() {
  6264. return this.tokens[this.position];
  6265. }
  6266. }, {
  6267. key: "nextToken",
  6268. get: function get() {
  6269. return this.tokens[this.position + 1];
  6270. }
  6271. }, {
  6272. key: "prevToken",
  6273. get: function get() {
  6274. return this.tokens[this.position - 1];
  6275. }
  6276. }]);
  6277. return Parser;
  6278. }();
  6279. exports["default"] = Parser;
  6280. module.exports = exports.default;
  6281. } (parser$1, parserExports));
  6282. (function (module, exports) {
  6283. exports.__esModule = true;
  6284. exports["default"] = void 0;
  6285. var _parser = _interopRequireDefault(parserExports);
  6286. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6287. var Processor = /*#__PURE__*/function () {
  6288. function Processor(func, options) {
  6289. this.func = func || function noop() {};
  6290. this.funcRes = null;
  6291. this.options = options;
  6292. }
  6293. var _proto = Processor.prototype;
  6294. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  6295. if (options === void 0) {
  6296. options = {};
  6297. }
  6298. var merged = Object.assign({}, this.options, options);
  6299. if (merged.updateSelector === false) {
  6300. return false;
  6301. } else {
  6302. return typeof rule !== "string";
  6303. }
  6304. };
  6305. _proto._isLossy = function _isLossy(options) {
  6306. if (options === void 0) {
  6307. options = {};
  6308. }
  6309. var merged = Object.assign({}, this.options, options);
  6310. if (merged.lossless === false) {
  6311. return true;
  6312. } else {
  6313. return false;
  6314. }
  6315. };
  6316. _proto._root = function _root(rule, options) {
  6317. if (options === void 0) {
  6318. options = {};
  6319. }
  6320. var parser = new _parser["default"](rule, this._parseOptions(options));
  6321. return parser.root;
  6322. };
  6323. _proto._parseOptions = function _parseOptions(options) {
  6324. return {
  6325. lossy: this._isLossy(options)
  6326. };
  6327. };
  6328. _proto._run = function _run(rule, options) {
  6329. var _this = this;
  6330. if (options === void 0) {
  6331. options = {};
  6332. }
  6333. return new Promise(function (resolve, reject) {
  6334. try {
  6335. var root = _this._root(rule, options);
  6336. Promise.resolve(_this.func(root)).then(function (transform) {
  6337. var string = undefined;
  6338. if (_this._shouldUpdateSelector(rule, options)) {
  6339. string = root.toString();
  6340. rule.selector = string;
  6341. }
  6342. return {
  6343. transform: transform,
  6344. root: root,
  6345. string: string
  6346. };
  6347. }).then(resolve, reject);
  6348. } catch (e) {
  6349. reject(e);
  6350. return;
  6351. }
  6352. });
  6353. };
  6354. _proto._runSync = function _runSync(rule, options) {
  6355. if (options === void 0) {
  6356. options = {};
  6357. }
  6358. var root = this._root(rule, options);
  6359. var transform = this.func(root);
  6360. if (transform && typeof transform.then === "function") {
  6361. throw new Error("Selector processor returned a promise to a synchronous call.");
  6362. }
  6363. var string = undefined;
  6364. if (options.updateSelector && typeof rule !== "string") {
  6365. string = root.toString();
  6366. rule.selector = string;
  6367. }
  6368. return {
  6369. transform: transform,
  6370. root: root,
  6371. string: string
  6372. };
  6373. }
  6374. /**
  6375. * Process rule into a selector AST.
  6376. *
  6377. * @param rule {postcss.Rule | string} The css selector to be processed
  6378. * @param options The options for processing
  6379. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  6380. */
  6381. ;
  6382. _proto.ast = function ast(rule, options) {
  6383. return this._run(rule, options).then(function (result) {
  6384. return result.root;
  6385. });
  6386. }
  6387. /**
  6388. * Process rule into a selector AST synchronously.
  6389. *
  6390. * @param rule {postcss.Rule | string} The css selector to be processed
  6391. * @param options The options for processing
  6392. * @returns {parser.Root} The AST of the selector after processing it.
  6393. */
  6394. ;
  6395. _proto.astSync = function astSync(rule, options) {
  6396. return this._runSync(rule, options).root;
  6397. }
  6398. /**
  6399. * Process a selector into a transformed value asynchronously
  6400. *
  6401. * @param rule {postcss.Rule | string} The css selector to be processed
  6402. * @param options The options for processing
  6403. * @returns {Promise<any>} The value returned by the processor.
  6404. */
  6405. ;
  6406. _proto.transform = function transform(rule, options) {
  6407. return this._run(rule, options).then(function (result) {
  6408. return result.transform;
  6409. });
  6410. }
  6411. /**
  6412. * Process a selector into a transformed value synchronously.
  6413. *
  6414. * @param rule {postcss.Rule | string} The css selector to be processed
  6415. * @param options The options for processing
  6416. * @returns {any} The value returned by the processor.
  6417. */
  6418. ;
  6419. _proto.transformSync = function transformSync(rule, options) {
  6420. return this._runSync(rule, options).transform;
  6421. }
  6422. /**
  6423. * Process a selector into a new selector string asynchronously.
  6424. *
  6425. * @param rule {postcss.Rule | string} The css selector to be processed
  6426. * @param options The options for processing
  6427. * @returns {string} the selector after processing.
  6428. */
  6429. ;
  6430. _proto.process = function process(rule, options) {
  6431. return this._run(rule, options).then(function (result) {
  6432. return result.string || result.root.toString();
  6433. });
  6434. }
  6435. /**
  6436. * Process a selector into a new selector string synchronously.
  6437. *
  6438. * @param rule {postcss.Rule | string} The css selector to be processed
  6439. * @param options The options for processing
  6440. * @returns {string} the selector after processing.
  6441. */
  6442. ;
  6443. _proto.processSync = function processSync(rule, options) {
  6444. var result = this._runSync(rule, options);
  6445. return result.string || result.root.toString();
  6446. };
  6447. return Processor;
  6448. }();
  6449. exports["default"] = Processor;
  6450. module.exports = exports.default;
  6451. } (processor, processorExports));
  6452. var selectors = {};
  6453. var constructors = {};
  6454. constructors.__esModule = true;
  6455. 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;
  6456. var _attribute = _interopRequireDefault$5(attribute$1);
  6457. var _className = _interopRequireDefault$5(classNameExports);
  6458. var _combinator = _interopRequireDefault$5(combinatorExports);
  6459. var _comment = _interopRequireDefault$5(commentExports);
  6460. var _id = _interopRequireDefault$5(idExports);
  6461. var _nesting = _interopRequireDefault$5(nestingExports);
  6462. var _pseudo = _interopRequireDefault$5(pseudoExports);
  6463. var _root = _interopRequireDefault$5(rootExports);
  6464. var _selector = _interopRequireDefault$5(selectorExports);
  6465. var _string = _interopRequireDefault$5(stringExports);
  6466. var _tag = _interopRequireDefault$5(tagExports);
  6467. var _universal = _interopRequireDefault$5(universalExports);
  6468. function _interopRequireDefault$5(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6469. var attribute = function attribute(opts) {
  6470. return new _attribute["default"](opts);
  6471. };
  6472. constructors.attribute = attribute;
  6473. var className = function className(opts) {
  6474. return new _className["default"](opts);
  6475. };
  6476. constructors.className = className;
  6477. var combinator = function combinator(opts) {
  6478. return new _combinator["default"](opts);
  6479. };
  6480. constructors.combinator = combinator;
  6481. var comment = function comment(opts) {
  6482. return new _comment["default"](opts);
  6483. };
  6484. constructors.comment = comment;
  6485. var id = function id(opts) {
  6486. return new _id["default"](opts);
  6487. };
  6488. constructors.id = id;
  6489. var nesting = function nesting(opts) {
  6490. return new _nesting["default"](opts);
  6491. };
  6492. constructors.nesting = nesting;
  6493. var pseudo = function pseudo(opts) {
  6494. return new _pseudo["default"](opts);
  6495. };
  6496. constructors.pseudo = pseudo;
  6497. var root$1 = function root(opts) {
  6498. return new _root["default"](opts);
  6499. };
  6500. constructors.root = root$1;
  6501. var selector = function selector(opts) {
  6502. return new _selector["default"](opts);
  6503. };
  6504. constructors.selector = selector;
  6505. var string = function string(opts) {
  6506. return new _string["default"](opts);
  6507. };
  6508. constructors.string = string;
  6509. var tag = function tag(opts) {
  6510. return new _tag["default"](opts);
  6511. };
  6512. constructors.tag = tag;
  6513. var universal = function universal(opts) {
  6514. return new _universal["default"](opts);
  6515. };
  6516. constructors.universal = universal;
  6517. var guards = {};
  6518. guards.__esModule = true;
  6519. guards.isNode = isNode;
  6520. guards.isPseudoElement = isPseudoElement;
  6521. guards.isPseudoClass = isPseudoClass;
  6522. guards.isContainer = isContainer;
  6523. guards.isNamespace = isNamespace;
  6524. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = guards.isPseudo = guards.isNesting = guards.isIdentifier = guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  6525. var _types = types$1;
  6526. var _IS_TYPE;
  6527. 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);
  6528. function isNode(node) {
  6529. return typeof node === "object" && IS_TYPE[node.type];
  6530. }
  6531. function isNodeType(type, node) {
  6532. return isNode(node) && node.type === type;
  6533. }
  6534. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  6535. guards.isAttribute = isAttribute;
  6536. var isClassName = isNodeType.bind(null, _types.CLASS);
  6537. guards.isClassName = isClassName;
  6538. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  6539. guards.isCombinator = isCombinator;
  6540. var isComment = isNodeType.bind(null, _types.COMMENT);
  6541. guards.isComment = isComment;
  6542. var isIdentifier = isNodeType.bind(null, _types.ID);
  6543. guards.isIdentifier = isIdentifier;
  6544. var isNesting = isNodeType.bind(null, _types.NESTING);
  6545. guards.isNesting = isNesting;
  6546. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  6547. guards.isPseudo = isPseudo;
  6548. var isRoot = isNodeType.bind(null, _types.ROOT);
  6549. guards.isRoot = isRoot;
  6550. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  6551. guards.isSelector = isSelector;
  6552. var isString = isNodeType.bind(null, _types.STRING);
  6553. guards.isString = isString;
  6554. var isTag = isNodeType.bind(null, _types.TAG);
  6555. guards.isTag = isTag;
  6556. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  6557. guards.isUniversal = isUniversal;
  6558. function isPseudoElement(node) {
  6559. 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");
  6560. }
  6561. function isPseudoClass(node) {
  6562. return isPseudo(node) && !isPseudoElement(node);
  6563. }
  6564. function isContainer(node) {
  6565. return !!(isNode(node) && node.walk);
  6566. }
  6567. function isNamespace(node) {
  6568. return isAttribute(node) || isTag(node);
  6569. }
  6570. (function (exports) {
  6571. exports.__esModule = true;
  6572. var _types = types$1;
  6573. Object.keys(_types).forEach(function (key) {
  6574. if (key === "default" || key === "__esModule") return;
  6575. if (key in exports && exports[key] === _types[key]) return;
  6576. exports[key] = _types[key];
  6577. });
  6578. var _constructors = constructors;
  6579. Object.keys(_constructors).forEach(function (key) {
  6580. if (key === "default" || key === "__esModule") return;
  6581. if (key in exports && exports[key] === _constructors[key]) return;
  6582. exports[key] = _constructors[key];
  6583. });
  6584. var _guards = guards;
  6585. Object.keys(_guards).forEach(function (key) {
  6586. if (key === "default" || key === "__esModule") return;
  6587. if (key in exports && exports[key] === _guards[key]) return;
  6588. exports[key] = _guards[key];
  6589. });
  6590. } (selectors));
  6591. (function (module, exports) {
  6592. exports.__esModule = true;
  6593. exports["default"] = void 0;
  6594. var _processor = _interopRequireDefault(processorExports);
  6595. var selectors$1 = _interopRequireWildcard(selectors);
  6596. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  6597. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }
  6598. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6599. var parser = function parser(processor) {
  6600. return new _processor["default"](processor);
  6601. };
  6602. Object.assign(parser, selectors$1);
  6603. delete parser.__esModule;
  6604. var _default = parser;
  6605. exports["default"] = _default;
  6606. module.exports = exports.default;
  6607. } (dist, distExports));
  6608. var selectorParser$2 = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  6609. const animationNameRE = /^(-\w+-)?animation-name$/;
  6610. const animationRE = /^(-\w+-)?animation$/;
  6611. const scopedPlugin = (id = "") => {
  6612. const keyframes = /* @__PURE__ */ Object.create(null);
  6613. const shortId = id.replace(/^data-v-/, "");
  6614. return {
  6615. postcssPlugin: "vue-sfc-scoped",
  6616. Rule(rule) {
  6617. processRule(id, rule);
  6618. },
  6619. AtRule(node) {
  6620. if (/-?keyframes$/.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  6621. keyframes[node.params] = node.params = node.params + "-" + shortId;
  6622. }
  6623. },
  6624. OnceExit(root) {
  6625. if (Object.keys(keyframes).length) {
  6626. root.walkDecls((decl) => {
  6627. if (animationNameRE.test(decl.prop)) {
  6628. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  6629. }
  6630. if (animationRE.test(decl.prop)) {
  6631. decl.value = decl.value.split(",").map((v) => {
  6632. const vals = v.trim().split(/\s+/);
  6633. const i = vals.findIndex((val) => keyframes[val]);
  6634. if (i !== -1) {
  6635. vals.splice(i, 1, keyframes[vals[i]]);
  6636. return vals.join(" ");
  6637. } else {
  6638. return v;
  6639. }
  6640. }).join(",");
  6641. }
  6642. });
  6643. }
  6644. }
  6645. };
  6646. };
  6647. const processedRules = /* @__PURE__ */ new WeakSet();
  6648. function processRule(id, rule) {
  6649. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && /-?keyframes$/.test(rule.parent.name)) {
  6650. return;
  6651. }
  6652. processedRules.add(rule);
  6653. rule.selector = selectorParser$2((selectorRoot) => {
  6654. selectorRoot.each((selector) => {
  6655. rewriteSelector(id, selector, selectorRoot);
  6656. });
  6657. }).processSync(rule.selector);
  6658. }
  6659. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  6660. let node = null;
  6661. let shouldInject = true;
  6662. selector.each((n) => {
  6663. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  6664. n.value = " ";
  6665. n.spaces.before = n.spaces.after = "";
  6666. warn(
  6667. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  6668. );
  6669. return false;
  6670. }
  6671. if (n.type === "pseudo") {
  6672. const { value } = n;
  6673. if (value === ":deep" || value === "::v-deep") {
  6674. if (n.nodes.length) {
  6675. let last = n;
  6676. n.nodes[0].each((ss) => {
  6677. selector.insertAfter(last, ss);
  6678. last = ss;
  6679. });
  6680. const prev = selector.at(selector.index(n) - 1);
  6681. if (!prev || !isSpaceCombinator(prev)) {
  6682. selector.insertAfter(
  6683. n,
  6684. selectorParser$2.combinator({
  6685. value: " "
  6686. })
  6687. );
  6688. }
  6689. selector.removeChild(n);
  6690. } else {
  6691. warn(
  6692. `::v-deep usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead.`
  6693. );
  6694. const prev = selector.at(selector.index(n) - 1);
  6695. if (prev && isSpaceCombinator(prev)) {
  6696. selector.removeChild(prev);
  6697. }
  6698. selector.removeChild(n);
  6699. }
  6700. return false;
  6701. }
  6702. if (value === ":slotted" || value === "::v-slotted") {
  6703. rewriteSelector(
  6704. id,
  6705. n.nodes[0],
  6706. selectorRoot,
  6707. true
  6708. /* slotted */
  6709. );
  6710. let last = n;
  6711. n.nodes[0].each((ss) => {
  6712. selector.insertAfter(last, ss);
  6713. last = ss;
  6714. });
  6715. selector.removeChild(n);
  6716. shouldInject = false;
  6717. return false;
  6718. }
  6719. if (value === ":global" || value === "::v-global") {
  6720. selectorRoot.insertAfter(selector, n.nodes[0]);
  6721. selectorRoot.removeChild(selector);
  6722. return false;
  6723. }
  6724. }
  6725. if (n.type !== "pseudo" && n.type !== "combinator") {
  6726. node = n;
  6727. }
  6728. });
  6729. if (node) {
  6730. node.spaces.after = "";
  6731. } else {
  6732. selector.first.spaces.before = "";
  6733. }
  6734. if (shouldInject) {
  6735. const idToAdd = slotted ? id + "-s" : id;
  6736. selector.insertAfter(
  6737. // If node is null it means we need to inject [id] at the start
  6738. // insertAfter can handle `null` here
  6739. node,
  6740. selectorParser$2.attribute({
  6741. attribute: idToAdd,
  6742. value: idToAdd,
  6743. raws: {},
  6744. quoteMark: `"`
  6745. })
  6746. );
  6747. }
  6748. }
  6749. function isSpaceCombinator(node) {
  6750. return node.type === "combinator" && /^\s+$/.test(node.value);
  6751. }
  6752. scopedPlugin.postcss = true;
  6753. var scopedPlugin$1 = scopedPlugin;
  6754. var sourceMap$1 = {};
  6755. var sourceMapGenerator = {};
  6756. var base64Vlq = {};
  6757. var base64$1 = {};
  6758. /* -*- Mode: js; js-indent-level: 2; -*- */
  6759. /*
  6760. * Copyright 2011 Mozilla Foundation and contributors
  6761. * Licensed under the New BSD license. See LICENSE or:
  6762. * http://opensource.org/licenses/BSD-3-Clause
  6763. */
  6764. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  6765. /**
  6766. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  6767. */
  6768. base64$1.encode = function (number) {
  6769. if (0 <= number && number < intToCharMap.length) {
  6770. return intToCharMap[number];
  6771. }
  6772. throw new TypeError("Must be between 0 and 63: " + number);
  6773. };
  6774. /**
  6775. * Decode a single base 64 character code digit to an integer. Returns -1 on
  6776. * failure.
  6777. */
  6778. base64$1.decode = function (charCode) {
  6779. var bigA = 65; // 'A'
  6780. var bigZ = 90; // 'Z'
  6781. var littleA = 97; // 'a'
  6782. var littleZ = 122; // 'z'
  6783. var zero = 48; // '0'
  6784. var nine = 57; // '9'
  6785. var plus = 43; // '+'
  6786. var slash = 47; // '/'
  6787. var littleOffset = 26;
  6788. var numberOffset = 52;
  6789. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  6790. if (bigA <= charCode && charCode <= bigZ) {
  6791. return (charCode - bigA);
  6792. }
  6793. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  6794. if (littleA <= charCode && charCode <= littleZ) {
  6795. return (charCode - littleA + littleOffset);
  6796. }
  6797. // 52 - 61: 0123456789
  6798. if (zero <= charCode && charCode <= nine) {
  6799. return (charCode - zero + numberOffset);
  6800. }
  6801. // 62: +
  6802. if (charCode == plus) {
  6803. return 62;
  6804. }
  6805. // 63: /
  6806. if (charCode == slash) {
  6807. return 63;
  6808. }
  6809. // Invalid base64 digit.
  6810. return -1;
  6811. };
  6812. /* -*- Mode: js; js-indent-level: 2; -*- */
  6813. /*
  6814. * Copyright 2011 Mozilla Foundation and contributors
  6815. * Licensed under the New BSD license. See LICENSE or:
  6816. * http://opensource.org/licenses/BSD-3-Clause
  6817. *
  6818. * Based on the Base 64 VLQ implementation in Closure Compiler:
  6819. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  6820. *
  6821. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  6822. * Redistribution and use in source and binary forms, with or without
  6823. * modification, are permitted provided that the following conditions are
  6824. * met:
  6825. *
  6826. * * Redistributions of source code must retain the above copyright
  6827. * notice, this list of conditions and the following disclaimer.
  6828. * * Redistributions in binary form must reproduce the above
  6829. * copyright notice, this list of conditions and the following
  6830. * disclaimer in the documentation and/or other materials provided
  6831. * with the distribution.
  6832. * * Neither the name of Google Inc. nor the names of its
  6833. * contributors may be used to endorse or promote products derived
  6834. * from this software without specific prior written permission.
  6835. *
  6836. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6837. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6838. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6839. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6840. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6841. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6842. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6843. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6844. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6845. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6846. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6847. */
  6848. var base64 = base64$1;
  6849. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  6850. // length quantities we use in the source map spec, the first bit is the sign,
  6851. // the next four bits are the actual value, and the 6th bit is the
  6852. // continuation bit. The continuation bit tells us whether there are more
  6853. // digits in this value following this digit.
  6854. //
  6855. // Continuation
  6856. // | Sign
  6857. // | |
  6858. // V V
  6859. // 101011
  6860. var VLQ_BASE_SHIFT = 5;
  6861. // binary: 100000
  6862. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  6863. // binary: 011111
  6864. var VLQ_BASE_MASK = VLQ_BASE - 1;
  6865. // binary: 100000
  6866. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  6867. /**
  6868. * Converts from a two-complement value to a value where the sign bit is
  6869. * placed in the least significant bit. For example, as decimals:
  6870. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  6871. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  6872. */
  6873. function toVLQSigned(aValue) {
  6874. return aValue < 0
  6875. ? ((-aValue) << 1) + 1
  6876. : (aValue << 1) + 0;
  6877. }
  6878. /**
  6879. * Converts to a two-complement value from a value where the sign bit is
  6880. * placed in the least significant bit. For example, as decimals:
  6881. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  6882. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  6883. */
  6884. function fromVLQSigned(aValue) {
  6885. var isNegative = (aValue & 1) === 1;
  6886. var shifted = aValue >> 1;
  6887. return isNegative
  6888. ? -shifted
  6889. : shifted;
  6890. }
  6891. /**
  6892. * Returns the base 64 VLQ encoded value.
  6893. */
  6894. base64Vlq.encode = function base64VLQ_encode(aValue) {
  6895. var encoded = "";
  6896. var digit;
  6897. var vlq = toVLQSigned(aValue);
  6898. do {
  6899. digit = vlq & VLQ_BASE_MASK;
  6900. vlq >>>= VLQ_BASE_SHIFT;
  6901. if (vlq > 0) {
  6902. // There are still more digits in this value, so we must make sure the
  6903. // continuation bit is marked.
  6904. digit |= VLQ_CONTINUATION_BIT;
  6905. }
  6906. encoded += base64.encode(digit);
  6907. } while (vlq > 0);
  6908. return encoded;
  6909. };
  6910. /**
  6911. * Decodes the next base 64 VLQ value from the given string and returns the
  6912. * value and the rest of the string via the out parameter.
  6913. */
  6914. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  6915. var strLen = aStr.length;
  6916. var result = 0;
  6917. var shift = 0;
  6918. var continuation, digit;
  6919. do {
  6920. if (aIndex >= strLen) {
  6921. throw new Error("Expected more digits in base 64 VLQ value.");
  6922. }
  6923. digit = base64.decode(aStr.charCodeAt(aIndex++));
  6924. if (digit === -1) {
  6925. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  6926. }
  6927. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  6928. digit &= VLQ_BASE_MASK;
  6929. result = result + (digit << shift);
  6930. shift += VLQ_BASE_SHIFT;
  6931. } while (continuation);
  6932. aOutParam.value = fromVLQSigned(result);
  6933. aOutParam.rest = aIndex;
  6934. };
  6935. var util$5 = {};
  6936. /* -*- Mode: js; js-indent-level: 2; -*- */
  6937. (function (exports) {
  6938. /*
  6939. * Copyright 2011 Mozilla Foundation and contributors
  6940. * Licensed under the New BSD license. See LICENSE or:
  6941. * http://opensource.org/licenses/BSD-3-Clause
  6942. */
  6943. /**
  6944. * This is a helper function for getting values from parameter/options
  6945. * objects.
  6946. *
  6947. * @param args The object we are extracting values from
  6948. * @param name The name of the property we are getting.
  6949. * @param defaultValue An optional value to return if the property is missing
  6950. * from the object. If this is not specified and the property is missing, an
  6951. * error will be thrown.
  6952. */
  6953. function getArg(aArgs, aName, aDefaultValue) {
  6954. if (aName in aArgs) {
  6955. return aArgs[aName];
  6956. } else if (arguments.length === 3) {
  6957. return aDefaultValue;
  6958. } else {
  6959. throw new Error('"' + aName + '" is a required argument.');
  6960. }
  6961. }
  6962. exports.getArg = getArg;
  6963. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  6964. var dataUrlRegexp = /^data:.+\,.+$/;
  6965. function urlParse(aUrl) {
  6966. var match = aUrl.match(urlRegexp);
  6967. if (!match) {
  6968. return null;
  6969. }
  6970. return {
  6971. scheme: match[1],
  6972. auth: match[2],
  6973. host: match[3],
  6974. port: match[4],
  6975. path: match[5]
  6976. };
  6977. }
  6978. exports.urlParse = urlParse;
  6979. function urlGenerate(aParsedUrl) {
  6980. var url = '';
  6981. if (aParsedUrl.scheme) {
  6982. url += aParsedUrl.scheme + ':';
  6983. }
  6984. url += '//';
  6985. if (aParsedUrl.auth) {
  6986. url += aParsedUrl.auth + '@';
  6987. }
  6988. if (aParsedUrl.host) {
  6989. url += aParsedUrl.host;
  6990. }
  6991. if (aParsedUrl.port) {
  6992. url += ":" + aParsedUrl.port;
  6993. }
  6994. if (aParsedUrl.path) {
  6995. url += aParsedUrl.path;
  6996. }
  6997. return url;
  6998. }
  6999. exports.urlGenerate = urlGenerate;
  7000. /**
  7001. * Normalizes a path, or the path portion of a URL:
  7002. *
  7003. * - Replaces consecutive slashes with one slash.
  7004. * - Removes unnecessary '.' parts.
  7005. * - Removes unnecessary '<dir>/..' parts.
  7006. *
  7007. * Based on code in the Node.js 'path' core module.
  7008. *
  7009. * @param aPath The path or url to normalize.
  7010. */
  7011. function normalize(aPath) {
  7012. var path = aPath;
  7013. var url = urlParse(aPath);
  7014. if (url) {
  7015. if (!url.path) {
  7016. return aPath;
  7017. }
  7018. path = url.path;
  7019. }
  7020. var isAbsolute = exports.isAbsolute(path);
  7021. var parts = path.split(/\/+/);
  7022. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  7023. part = parts[i];
  7024. if (part === '.') {
  7025. parts.splice(i, 1);
  7026. } else if (part === '..') {
  7027. up++;
  7028. } else if (up > 0) {
  7029. if (part === '') {
  7030. // The first part is blank if the path is absolute. Trying to go
  7031. // above the root is a no-op. Therefore we can remove all '..' parts
  7032. // directly after the root.
  7033. parts.splice(i + 1, up);
  7034. up = 0;
  7035. } else {
  7036. parts.splice(i, 2);
  7037. up--;
  7038. }
  7039. }
  7040. }
  7041. path = parts.join('/');
  7042. if (path === '') {
  7043. path = isAbsolute ? '/' : '.';
  7044. }
  7045. if (url) {
  7046. url.path = path;
  7047. return urlGenerate(url);
  7048. }
  7049. return path;
  7050. }
  7051. exports.normalize = normalize;
  7052. /**
  7053. * Joins two paths/URLs.
  7054. *
  7055. * @param aRoot The root path or URL.
  7056. * @param aPath The path or URL to be joined with the root.
  7057. *
  7058. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  7059. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  7060. * first.
  7061. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  7062. * is updated with the result and aRoot is returned. Otherwise the result
  7063. * is returned.
  7064. * - If aPath is absolute, the result is aPath.
  7065. * - Otherwise the two paths are joined with a slash.
  7066. * - Joining for example 'http://' and 'www.example.com' is also supported.
  7067. */
  7068. function join(aRoot, aPath) {
  7069. if (aRoot === "") {
  7070. aRoot = ".";
  7071. }
  7072. if (aPath === "") {
  7073. aPath = ".";
  7074. }
  7075. var aPathUrl = urlParse(aPath);
  7076. var aRootUrl = urlParse(aRoot);
  7077. if (aRootUrl) {
  7078. aRoot = aRootUrl.path || '/';
  7079. }
  7080. // `join(foo, '//www.example.org')`
  7081. if (aPathUrl && !aPathUrl.scheme) {
  7082. if (aRootUrl) {
  7083. aPathUrl.scheme = aRootUrl.scheme;
  7084. }
  7085. return urlGenerate(aPathUrl);
  7086. }
  7087. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  7088. return aPath;
  7089. }
  7090. // `join('http://', 'www.example.com')`
  7091. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  7092. aRootUrl.host = aPath;
  7093. return urlGenerate(aRootUrl);
  7094. }
  7095. var joined = aPath.charAt(0) === '/'
  7096. ? aPath
  7097. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  7098. if (aRootUrl) {
  7099. aRootUrl.path = joined;
  7100. return urlGenerate(aRootUrl);
  7101. }
  7102. return joined;
  7103. }
  7104. exports.join = join;
  7105. exports.isAbsolute = function (aPath) {
  7106. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  7107. };
  7108. /**
  7109. * Make a path relative to a URL or another path.
  7110. *
  7111. * @param aRoot The root path or URL.
  7112. * @param aPath The path or URL to be made relative to aRoot.
  7113. */
  7114. function relative(aRoot, aPath) {
  7115. if (aRoot === "") {
  7116. aRoot = ".";
  7117. }
  7118. aRoot = aRoot.replace(/\/$/, '');
  7119. // It is possible for the path to be above the root. In this case, simply
  7120. // checking whether the root is a prefix of the path won't work. Instead, we
  7121. // need to remove components from the root one by one, until either we find
  7122. // a prefix that fits, or we run out of components to remove.
  7123. var level = 0;
  7124. while (aPath.indexOf(aRoot + '/') !== 0) {
  7125. var index = aRoot.lastIndexOf("/");
  7126. if (index < 0) {
  7127. return aPath;
  7128. }
  7129. // If the only part of the root that is left is the scheme (i.e. http://,
  7130. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  7131. // have exhausted all components, so the path is not relative to the root.
  7132. aRoot = aRoot.slice(0, index);
  7133. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  7134. return aPath;
  7135. }
  7136. ++level;
  7137. }
  7138. // Make sure we add a "../" for each component we removed from the root.
  7139. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  7140. }
  7141. exports.relative = relative;
  7142. var supportsNullProto = (function () {
  7143. var obj = Object.create(null);
  7144. return !('__proto__' in obj);
  7145. }());
  7146. function identity (s) {
  7147. return s;
  7148. }
  7149. /**
  7150. * Because behavior goes wacky when you set `__proto__` on objects, we
  7151. * have to prefix all the strings in our set with an arbitrary character.
  7152. *
  7153. * See https://github.com/mozilla/source-map/pull/31 and
  7154. * https://github.com/mozilla/source-map/issues/30
  7155. *
  7156. * @param String aStr
  7157. */
  7158. function toSetString(aStr) {
  7159. if (isProtoString(aStr)) {
  7160. return '$' + aStr;
  7161. }
  7162. return aStr;
  7163. }
  7164. exports.toSetString = supportsNullProto ? identity : toSetString;
  7165. function fromSetString(aStr) {
  7166. if (isProtoString(aStr)) {
  7167. return aStr.slice(1);
  7168. }
  7169. return aStr;
  7170. }
  7171. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  7172. function isProtoString(s) {
  7173. if (!s) {
  7174. return false;
  7175. }
  7176. var length = s.length;
  7177. if (length < 9 /* "__proto__".length */) {
  7178. return false;
  7179. }
  7180. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  7181. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  7182. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  7183. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  7184. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  7185. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  7186. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  7187. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  7188. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  7189. return false;
  7190. }
  7191. for (var i = length - 10; i >= 0; i--) {
  7192. if (s.charCodeAt(i) !== 36 /* '$' */) {
  7193. return false;
  7194. }
  7195. }
  7196. return true;
  7197. }
  7198. /**
  7199. * Comparator between two mappings where the original positions are compared.
  7200. *
  7201. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  7202. * mappings with the same original source/line/column, but different generated
  7203. * line and column the same. Useful when searching for a mapping with a
  7204. * stubbed out mapping.
  7205. */
  7206. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  7207. var cmp = strcmp(mappingA.source, mappingB.source);
  7208. if (cmp !== 0) {
  7209. return cmp;
  7210. }
  7211. cmp = mappingA.originalLine - mappingB.originalLine;
  7212. if (cmp !== 0) {
  7213. return cmp;
  7214. }
  7215. cmp = mappingA.originalColumn - mappingB.originalColumn;
  7216. if (cmp !== 0 || onlyCompareOriginal) {
  7217. return cmp;
  7218. }
  7219. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  7220. if (cmp !== 0) {
  7221. return cmp;
  7222. }
  7223. cmp = mappingA.generatedLine - mappingB.generatedLine;
  7224. if (cmp !== 0) {
  7225. return cmp;
  7226. }
  7227. return strcmp(mappingA.name, mappingB.name);
  7228. }
  7229. exports.compareByOriginalPositions = compareByOriginalPositions;
  7230. /**
  7231. * Comparator between two mappings with deflated source and name indices where
  7232. * the generated positions are compared.
  7233. *
  7234. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  7235. * mappings with the same generated line and column, but different
  7236. * source/name/original line and column the same. Useful when searching for a
  7237. * mapping with a stubbed out mapping.
  7238. */
  7239. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  7240. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  7241. if (cmp !== 0) {
  7242. return cmp;
  7243. }
  7244. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  7245. if (cmp !== 0 || onlyCompareGenerated) {
  7246. return cmp;
  7247. }
  7248. cmp = strcmp(mappingA.source, mappingB.source);
  7249. if (cmp !== 0) {
  7250. return cmp;
  7251. }
  7252. cmp = mappingA.originalLine - mappingB.originalLine;
  7253. if (cmp !== 0) {
  7254. return cmp;
  7255. }
  7256. cmp = mappingA.originalColumn - mappingB.originalColumn;
  7257. if (cmp !== 0) {
  7258. return cmp;
  7259. }
  7260. return strcmp(mappingA.name, mappingB.name);
  7261. }
  7262. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  7263. function strcmp(aStr1, aStr2) {
  7264. if (aStr1 === aStr2) {
  7265. return 0;
  7266. }
  7267. if (aStr1 === null) {
  7268. return 1; // aStr2 !== null
  7269. }
  7270. if (aStr2 === null) {
  7271. return -1; // aStr1 !== null
  7272. }
  7273. if (aStr1 > aStr2) {
  7274. return 1;
  7275. }
  7276. return -1;
  7277. }
  7278. /**
  7279. * Comparator between two mappings with inflated source and name strings where
  7280. * the generated positions are compared.
  7281. */
  7282. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  7283. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  7284. if (cmp !== 0) {
  7285. return cmp;
  7286. }
  7287. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  7288. if (cmp !== 0) {
  7289. return cmp;
  7290. }
  7291. cmp = strcmp(mappingA.source, mappingB.source);
  7292. if (cmp !== 0) {
  7293. return cmp;
  7294. }
  7295. cmp = mappingA.originalLine - mappingB.originalLine;
  7296. if (cmp !== 0) {
  7297. return cmp;
  7298. }
  7299. cmp = mappingA.originalColumn - mappingB.originalColumn;
  7300. if (cmp !== 0) {
  7301. return cmp;
  7302. }
  7303. return strcmp(mappingA.name, mappingB.name);
  7304. }
  7305. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  7306. /**
  7307. * Strip any JSON XSSI avoidance prefix from the string (as documented
  7308. * in the source maps specification), and then parse the string as
  7309. * JSON.
  7310. */
  7311. function parseSourceMapInput(str) {
  7312. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  7313. }
  7314. exports.parseSourceMapInput = parseSourceMapInput;
  7315. /**
  7316. * Compute the URL of a source given the the source root, the source's
  7317. * URL, and the source map's URL.
  7318. */
  7319. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  7320. sourceURL = sourceURL || '';
  7321. if (sourceRoot) {
  7322. // This follows what Chrome does.
  7323. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  7324. sourceRoot += '/';
  7325. }
  7326. // The spec says:
  7327. // Line 4: An optional source root, useful for relocating source
  7328. // files on a server or removing repeated values in the
  7329. // “sources” entry. This value is prepended to the individual
  7330. // entries in the “source” field.
  7331. sourceURL = sourceRoot + sourceURL;
  7332. }
  7333. // Historically, SourceMapConsumer did not take the sourceMapURL as
  7334. // a parameter. This mode is still somewhat supported, which is why
  7335. // this code block is conditional. However, it's preferable to pass
  7336. // the source map URL to SourceMapConsumer, so that this function
  7337. // can implement the source URL resolution algorithm as outlined in
  7338. // the spec. This block is basically the equivalent of:
  7339. // new URL(sourceURL, sourceMapURL).toString()
  7340. // ... except it avoids using URL, which wasn't available in the
  7341. // older releases of node still supported by this library.
  7342. //
  7343. // The spec says:
  7344. // If the sources are not absolute URLs after prepending of the
  7345. // “sourceRoot”, the sources are resolved relative to the
  7346. // SourceMap (like resolving script src in a html document).
  7347. if (sourceMapURL) {
  7348. var parsed = urlParse(sourceMapURL);
  7349. if (!parsed) {
  7350. throw new Error("sourceMapURL could not be parsed");
  7351. }
  7352. if (parsed.path) {
  7353. // Strip the last path component, but keep the "/".
  7354. var index = parsed.path.lastIndexOf('/');
  7355. if (index >= 0) {
  7356. parsed.path = parsed.path.substring(0, index + 1);
  7357. }
  7358. }
  7359. sourceURL = join(urlGenerate(parsed), sourceURL);
  7360. }
  7361. return normalize(sourceURL);
  7362. }
  7363. exports.computeSourceURL = computeSourceURL;
  7364. } (util$5));
  7365. var arraySet = {};
  7366. /* -*- Mode: js; js-indent-level: 2; -*- */
  7367. /*
  7368. * Copyright 2011 Mozilla Foundation and contributors
  7369. * Licensed under the New BSD license. See LICENSE or:
  7370. * http://opensource.org/licenses/BSD-3-Clause
  7371. */
  7372. var util$4 = util$5;
  7373. var has = Object.prototype.hasOwnProperty;
  7374. var hasNativeMap = typeof Map !== "undefined";
  7375. /**
  7376. * A data structure which is a combination of an array and a set. Adding a new
  7377. * member is O(1), testing for membership is O(1), and finding the index of an
  7378. * element is O(1). Removing elements from the set is not supported. Only
  7379. * strings are supported for membership.
  7380. */
  7381. function ArraySet$2() {
  7382. this._array = [];
  7383. this._set = hasNativeMap ? new Map() : Object.create(null);
  7384. }
  7385. /**
  7386. * Static method for creating ArraySet instances from an existing array.
  7387. */
  7388. ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  7389. var set = new ArraySet$2();
  7390. for (var i = 0, len = aArray.length; i < len; i++) {
  7391. set.add(aArray[i], aAllowDuplicates);
  7392. }
  7393. return set;
  7394. };
  7395. /**
  7396. * Return how many unique items are in this ArraySet. If duplicates have been
  7397. * added, than those do not count towards the size.
  7398. *
  7399. * @returns Number
  7400. */
  7401. ArraySet$2.prototype.size = function ArraySet_size() {
  7402. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  7403. };
  7404. /**
  7405. * Add the given string to this set.
  7406. *
  7407. * @param String aStr
  7408. */
  7409. ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  7410. var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr);
  7411. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  7412. var idx = this._array.length;
  7413. if (!isDuplicate || aAllowDuplicates) {
  7414. this._array.push(aStr);
  7415. }
  7416. if (!isDuplicate) {
  7417. if (hasNativeMap) {
  7418. this._set.set(aStr, idx);
  7419. } else {
  7420. this._set[sStr] = idx;
  7421. }
  7422. }
  7423. };
  7424. /**
  7425. * Is the given string a member of this set?
  7426. *
  7427. * @param String aStr
  7428. */
  7429. ArraySet$2.prototype.has = function ArraySet_has(aStr) {
  7430. if (hasNativeMap) {
  7431. return this._set.has(aStr);
  7432. } else {
  7433. var sStr = util$4.toSetString(aStr);
  7434. return has.call(this._set, sStr);
  7435. }
  7436. };
  7437. /**
  7438. * What is the index of the given string in the array?
  7439. *
  7440. * @param String aStr
  7441. */
  7442. ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) {
  7443. if (hasNativeMap) {
  7444. var idx = this._set.get(aStr);
  7445. if (idx >= 0) {
  7446. return idx;
  7447. }
  7448. } else {
  7449. var sStr = util$4.toSetString(aStr);
  7450. if (has.call(this._set, sStr)) {
  7451. return this._set[sStr];
  7452. }
  7453. }
  7454. throw new Error('"' + aStr + '" is not in the set.');
  7455. };
  7456. /**
  7457. * What is the element at the given index?
  7458. *
  7459. * @param Number aIdx
  7460. */
  7461. ArraySet$2.prototype.at = function ArraySet_at(aIdx) {
  7462. if (aIdx >= 0 && aIdx < this._array.length) {
  7463. return this._array[aIdx];
  7464. }
  7465. throw new Error('No element indexed by ' + aIdx);
  7466. };
  7467. /**
  7468. * Returns the array representation of this set (which has the proper indices
  7469. * indicated by indexOf). Note that this is a copy of the internal array used
  7470. * for storing the members so that no one can mess with internal state.
  7471. */
  7472. ArraySet$2.prototype.toArray = function ArraySet_toArray() {
  7473. return this._array.slice();
  7474. };
  7475. arraySet.ArraySet = ArraySet$2;
  7476. var mappingList = {};
  7477. /* -*- Mode: js; js-indent-level: 2; -*- */
  7478. /*
  7479. * Copyright 2014 Mozilla Foundation and contributors
  7480. * Licensed under the New BSD license. See LICENSE or:
  7481. * http://opensource.org/licenses/BSD-3-Clause
  7482. */
  7483. var util$3 = util$5;
  7484. /**
  7485. * Determine whether mappingB is after mappingA with respect to generated
  7486. * position.
  7487. */
  7488. function generatedPositionAfter(mappingA, mappingB) {
  7489. // Optimized for most common case
  7490. var lineA = mappingA.generatedLine;
  7491. var lineB = mappingB.generatedLine;
  7492. var columnA = mappingA.generatedColumn;
  7493. var columnB = mappingB.generatedColumn;
  7494. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  7495. util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  7496. }
  7497. /**
  7498. * A data structure to provide a sorted view of accumulated mappings in a
  7499. * performance conscious manner. It trades a neglibable overhead in general
  7500. * case for a large speedup in case of mappings being added in order.
  7501. */
  7502. function MappingList$1() {
  7503. this._array = [];
  7504. this._sorted = true;
  7505. // Serves as infimum
  7506. this._last = {generatedLine: -1, generatedColumn: 0};
  7507. }
  7508. /**
  7509. * Iterate through internal items. This method takes the same arguments that
  7510. * `Array.prototype.forEach` takes.
  7511. *
  7512. * NOTE: The order of the mappings is NOT guaranteed.
  7513. */
  7514. MappingList$1.prototype.unsortedForEach =
  7515. function MappingList_forEach(aCallback, aThisArg) {
  7516. this._array.forEach(aCallback, aThisArg);
  7517. };
  7518. /**
  7519. * Add the given source mapping.
  7520. *
  7521. * @param Object aMapping
  7522. */
  7523. MappingList$1.prototype.add = function MappingList_add(aMapping) {
  7524. if (generatedPositionAfter(this._last, aMapping)) {
  7525. this._last = aMapping;
  7526. this._array.push(aMapping);
  7527. } else {
  7528. this._sorted = false;
  7529. this._array.push(aMapping);
  7530. }
  7531. };
  7532. /**
  7533. * Returns the flat, sorted array of mappings. The mappings are sorted by
  7534. * generated position.
  7535. *
  7536. * WARNING: This method returns internal data without copying, for
  7537. * performance. The return value must NOT be mutated, and should be treated as
  7538. * an immutable borrow. If you want to take ownership, you must make your own
  7539. * copy.
  7540. */
  7541. MappingList$1.prototype.toArray = function MappingList_toArray() {
  7542. if (!this._sorted) {
  7543. this._array.sort(util$3.compareByGeneratedPositionsInflated);
  7544. this._sorted = true;
  7545. }
  7546. return this._array;
  7547. };
  7548. mappingList.MappingList = MappingList$1;
  7549. /* -*- Mode: js; js-indent-level: 2; -*- */
  7550. /*
  7551. * Copyright 2011 Mozilla Foundation and contributors
  7552. * Licensed under the New BSD license. See LICENSE or:
  7553. * http://opensource.org/licenses/BSD-3-Clause
  7554. */
  7555. var base64VLQ$1 = base64Vlq;
  7556. var util$2 = util$5;
  7557. var ArraySet$1 = arraySet.ArraySet;
  7558. var MappingList = mappingList.MappingList;
  7559. /**
  7560. * An instance of the SourceMapGenerator represents a source map which is
  7561. * being built incrementally. You may pass an object with the following
  7562. * properties:
  7563. *
  7564. * - file: The filename of the generated source.
  7565. * - sourceRoot: A root for all relative URLs in this source map.
  7566. */
  7567. function SourceMapGenerator$2(aArgs) {
  7568. if (!aArgs) {
  7569. aArgs = {};
  7570. }
  7571. this._file = util$2.getArg(aArgs, 'file', null);
  7572. this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null);
  7573. this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false);
  7574. this._sources = new ArraySet$1();
  7575. this._names = new ArraySet$1();
  7576. this._mappings = new MappingList();
  7577. this._sourcesContents = null;
  7578. }
  7579. SourceMapGenerator$2.prototype._version = 3;
  7580. /**
  7581. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  7582. *
  7583. * @param aSourceMapConsumer The SourceMap.
  7584. */
  7585. SourceMapGenerator$2.fromSourceMap =
  7586. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  7587. var sourceRoot = aSourceMapConsumer.sourceRoot;
  7588. var generator = new SourceMapGenerator$2({
  7589. file: aSourceMapConsumer.file,
  7590. sourceRoot: sourceRoot
  7591. });
  7592. aSourceMapConsumer.eachMapping(function (mapping) {
  7593. var newMapping = {
  7594. generated: {
  7595. line: mapping.generatedLine,
  7596. column: mapping.generatedColumn
  7597. }
  7598. };
  7599. if (mapping.source != null) {
  7600. newMapping.source = mapping.source;
  7601. if (sourceRoot != null) {
  7602. newMapping.source = util$2.relative(sourceRoot, newMapping.source);
  7603. }
  7604. newMapping.original = {
  7605. line: mapping.originalLine,
  7606. column: mapping.originalColumn
  7607. };
  7608. if (mapping.name != null) {
  7609. newMapping.name = mapping.name;
  7610. }
  7611. }
  7612. generator.addMapping(newMapping);
  7613. });
  7614. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  7615. var sourceRelative = sourceFile;
  7616. if (sourceRoot !== null) {
  7617. sourceRelative = util$2.relative(sourceRoot, sourceFile);
  7618. }
  7619. if (!generator._sources.has(sourceRelative)) {
  7620. generator._sources.add(sourceRelative);
  7621. }
  7622. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  7623. if (content != null) {
  7624. generator.setSourceContent(sourceFile, content);
  7625. }
  7626. });
  7627. return generator;
  7628. };
  7629. /**
  7630. * Add a single mapping from original source line and column to the generated
  7631. * source's line and column for this source map being created. The mapping
  7632. * object should have the following properties:
  7633. *
  7634. * - generated: An object with the generated line and column positions.
  7635. * - original: An object with the original line and column positions.
  7636. * - source: The original source file (relative to the sourceRoot).
  7637. * - name: An optional original token name for this mapping.
  7638. */
  7639. SourceMapGenerator$2.prototype.addMapping =
  7640. function SourceMapGenerator_addMapping(aArgs) {
  7641. var generated = util$2.getArg(aArgs, 'generated');
  7642. var original = util$2.getArg(aArgs, 'original', null);
  7643. var source = util$2.getArg(aArgs, 'source', null);
  7644. var name = util$2.getArg(aArgs, 'name', null);
  7645. if (!this._skipValidation) {
  7646. this._validateMapping(generated, original, source, name);
  7647. }
  7648. if (source != null) {
  7649. source = String(source);
  7650. if (!this._sources.has(source)) {
  7651. this._sources.add(source);
  7652. }
  7653. }
  7654. if (name != null) {
  7655. name = String(name);
  7656. if (!this._names.has(name)) {
  7657. this._names.add(name);
  7658. }
  7659. }
  7660. this._mappings.add({
  7661. generatedLine: generated.line,
  7662. generatedColumn: generated.column,
  7663. originalLine: original != null && original.line,
  7664. originalColumn: original != null && original.column,
  7665. source: source,
  7666. name: name
  7667. });
  7668. };
  7669. /**
  7670. * Set the source content for a source file.
  7671. */
  7672. SourceMapGenerator$2.prototype.setSourceContent =
  7673. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  7674. var source = aSourceFile;
  7675. if (this._sourceRoot != null) {
  7676. source = util$2.relative(this._sourceRoot, source);
  7677. }
  7678. if (aSourceContent != null) {
  7679. // Add the source content to the _sourcesContents map.
  7680. // Create a new _sourcesContents map if the property is null.
  7681. if (!this._sourcesContents) {
  7682. this._sourcesContents = Object.create(null);
  7683. }
  7684. this._sourcesContents[util$2.toSetString(source)] = aSourceContent;
  7685. } else if (this._sourcesContents) {
  7686. // Remove the source file from the _sourcesContents map.
  7687. // If the _sourcesContents map is empty, set the property to null.
  7688. delete this._sourcesContents[util$2.toSetString(source)];
  7689. if (Object.keys(this._sourcesContents).length === 0) {
  7690. this._sourcesContents = null;
  7691. }
  7692. }
  7693. };
  7694. /**
  7695. * Applies the mappings of a sub-source-map for a specific source file to the
  7696. * source map being generated. Each mapping to the supplied source file is
  7697. * rewritten using the supplied source map. Note: The resolution for the
  7698. * resulting mappings is the minimium of this map and the supplied map.
  7699. *
  7700. * @param aSourceMapConsumer The source map to be applied.
  7701. * @param aSourceFile Optional. The filename of the source file.
  7702. * If omitted, SourceMapConsumer's file property will be used.
  7703. * @param aSourceMapPath Optional. The dirname of the path to the source map
  7704. * to be applied. If relative, it is relative to the SourceMapConsumer.
  7705. * This parameter is needed when the two source maps aren't in the same
  7706. * directory, and the source map to be applied contains relative source
  7707. * paths. If so, those relative source paths need to be rewritten
  7708. * relative to the SourceMapGenerator.
  7709. */
  7710. SourceMapGenerator$2.prototype.applySourceMap =
  7711. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  7712. var sourceFile = aSourceFile;
  7713. // If aSourceFile is omitted, we will use the file property of the SourceMap
  7714. if (aSourceFile == null) {
  7715. if (aSourceMapConsumer.file == null) {
  7716. throw new Error(
  7717. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  7718. 'or the source map\'s "file" property. Both were omitted.'
  7719. );
  7720. }
  7721. sourceFile = aSourceMapConsumer.file;
  7722. }
  7723. var sourceRoot = this._sourceRoot;
  7724. // Make "sourceFile" relative if an absolute Url is passed.
  7725. if (sourceRoot != null) {
  7726. sourceFile = util$2.relative(sourceRoot, sourceFile);
  7727. }
  7728. // Applying the SourceMap can add and remove items from the sources and
  7729. // the names array.
  7730. var newSources = new ArraySet$1();
  7731. var newNames = new ArraySet$1();
  7732. // Find mappings for the "sourceFile"
  7733. this._mappings.unsortedForEach(function (mapping) {
  7734. if (mapping.source === sourceFile && mapping.originalLine != null) {
  7735. // Check if it can be mapped by the source map, then update the mapping.
  7736. var original = aSourceMapConsumer.originalPositionFor({
  7737. line: mapping.originalLine,
  7738. column: mapping.originalColumn
  7739. });
  7740. if (original.source != null) {
  7741. // Copy mapping
  7742. mapping.source = original.source;
  7743. if (aSourceMapPath != null) {
  7744. mapping.source = util$2.join(aSourceMapPath, mapping.source);
  7745. }
  7746. if (sourceRoot != null) {
  7747. mapping.source = util$2.relative(sourceRoot, mapping.source);
  7748. }
  7749. mapping.originalLine = original.line;
  7750. mapping.originalColumn = original.column;
  7751. if (original.name != null) {
  7752. mapping.name = original.name;
  7753. }
  7754. }
  7755. }
  7756. var source = mapping.source;
  7757. if (source != null && !newSources.has(source)) {
  7758. newSources.add(source);
  7759. }
  7760. var name = mapping.name;
  7761. if (name != null && !newNames.has(name)) {
  7762. newNames.add(name);
  7763. }
  7764. }, this);
  7765. this._sources = newSources;
  7766. this._names = newNames;
  7767. // Copy sourcesContents of applied map.
  7768. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  7769. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  7770. if (content != null) {
  7771. if (aSourceMapPath != null) {
  7772. sourceFile = util$2.join(aSourceMapPath, sourceFile);
  7773. }
  7774. if (sourceRoot != null) {
  7775. sourceFile = util$2.relative(sourceRoot, sourceFile);
  7776. }
  7777. this.setSourceContent(sourceFile, content);
  7778. }
  7779. }, this);
  7780. };
  7781. /**
  7782. * A mapping can have one of the three levels of data:
  7783. *
  7784. * 1. Just the generated position.
  7785. * 2. The Generated position, original position, and original source.
  7786. * 3. Generated and original position, original source, as well as a name
  7787. * token.
  7788. *
  7789. * To maintain consistency, we validate that any new mapping being added falls
  7790. * in to one of these categories.
  7791. */
  7792. SourceMapGenerator$2.prototype._validateMapping =
  7793. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  7794. aName) {
  7795. // When aOriginal is truthy but has empty values for .line and .column,
  7796. // it is most likely a programmer error. In this case we throw a very
  7797. // specific error message to try to guide them the right way.
  7798. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  7799. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  7800. throw new Error(
  7801. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  7802. 'the original mapping entirely and only map the generated position. If so, pass ' +
  7803. 'null for the original mapping instead of an object with empty or null values.'
  7804. );
  7805. }
  7806. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  7807. && aGenerated.line > 0 && aGenerated.column >= 0
  7808. && !aOriginal && !aSource && !aName) {
  7809. // Case 1.
  7810. return;
  7811. }
  7812. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  7813. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  7814. && aGenerated.line > 0 && aGenerated.column >= 0
  7815. && aOriginal.line > 0 && aOriginal.column >= 0
  7816. && aSource) {
  7817. // Cases 2 and 3.
  7818. return;
  7819. }
  7820. else {
  7821. throw new Error('Invalid mapping: ' + JSON.stringify({
  7822. generated: aGenerated,
  7823. source: aSource,
  7824. original: aOriginal,
  7825. name: aName
  7826. }));
  7827. }
  7828. };
  7829. /**
  7830. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  7831. * specified by the source map format.
  7832. */
  7833. SourceMapGenerator$2.prototype._serializeMappings =
  7834. function SourceMapGenerator_serializeMappings() {
  7835. var previousGeneratedColumn = 0;
  7836. var previousGeneratedLine = 1;
  7837. var previousOriginalColumn = 0;
  7838. var previousOriginalLine = 0;
  7839. var previousName = 0;
  7840. var previousSource = 0;
  7841. var result = '';
  7842. var next;
  7843. var mapping;
  7844. var nameIdx;
  7845. var sourceIdx;
  7846. var mappings = this._mappings.toArray();
  7847. for (var i = 0, len = mappings.length; i < len; i++) {
  7848. mapping = mappings[i];
  7849. next = '';
  7850. if (mapping.generatedLine !== previousGeneratedLine) {
  7851. previousGeneratedColumn = 0;
  7852. while (mapping.generatedLine !== previousGeneratedLine) {
  7853. next += ';';
  7854. previousGeneratedLine++;
  7855. }
  7856. }
  7857. else {
  7858. if (i > 0) {
  7859. if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  7860. continue;
  7861. }
  7862. next += ',';
  7863. }
  7864. }
  7865. next += base64VLQ$1.encode(mapping.generatedColumn
  7866. - previousGeneratedColumn);
  7867. previousGeneratedColumn = mapping.generatedColumn;
  7868. if (mapping.source != null) {
  7869. sourceIdx = this._sources.indexOf(mapping.source);
  7870. next += base64VLQ$1.encode(sourceIdx - previousSource);
  7871. previousSource = sourceIdx;
  7872. // lines are stored 0-based in SourceMap spec version 3
  7873. next += base64VLQ$1.encode(mapping.originalLine - 1
  7874. - previousOriginalLine);
  7875. previousOriginalLine = mapping.originalLine - 1;
  7876. next += base64VLQ$1.encode(mapping.originalColumn
  7877. - previousOriginalColumn);
  7878. previousOriginalColumn = mapping.originalColumn;
  7879. if (mapping.name != null) {
  7880. nameIdx = this._names.indexOf(mapping.name);
  7881. next += base64VLQ$1.encode(nameIdx - previousName);
  7882. previousName = nameIdx;
  7883. }
  7884. }
  7885. result += next;
  7886. }
  7887. return result;
  7888. };
  7889. SourceMapGenerator$2.prototype._generateSourcesContent =
  7890. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  7891. return aSources.map(function (source) {
  7892. if (!this._sourcesContents) {
  7893. return null;
  7894. }
  7895. if (aSourceRoot != null) {
  7896. source = util$2.relative(aSourceRoot, source);
  7897. }
  7898. var key = util$2.toSetString(source);
  7899. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  7900. ? this._sourcesContents[key]
  7901. : null;
  7902. }, this);
  7903. };
  7904. /**
  7905. * Externalize the source map.
  7906. */
  7907. SourceMapGenerator$2.prototype.toJSON =
  7908. function SourceMapGenerator_toJSON() {
  7909. var map = {
  7910. version: this._version,
  7911. sources: this._sources.toArray(),
  7912. names: this._names.toArray(),
  7913. mappings: this._serializeMappings()
  7914. };
  7915. if (this._file != null) {
  7916. map.file = this._file;
  7917. }
  7918. if (this._sourceRoot != null) {
  7919. map.sourceRoot = this._sourceRoot;
  7920. }
  7921. if (this._sourcesContents) {
  7922. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  7923. }
  7924. return map;
  7925. };
  7926. /**
  7927. * Render the source map being generated to a string.
  7928. */
  7929. SourceMapGenerator$2.prototype.toString =
  7930. function SourceMapGenerator_toString() {
  7931. return JSON.stringify(this.toJSON());
  7932. };
  7933. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$2;
  7934. var sourceMapConsumer = {};
  7935. var binarySearch$1 = {};
  7936. /* -*- Mode: js; js-indent-level: 2; -*- */
  7937. (function (exports) {
  7938. /*
  7939. * Copyright 2011 Mozilla Foundation and contributors
  7940. * Licensed under the New BSD license. See LICENSE or:
  7941. * http://opensource.org/licenses/BSD-3-Clause
  7942. */
  7943. exports.GREATEST_LOWER_BOUND = 1;
  7944. exports.LEAST_UPPER_BOUND = 2;
  7945. /**
  7946. * Recursive implementation of binary search.
  7947. *
  7948. * @param aLow Indices here and lower do not contain the needle.
  7949. * @param aHigh Indices here and higher do not contain the needle.
  7950. * @param aNeedle The element being searched for.
  7951. * @param aHaystack The non-empty array being searched.
  7952. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  7953. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  7954. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  7955. * closest element that is smaller than or greater than the one we are
  7956. * searching for, respectively, if the exact element cannot be found.
  7957. */
  7958. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  7959. // This function terminates when one of the following is true:
  7960. //
  7961. // 1. We find the exact element we are looking for.
  7962. //
  7963. // 2. We did not find the exact element, but we can return the index of
  7964. // the next-closest element.
  7965. //
  7966. // 3. We did not find the exact element, and there is no next-closest
  7967. // element than the one we are searching for, so we return -1.
  7968. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  7969. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  7970. if (cmp === 0) {
  7971. // Found the element we are looking for.
  7972. return mid;
  7973. }
  7974. else if (cmp > 0) {
  7975. // Our needle is greater than aHaystack[mid].
  7976. if (aHigh - mid > 1) {
  7977. // The element is in the upper half.
  7978. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  7979. }
  7980. // The exact needle element was not found in this haystack. Determine if
  7981. // we are in termination case (3) or (2) and return the appropriate thing.
  7982. if (aBias == exports.LEAST_UPPER_BOUND) {
  7983. return aHigh < aHaystack.length ? aHigh : -1;
  7984. } else {
  7985. return mid;
  7986. }
  7987. }
  7988. else {
  7989. // Our needle is less than aHaystack[mid].
  7990. if (mid - aLow > 1) {
  7991. // The element is in the lower half.
  7992. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  7993. }
  7994. // we are in termination case (3) or (2) and return the appropriate thing.
  7995. if (aBias == exports.LEAST_UPPER_BOUND) {
  7996. return mid;
  7997. } else {
  7998. return aLow < 0 ? -1 : aLow;
  7999. }
  8000. }
  8001. }
  8002. /**
  8003. * This is an implementation of binary search which will always try and return
  8004. * the index of the closest element if there is no exact hit. This is because
  8005. * mappings between original and generated line/col pairs are single points,
  8006. * and there is an implicit region between each of them, so a miss just means
  8007. * that you aren't on the very start of a region.
  8008. *
  8009. * @param aNeedle The element you are looking for.
  8010. * @param aHaystack The array that is being searched.
  8011. * @param aCompare A function which takes the needle and an element in the
  8012. * array and returns -1, 0, or 1 depending on whether the needle is less
  8013. * than, equal to, or greater than the element, respectively.
  8014. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8015. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8016. * closest element that is smaller than or greater than the one we are
  8017. * searching for, respectively, if the exact element cannot be found.
  8018. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  8019. */
  8020. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  8021. if (aHaystack.length === 0) {
  8022. return -1;
  8023. }
  8024. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  8025. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  8026. if (index < 0) {
  8027. return -1;
  8028. }
  8029. // We have found either the exact element, or the next-closest element than
  8030. // the one we are searching for. However, there may be more than one such
  8031. // element. Make sure we always return the smallest of these.
  8032. while (index - 1 >= 0) {
  8033. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  8034. break;
  8035. }
  8036. --index;
  8037. }
  8038. return index;
  8039. };
  8040. } (binarySearch$1));
  8041. var quickSort$1 = {};
  8042. /* -*- Mode: js; js-indent-level: 2; -*- */
  8043. /*
  8044. * Copyright 2011 Mozilla Foundation and contributors
  8045. * Licensed under the New BSD license. See LICENSE or:
  8046. * http://opensource.org/licenses/BSD-3-Clause
  8047. */
  8048. // It turns out that some (most?) JavaScript engines don't self-host
  8049. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  8050. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  8051. // custom comparator function, calling back and forth between the VM's C++ and
  8052. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  8053. // worse generated code for the comparator function than would be optimal. In
  8054. // fact, when sorting with a comparator, these costs outweigh the benefits of
  8055. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  8056. // a ~3500ms mean speed-up in `bench/bench.html`.
  8057. /**
  8058. * Swap the elements indexed by `x` and `y` in the array `ary`.
  8059. *
  8060. * @param {Array} ary
  8061. * The array.
  8062. * @param {Number} x
  8063. * The index of the first item.
  8064. * @param {Number} y
  8065. * The index of the second item.
  8066. */
  8067. function swap(ary, x, y) {
  8068. var temp = ary[x];
  8069. ary[x] = ary[y];
  8070. ary[y] = temp;
  8071. }
  8072. /**
  8073. * Returns a random integer within the range `low .. high` inclusive.
  8074. *
  8075. * @param {Number} low
  8076. * The lower bound on the range.
  8077. * @param {Number} high
  8078. * The upper bound on the range.
  8079. */
  8080. function randomIntInRange(low, high) {
  8081. return Math.round(low + (Math.random() * (high - low)));
  8082. }
  8083. /**
  8084. * The Quick Sort algorithm.
  8085. *
  8086. * @param {Array} ary
  8087. * An array to sort.
  8088. * @param {function} comparator
  8089. * Function to use to compare two items.
  8090. * @param {Number} p
  8091. * Start index of the array
  8092. * @param {Number} r
  8093. * End index of the array
  8094. */
  8095. function doQuickSort(ary, comparator, p, r) {
  8096. // If our lower bound is less than our upper bound, we (1) partition the
  8097. // array into two pieces and (2) recurse on each half. If it is not, this is
  8098. // the empty array and our base case.
  8099. if (p < r) {
  8100. // (1) Partitioning.
  8101. //
  8102. // The partitioning chooses a pivot between `p` and `r` and moves all
  8103. // elements that are less than or equal to the pivot to the before it, and
  8104. // all the elements that are greater than it after it. The effect is that
  8105. // once partition is done, the pivot is in the exact place it will be when
  8106. // the array is put in sorted order, and it will not need to be moved
  8107. // again. This runs in O(n) time.
  8108. // Always choose a random pivot so that an input array which is reverse
  8109. // sorted does not cause O(n^2) running time.
  8110. var pivotIndex = randomIntInRange(p, r);
  8111. var i = p - 1;
  8112. swap(ary, pivotIndex, r);
  8113. var pivot = ary[r];
  8114. // Immediately after `j` is incremented in this loop, the following hold
  8115. // true:
  8116. //
  8117. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  8118. //
  8119. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  8120. for (var j = p; j < r; j++) {
  8121. if (comparator(ary[j], pivot) <= 0) {
  8122. i += 1;
  8123. swap(ary, i, j);
  8124. }
  8125. }
  8126. swap(ary, i + 1, j);
  8127. var q = i + 1;
  8128. // (2) Recurse on each half.
  8129. doQuickSort(ary, comparator, p, q - 1);
  8130. doQuickSort(ary, comparator, q + 1, r);
  8131. }
  8132. }
  8133. /**
  8134. * Sort the given array in-place with the given comparator function.
  8135. *
  8136. * @param {Array} ary
  8137. * An array to sort.
  8138. * @param {function} comparator
  8139. * Function to use to compare two items.
  8140. */
  8141. quickSort$1.quickSort = function (ary, comparator) {
  8142. doQuickSort(ary, comparator, 0, ary.length - 1);
  8143. };
  8144. /* -*- Mode: js; js-indent-level: 2; -*- */
  8145. /*
  8146. * Copyright 2011 Mozilla Foundation and contributors
  8147. * Licensed under the New BSD license. See LICENSE or:
  8148. * http://opensource.org/licenses/BSD-3-Clause
  8149. */
  8150. var util$1 = util$5;
  8151. var binarySearch = binarySearch$1;
  8152. var ArraySet = arraySet.ArraySet;
  8153. var base64VLQ = base64Vlq;
  8154. var quickSort = quickSort$1.quickSort;
  8155. function SourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  8156. var sourceMap = aSourceMap;
  8157. if (typeof aSourceMap === 'string') {
  8158. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  8159. }
  8160. return sourceMap.sections != null
  8161. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  8162. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  8163. }
  8164. SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  8165. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  8166. };
  8167. /**
  8168. * The version of the source mapping spec that we are consuming.
  8169. */
  8170. SourceMapConsumer$1.prototype._version = 3;
  8171. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  8172. // parsed mapping coordinates from the source map's "mappings" attribute. They
  8173. // are lazily instantiated, accessed via the `_generatedMappings` and
  8174. // `_originalMappings` getters respectively, and we only parse the mappings
  8175. // and create these arrays once queried for a source location. We jump through
  8176. // these hoops because there can be many thousands of mappings, and parsing
  8177. // them is expensive, so we only want to do it if we must.
  8178. //
  8179. // Each object in the arrays is of the form:
  8180. //
  8181. // {
  8182. // generatedLine: The line number in the generated code,
  8183. // generatedColumn: The column number in the generated code,
  8184. // source: The path to the original source file that generated this
  8185. // chunk of code,
  8186. // originalLine: The line number in the original source that
  8187. // corresponds to this chunk of generated code,
  8188. // originalColumn: The column number in the original source that
  8189. // corresponds to this chunk of generated code,
  8190. // name: The name of the original symbol which generated this chunk of
  8191. // code.
  8192. // }
  8193. //
  8194. // All properties except for `generatedLine` and `generatedColumn` can be
  8195. // `null`.
  8196. //
  8197. // `_generatedMappings` is ordered by the generated positions.
  8198. //
  8199. // `_originalMappings` is ordered by the original positions.
  8200. SourceMapConsumer$1.prototype.__generatedMappings = null;
  8201. Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', {
  8202. configurable: true,
  8203. enumerable: true,
  8204. get: function () {
  8205. if (!this.__generatedMappings) {
  8206. this._parseMappings(this._mappings, this.sourceRoot);
  8207. }
  8208. return this.__generatedMappings;
  8209. }
  8210. });
  8211. SourceMapConsumer$1.prototype.__originalMappings = null;
  8212. Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', {
  8213. configurable: true,
  8214. enumerable: true,
  8215. get: function () {
  8216. if (!this.__originalMappings) {
  8217. this._parseMappings(this._mappings, this.sourceRoot);
  8218. }
  8219. return this.__originalMappings;
  8220. }
  8221. });
  8222. SourceMapConsumer$1.prototype._charIsMappingSeparator =
  8223. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  8224. var c = aStr.charAt(index);
  8225. return c === ";" || c === ",";
  8226. };
  8227. /**
  8228. * Parse the mappings in a string in to a data structure which we can easily
  8229. * query (the ordered arrays in the `this.__generatedMappings` and
  8230. * `this.__originalMappings` properties).
  8231. */
  8232. SourceMapConsumer$1.prototype._parseMappings =
  8233. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  8234. throw new Error("Subclasses must implement _parseMappings");
  8235. };
  8236. SourceMapConsumer$1.GENERATED_ORDER = 1;
  8237. SourceMapConsumer$1.ORIGINAL_ORDER = 2;
  8238. SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1;
  8239. SourceMapConsumer$1.LEAST_UPPER_BOUND = 2;
  8240. /**
  8241. * Iterate over each mapping between an original source/line/column and a
  8242. * generated line/column in this source map.
  8243. *
  8244. * @param Function aCallback
  8245. * The function that is called with each mapping.
  8246. * @param Object aContext
  8247. * Optional. If specified, this object will be the value of `this` every
  8248. * time that `aCallback` is called.
  8249. * @param aOrder
  8250. * Either `SourceMapConsumer.GENERATED_ORDER` or
  8251. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  8252. * iterate over the mappings sorted by the generated file's line/column
  8253. * order or the original's source/line/column order, respectively. Defaults to
  8254. * `SourceMapConsumer.GENERATED_ORDER`.
  8255. */
  8256. SourceMapConsumer$1.prototype.eachMapping =
  8257. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  8258. var context = aContext || null;
  8259. var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER;
  8260. var mappings;
  8261. switch (order) {
  8262. case SourceMapConsumer$1.GENERATED_ORDER:
  8263. mappings = this._generatedMappings;
  8264. break;
  8265. case SourceMapConsumer$1.ORIGINAL_ORDER:
  8266. mappings = this._originalMappings;
  8267. break;
  8268. default:
  8269. throw new Error("Unknown order of iteration.");
  8270. }
  8271. var sourceRoot = this.sourceRoot;
  8272. mappings.map(function (mapping) {
  8273. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  8274. source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  8275. return {
  8276. source: source,
  8277. generatedLine: mapping.generatedLine,
  8278. generatedColumn: mapping.generatedColumn,
  8279. originalLine: mapping.originalLine,
  8280. originalColumn: mapping.originalColumn,
  8281. name: mapping.name === null ? null : this._names.at(mapping.name)
  8282. };
  8283. }, this).forEach(aCallback, context);
  8284. };
  8285. /**
  8286. * Returns all generated line and column information for the original source,
  8287. * line, and column provided. If no column is provided, returns all mappings
  8288. * corresponding to a either the line we are searching for or the next
  8289. * closest line that has any mappings. Otherwise, returns all mappings
  8290. * corresponding to the given line and either the column we are searching for
  8291. * or the next closest column that has any offsets.
  8292. *
  8293. * The only argument is an object with the following properties:
  8294. *
  8295. * - source: The filename of the original source.
  8296. * - line: The line number in the original source. The line number is 1-based.
  8297. * - column: Optional. the column number in the original source.
  8298. * The column number is 0-based.
  8299. *
  8300. * and an array of objects is returned, each with the following properties:
  8301. *
  8302. * - line: The line number in the generated source, or null. The
  8303. * line number is 1-based.
  8304. * - column: The column number in the generated source, or null.
  8305. * The column number is 0-based.
  8306. */
  8307. SourceMapConsumer$1.prototype.allGeneratedPositionsFor =
  8308. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  8309. var line = util$1.getArg(aArgs, 'line');
  8310. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  8311. // returns the index of the closest mapping less than the needle. By
  8312. // setting needle.originalColumn to 0, we thus find the last mapping for
  8313. // the given line, provided such a mapping exists.
  8314. var needle = {
  8315. source: util$1.getArg(aArgs, 'source'),
  8316. originalLine: line,
  8317. originalColumn: util$1.getArg(aArgs, 'column', 0)
  8318. };
  8319. needle.source = this._findSourceIndex(needle.source);
  8320. if (needle.source < 0) {
  8321. return [];
  8322. }
  8323. var mappings = [];
  8324. var index = this._findMapping(needle,
  8325. this._originalMappings,
  8326. "originalLine",
  8327. "originalColumn",
  8328. util$1.compareByOriginalPositions,
  8329. binarySearch.LEAST_UPPER_BOUND);
  8330. if (index >= 0) {
  8331. var mapping = this._originalMappings[index];
  8332. if (aArgs.column === undefined) {
  8333. var originalLine = mapping.originalLine;
  8334. // Iterate until either we run out of mappings, or we run into
  8335. // a mapping for a different line than the one we found. Since
  8336. // mappings are sorted, this is guaranteed to find all mappings for
  8337. // the line we found.
  8338. while (mapping && mapping.originalLine === originalLine) {
  8339. mappings.push({
  8340. line: util$1.getArg(mapping, 'generatedLine', null),
  8341. column: util$1.getArg(mapping, 'generatedColumn', null),
  8342. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  8343. });
  8344. mapping = this._originalMappings[++index];
  8345. }
  8346. } else {
  8347. var originalColumn = mapping.originalColumn;
  8348. // Iterate until either we run out of mappings, or we run into
  8349. // a mapping for a different line than the one we were searching for.
  8350. // Since mappings are sorted, this is guaranteed to find all mappings for
  8351. // the line we are searching for.
  8352. while (mapping &&
  8353. mapping.originalLine === line &&
  8354. mapping.originalColumn == originalColumn) {
  8355. mappings.push({
  8356. line: util$1.getArg(mapping, 'generatedLine', null),
  8357. column: util$1.getArg(mapping, 'generatedColumn', null),
  8358. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  8359. });
  8360. mapping = this._originalMappings[++index];
  8361. }
  8362. }
  8363. }
  8364. return mappings;
  8365. };
  8366. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1;
  8367. /**
  8368. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  8369. * query for information about the original file positions by giving it a file
  8370. * position in the generated source.
  8371. *
  8372. * The first parameter is the raw source map (either as a JSON string, or
  8373. * already parsed to an object). According to the spec, source maps have the
  8374. * following attributes:
  8375. *
  8376. * - version: Which version of the source map spec this map is following.
  8377. * - sources: An array of URLs to the original source files.
  8378. * - names: An array of identifiers which can be referrenced by individual mappings.
  8379. * - sourceRoot: Optional. The URL root from which all sources are relative.
  8380. * - sourcesContent: Optional. An array of contents of the original source files.
  8381. * - mappings: A string of base64 VLQs which contain the actual mappings.
  8382. * - file: Optional. The generated file this source map is associated with.
  8383. *
  8384. * Here is an example source map, taken from the source map spec[0]:
  8385. *
  8386. * {
  8387. * version : 3,
  8388. * file: "out.js",
  8389. * sourceRoot : "",
  8390. * sources: ["foo.js", "bar.js"],
  8391. * names: ["src", "maps", "are", "fun"],
  8392. * mappings: "AA,AB;;ABCDE;"
  8393. * }
  8394. *
  8395. * The second parameter, if given, is a string whose value is the URL
  8396. * at which the source map was found. This URL is used to compute the
  8397. * sources array.
  8398. *
  8399. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  8400. */
  8401. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  8402. var sourceMap = aSourceMap;
  8403. if (typeof aSourceMap === 'string') {
  8404. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  8405. }
  8406. var version = util$1.getArg(sourceMap, 'version');
  8407. var sources = util$1.getArg(sourceMap, 'sources');
  8408. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  8409. // requires the array) to play nice here.
  8410. var names = util$1.getArg(sourceMap, 'names', []);
  8411. var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
  8412. var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
  8413. var mappings = util$1.getArg(sourceMap, 'mappings');
  8414. var file = util$1.getArg(sourceMap, 'file', null);
  8415. // Once again, Sass deviates from the spec and supplies the version as a
  8416. // string rather than a number, so we use loose equality checking here.
  8417. if (version != this._version) {
  8418. throw new Error('Unsupported version: ' + version);
  8419. }
  8420. if (sourceRoot) {
  8421. sourceRoot = util$1.normalize(sourceRoot);
  8422. }
  8423. sources = sources
  8424. .map(String)
  8425. // Some source maps produce relative source paths like "./foo.js" instead of
  8426. // "foo.js". Normalize these first so that future comparisons will succeed.
  8427. // See bugzil.la/1090768.
  8428. .map(util$1.normalize)
  8429. // Always ensure that absolute sources are internally stored relative to
  8430. // the source root, if the source root is absolute. Not doing this would
  8431. // be particularly problematic when the source root is a prefix of the
  8432. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  8433. .map(function (source) {
  8434. return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
  8435. ? util$1.relative(sourceRoot, source)
  8436. : source;
  8437. });
  8438. // Pass `true` below to allow duplicate names and sources. While source maps
  8439. // are intended to be compressed and deduplicated, the TypeScript compiler
  8440. // sometimes generates source maps with duplicates in them. See Github issue
  8441. // #72 and bugzil.la/889492.
  8442. this._names = ArraySet.fromArray(names.map(String), true);
  8443. this._sources = ArraySet.fromArray(sources, true);
  8444. this._absoluteSources = this._sources.toArray().map(function (s) {
  8445. return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL);
  8446. });
  8447. this.sourceRoot = sourceRoot;
  8448. this.sourcesContent = sourcesContent;
  8449. this._mappings = mappings;
  8450. this._sourceMapURL = aSourceMapURL;
  8451. this.file = file;
  8452. }
  8453. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  8454. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1;
  8455. /**
  8456. * Utility function to find the index of a source. Returns -1 if not
  8457. * found.
  8458. */
  8459. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  8460. var relativeSource = aSource;
  8461. if (this.sourceRoot != null) {
  8462. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  8463. }
  8464. if (this._sources.has(relativeSource)) {
  8465. return this._sources.indexOf(relativeSource);
  8466. }
  8467. // Maybe aSource is an absolute URL as returned by |sources|. In
  8468. // this case we can't simply undo the transform.
  8469. var i;
  8470. for (i = 0; i < this._absoluteSources.length; ++i) {
  8471. if (this._absoluteSources[i] == aSource) {
  8472. return i;
  8473. }
  8474. }
  8475. return -1;
  8476. };
  8477. /**
  8478. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  8479. *
  8480. * @param SourceMapGenerator aSourceMap
  8481. * The source map that will be consumed.
  8482. * @param String aSourceMapURL
  8483. * The URL at which the source map can be found (optional)
  8484. * @returns BasicSourceMapConsumer
  8485. */
  8486. BasicSourceMapConsumer.fromSourceMap =
  8487. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  8488. var smc = Object.create(BasicSourceMapConsumer.prototype);
  8489. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  8490. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  8491. smc.sourceRoot = aSourceMap._sourceRoot;
  8492. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  8493. smc.sourceRoot);
  8494. smc.file = aSourceMap._file;
  8495. smc._sourceMapURL = aSourceMapURL;
  8496. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  8497. return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  8498. });
  8499. // Because we are modifying the entries (by converting string sources and
  8500. // names to indices into the sources and names ArraySets), we have to make
  8501. // a copy of the entry or else bad things happen. Shared mutable state
  8502. // strikes again! See github issue #191.
  8503. var generatedMappings = aSourceMap._mappings.toArray().slice();
  8504. var destGeneratedMappings = smc.__generatedMappings = [];
  8505. var destOriginalMappings = smc.__originalMappings = [];
  8506. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  8507. var srcMapping = generatedMappings[i];
  8508. var destMapping = new Mapping;
  8509. destMapping.generatedLine = srcMapping.generatedLine;
  8510. destMapping.generatedColumn = srcMapping.generatedColumn;
  8511. if (srcMapping.source) {
  8512. destMapping.source = sources.indexOf(srcMapping.source);
  8513. destMapping.originalLine = srcMapping.originalLine;
  8514. destMapping.originalColumn = srcMapping.originalColumn;
  8515. if (srcMapping.name) {
  8516. destMapping.name = names.indexOf(srcMapping.name);
  8517. }
  8518. destOriginalMappings.push(destMapping);
  8519. }
  8520. destGeneratedMappings.push(destMapping);
  8521. }
  8522. quickSort(smc.__originalMappings, util$1.compareByOriginalPositions);
  8523. return smc;
  8524. };
  8525. /**
  8526. * The version of the source mapping spec that we are consuming.
  8527. */
  8528. BasicSourceMapConsumer.prototype._version = 3;
  8529. /**
  8530. * The list of original sources.
  8531. */
  8532. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  8533. get: function () {
  8534. return this._absoluteSources.slice();
  8535. }
  8536. });
  8537. /**
  8538. * Provide the JIT with a nice shape / hidden class.
  8539. */
  8540. function Mapping() {
  8541. this.generatedLine = 0;
  8542. this.generatedColumn = 0;
  8543. this.source = null;
  8544. this.originalLine = null;
  8545. this.originalColumn = null;
  8546. this.name = null;
  8547. }
  8548. /**
  8549. * Parse the mappings in a string in to a data structure which we can easily
  8550. * query (the ordered arrays in the `this.__generatedMappings` and
  8551. * `this.__originalMappings` properties).
  8552. */
  8553. BasicSourceMapConsumer.prototype._parseMappings =
  8554. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  8555. var generatedLine = 1;
  8556. var previousGeneratedColumn = 0;
  8557. var previousOriginalLine = 0;
  8558. var previousOriginalColumn = 0;
  8559. var previousSource = 0;
  8560. var previousName = 0;
  8561. var length = aStr.length;
  8562. var index = 0;
  8563. var cachedSegments = {};
  8564. var temp = {};
  8565. var originalMappings = [];
  8566. var generatedMappings = [];
  8567. var mapping, str, segment, end, value;
  8568. while (index < length) {
  8569. if (aStr.charAt(index) === ';') {
  8570. generatedLine++;
  8571. index++;
  8572. previousGeneratedColumn = 0;
  8573. }
  8574. else if (aStr.charAt(index) === ',') {
  8575. index++;
  8576. }
  8577. else {
  8578. mapping = new Mapping();
  8579. mapping.generatedLine = generatedLine;
  8580. // Because each offset is encoded relative to the previous one,
  8581. // many segments often have the same encoding. We can exploit this
  8582. // fact by caching the parsed variable length fields of each segment,
  8583. // allowing us to avoid a second parse if we encounter the same
  8584. // segment again.
  8585. for (end = index; end < length; end++) {
  8586. if (this._charIsMappingSeparator(aStr, end)) {
  8587. break;
  8588. }
  8589. }
  8590. str = aStr.slice(index, end);
  8591. segment = cachedSegments[str];
  8592. if (segment) {
  8593. index += str.length;
  8594. } else {
  8595. segment = [];
  8596. while (index < end) {
  8597. base64VLQ.decode(aStr, index, temp);
  8598. value = temp.value;
  8599. index = temp.rest;
  8600. segment.push(value);
  8601. }
  8602. if (segment.length === 2) {
  8603. throw new Error('Found a source, but no line and column');
  8604. }
  8605. if (segment.length === 3) {
  8606. throw new Error('Found a source and line, but no column');
  8607. }
  8608. cachedSegments[str] = segment;
  8609. }
  8610. // Generated column.
  8611. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  8612. previousGeneratedColumn = mapping.generatedColumn;
  8613. if (segment.length > 1) {
  8614. // Original source.
  8615. mapping.source = previousSource + segment[1];
  8616. previousSource += segment[1];
  8617. // Original line.
  8618. mapping.originalLine = previousOriginalLine + segment[2];
  8619. previousOriginalLine = mapping.originalLine;
  8620. // Lines are stored 0-based
  8621. mapping.originalLine += 1;
  8622. // Original column.
  8623. mapping.originalColumn = previousOriginalColumn + segment[3];
  8624. previousOriginalColumn = mapping.originalColumn;
  8625. if (segment.length > 4) {
  8626. // Original name.
  8627. mapping.name = previousName + segment[4];
  8628. previousName += segment[4];
  8629. }
  8630. }
  8631. generatedMappings.push(mapping);
  8632. if (typeof mapping.originalLine === 'number') {
  8633. originalMappings.push(mapping);
  8634. }
  8635. }
  8636. }
  8637. quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  8638. this.__generatedMappings = generatedMappings;
  8639. quickSort(originalMappings, util$1.compareByOriginalPositions);
  8640. this.__originalMappings = originalMappings;
  8641. };
  8642. /**
  8643. * Find the mapping that best matches the hypothetical "needle" mapping that
  8644. * we are searching for in the given "haystack" of mappings.
  8645. */
  8646. BasicSourceMapConsumer.prototype._findMapping =
  8647. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  8648. aColumnName, aComparator, aBias) {
  8649. // To return the position we are searching for, we must first find the
  8650. // mapping for the given position and then return the opposite position it
  8651. // points to. Because the mappings are sorted, we can use binary search to
  8652. // find the best mapping.
  8653. if (aNeedle[aLineName] <= 0) {
  8654. throw new TypeError('Line must be greater than or equal to 1, got '
  8655. + aNeedle[aLineName]);
  8656. }
  8657. if (aNeedle[aColumnName] < 0) {
  8658. throw new TypeError('Column must be greater than or equal to 0, got '
  8659. + aNeedle[aColumnName]);
  8660. }
  8661. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  8662. };
  8663. /**
  8664. * Compute the last column for each generated mapping. The last column is
  8665. * inclusive.
  8666. */
  8667. BasicSourceMapConsumer.prototype.computeColumnSpans =
  8668. function SourceMapConsumer_computeColumnSpans() {
  8669. for (var index = 0; index < this._generatedMappings.length; ++index) {
  8670. var mapping = this._generatedMappings[index];
  8671. // Mappings do not contain a field for the last generated columnt. We
  8672. // can come up with an optimistic estimate, however, by assuming that
  8673. // mappings are contiguous (i.e. given two consecutive mappings, the
  8674. // first mapping ends where the second one starts).
  8675. if (index + 1 < this._generatedMappings.length) {
  8676. var nextMapping = this._generatedMappings[index + 1];
  8677. if (mapping.generatedLine === nextMapping.generatedLine) {
  8678. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  8679. continue;
  8680. }
  8681. }
  8682. // The last mapping for each line spans the entire line.
  8683. mapping.lastGeneratedColumn = Infinity;
  8684. }
  8685. };
  8686. /**
  8687. * Returns the original source, line, and column information for the generated
  8688. * source's line and column positions provided. The only argument is an object
  8689. * with the following properties:
  8690. *
  8691. * - line: The line number in the generated source. The line number
  8692. * is 1-based.
  8693. * - column: The column number in the generated source. The column
  8694. * number is 0-based.
  8695. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  8696. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  8697. * closest element that is smaller than or greater than the one we are
  8698. * searching for, respectively, if the exact element cannot be found.
  8699. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  8700. *
  8701. * and an object is returned with the following properties:
  8702. *
  8703. * - source: The original source file, or null.
  8704. * - line: The line number in the original source, or null. The
  8705. * line number is 1-based.
  8706. * - column: The column number in the original source, or null. The
  8707. * column number is 0-based.
  8708. * - name: The original identifier, or null.
  8709. */
  8710. BasicSourceMapConsumer.prototype.originalPositionFor =
  8711. function SourceMapConsumer_originalPositionFor(aArgs) {
  8712. var needle = {
  8713. generatedLine: util$1.getArg(aArgs, 'line'),
  8714. generatedColumn: util$1.getArg(aArgs, 'column')
  8715. };
  8716. var index = this._findMapping(
  8717. needle,
  8718. this._generatedMappings,
  8719. "generatedLine",
  8720. "generatedColumn",
  8721. util$1.compareByGeneratedPositionsDeflated,
  8722. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  8723. );
  8724. if (index >= 0) {
  8725. var mapping = this._generatedMappings[index];
  8726. if (mapping.generatedLine === needle.generatedLine) {
  8727. var source = util$1.getArg(mapping, 'source', null);
  8728. if (source !== null) {
  8729. source = this._sources.at(source);
  8730. source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  8731. }
  8732. var name = util$1.getArg(mapping, 'name', null);
  8733. if (name !== null) {
  8734. name = this._names.at(name);
  8735. }
  8736. return {
  8737. source: source,
  8738. line: util$1.getArg(mapping, 'originalLine', null),
  8739. column: util$1.getArg(mapping, 'originalColumn', null),
  8740. name: name
  8741. };
  8742. }
  8743. }
  8744. return {
  8745. source: null,
  8746. line: null,
  8747. column: null,
  8748. name: null
  8749. };
  8750. };
  8751. /**
  8752. * Return true if we have the source content for every source in the source
  8753. * map, false otherwise.
  8754. */
  8755. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  8756. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  8757. if (!this.sourcesContent) {
  8758. return false;
  8759. }
  8760. return this.sourcesContent.length >= this._sources.size() &&
  8761. !this.sourcesContent.some(function (sc) { return sc == null; });
  8762. };
  8763. /**
  8764. * Returns the original source content. The only argument is the url of the
  8765. * original source file. Returns null if no original source content is
  8766. * available.
  8767. */
  8768. BasicSourceMapConsumer.prototype.sourceContentFor =
  8769. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  8770. if (!this.sourcesContent) {
  8771. return null;
  8772. }
  8773. var index = this._findSourceIndex(aSource);
  8774. if (index >= 0) {
  8775. return this.sourcesContent[index];
  8776. }
  8777. var relativeSource = aSource;
  8778. if (this.sourceRoot != null) {
  8779. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  8780. }
  8781. var url;
  8782. if (this.sourceRoot != null
  8783. && (url = util$1.urlParse(this.sourceRoot))) {
  8784. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  8785. // many users. We can help them out when they expect file:// URIs to
  8786. // behave like it would if they were running a local HTTP server. See
  8787. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  8788. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  8789. if (url.scheme == "file"
  8790. && this._sources.has(fileUriAbsPath)) {
  8791. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  8792. }
  8793. if ((!url.path || url.path == "/")
  8794. && this._sources.has("/" + relativeSource)) {
  8795. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  8796. }
  8797. }
  8798. // This function is used recursively from
  8799. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  8800. // don't want to throw if we can't find the source - we just want to
  8801. // return null, so we provide a flag to exit gracefully.
  8802. if (nullOnMissing) {
  8803. return null;
  8804. }
  8805. else {
  8806. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  8807. }
  8808. };
  8809. /**
  8810. * Returns the generated line and column information for the original source,
  8811. * line, and column positions provided. The only argument is an object with
  8812. * the following properties:
  8813. *
  8814. * - source: The filename of the original source.
  8815. * - line: The line number in the original source. The line number
  8816. * is 1-based.
  8817. * - column: The column number in the original source. The column
  8818. * number is 0-based.
  8819. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  8820. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  8821. * closest element that is smaller than or greater than the one we are
  8822. * searching for, respectively, if the exact element cannot be found.
  8823. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  8824. *
  8825. * and an object is returned with the following properties:
  8826. *
  8827. * - line: The line number in the generated source, or null. The
  8828. * line number is 1-based.
  8829. * - column: The column number in the generated source, or null.
  8830. * The column number is 0-based.
  8831. */
  8832. BasicSourceMapConsumer.prototype.generatedPositionFor =
  8833. function SourceMapConsumer_generatedPositionFor(aArgs) {
  8834. var source = util$1.getArg(aArgs, 'source');
  8835. source = this._findSourceIndex(source);
  8836. if (source < 0) {
  8837. return {
  8838. line: null,
  8839. column: null,
  8840. lastColumn: null
  8841. };
  8842. }
  8843. var needle = {
  8844. source: source,
  8845. originalLine: util$1.getArg(aArgs, 'line'),
  8846. originalColumn: util$1.getArg(aArgs, 'column')
  8847. };
  8848. var index = this._findMapping(
  8849. needle,
  8850. this._originalMappings,
  8851. "originalLine",
  8852. "originalColumn",
  8853. util$1.compareByOriginalPositions,
  8854. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  8855. );
  8856. if (index >= 0) {
  8857. var mapping = this._originalMappings[index];
  8858. if (mapping.source === needle.source) {
  8859. return {
  8860. line: util$1.getArg(mapping, 'generatedLine', null),
  8861. column: util$1.getArg(mapping, 'generatedColumn', null),
  8862. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  8863. };
  8864. }
  8865. }
  8866. return {
  8867. line: null,
  8868. column: null,
  8869. lastColumn: null
  8870. };
  8871. };
  8872. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  8873. /**
  8874. * An IndexedSourceMapConsumer instance represents a parsed source map which
  8875. * we can query for information. It differs from BasicSourceMapConsumer in
  8876. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  8877. * input.
  8878. *
  8879. * The first parameter is a raw source map (either as a JSON string, or already
  8880. * parsed to an object). According to the spec for indexed source maps, they
  8881. * have the following attributes:
  8882. *
  8883. * - version: Which version of the source map spec this map is following.
  8884. * - file: Optional. The generated file this source map is associated with.
  8885. * - sections: A list of section definitions.
  8886. *
  8887. * Each value under the "sections" field has two fields:
  8888. * - offset: The offset into the original specified at which this section
  8889. * begins to apply, defined as an object with a "line" and "column"
  8890. * field.
  8891. * - map: A source map definition. This source map could also be indexed,
  8892. * but doesn't have to be.
  8893. *
  8894. * Instead of the "map" field, it's also possible to have a "url" field
  8895. * specifying a URL to retrieve a source map from, but that's currently
  8896. * unsupported.
  8897. *
  8898. * Here's an example source map, taken from the source map spec[0], but
  8899. * modified to omit a section which uses the "url" field.
  8900. *
  8901. * {
  8902. * version : 3,
  8903. * file: "app.js",
  8904. * sections: [{
  8905. * offset: {line:100, column:10},
  8906. * map: {
  8907. * version : 3,
  8908. * file: "section.js",
  8909. * sources: ["foo.js", "bar.js"],
  8910. * names: ["src", "maps", "are", "fun"],
  8911. * mappings: "AAAA,E;;ABCDE;"
  8912. * }
  8913. * }],
  8914. * }
  8915. *
  8916. * The second parameter, if given, is a string whose value is the URL
  8917. * at which the source map was found. This URL is used to compute the
  8918. * sources array.
  8919. *
  8920. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  8921. */
  8922. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  8923. var sourceMap = aSourceMap;
  8924. if (typeof aSourceMap === 'string') {
  8925. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  8926. }
  8927. var version = util$1.getArg(sourceMap, 'version');
  8928. var sections = util$1.getArg(sourceMap, 'sections');
  8929. if (version != this._version) {
  8930. throw new Error('Unsupported version: ' + version);
  8931. }
  8932. this._sources = new ArraySet();
  8933. this._names = new ArraySet();
  8934. var lastOffset = {
  8935. line: -1,
  8936. column: 0
  8937. };
  8938. this._sections = sections.map(function (s) {
  8939. if (s.url) {
  8940. // The url field will require support for asynchronicity.
  8941. // See https://github.com/mozilla/source-map/issues/16
  8942. throw new Error('Support for url field in sections not implemented.');
  8943. }
  8944. var offset = util$1.getArg(s, 'offset');
  8945. var offsetLine = util$1.getArg(offset, 'line');
  8946. var offsetColumn = util$1.getArg(offset, 'column');
  8947. if (offsetLine < lastOffset.line ||
  8948. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  8949. throw new Error('Section offsets must be ordered and non-overlapping.');
  8950. }
  8951. lastOffset = offset;
  8952. return {
  8953. generatedOffset: {
  8954. // The offset fields are 0-based, but we use 1-based indices when
  8955. // encoding/decoding from VLQ.
  8956. generatedLine: offsetLine + 1,
  8957. generatedColumn: offsetColumn + 1
  8958. },
  8959. consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL)
  8960. }
  8961. });
  8962. }
  8963. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  8964. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1;
  8965. /**
  8966. * The version of the source mapping spec that we are consuming.
  8967. */
  8968. IndexedSourceMapConsumer.prototype._version = 3;
  8969. /**
  8970. * The list of original sources.
  8971. */
  8972. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  8973. get: function () {
  8974. var sources = [];
  8975. for (var i = 0; i < this._sections.length; i++) {
  8976. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  8977. sources.push(this._sections[i].consumer.sources[j]);
  8978. }
  8979. }
  8980. return sources;
  8981. }
  8982. });
  8983. /**
  8984. * Returns the original source, line, and column information for the generated
  8985. * source's line and column positions provided. The only argument is an object
  8986. * with the following properties:
  8987. *
  8988. * - line: The line number in the generated source. The line number
  8989. * is 1-based.
  8990. * - column: The column number in the generated source. The column
  8991. * number is 0-based.
  8992. *
  8993. * and an object is returned with the following properties:
  8994. *
  8995. * - source: The original source file, or null.
  8996. * - line: The line number in the original source, or null. The
  8997. * line number is 1-based.
  8998. * - column: The column number in the original source, or null. The
  8999. * column number is 0-based.
  9000. * - name: The original identifier, or null.
  9001. */
  9002. IndexedSourceMapConsumer.prototype.originalPositionFor =
  9003. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  9004. var needle = {
  9005. generatedLine: util$1.getArg(aArgs, 'line'),
  9006. generatedColumn: util$1.getArg(aArgs, 'column')
  9007. };
  9008. // Find the section containing the generated position we're trying to map
  9009. // to an original position.
  9010. var sectionIndex = binarySearch.search(needle, this._sections,
  9011. function(needle, section) {
  9012. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  9013. if (cmp) {
  9014. return cmp;
  9015. }
  9016. return (needle.generatedColumn -
  9017. section.generatedOffset.generatedColumn);
  9018. });
  9019. var section = this._sections[sectionIndex];
  9020. if (!section) {
  9021. return {
  9022. source: null,
  9023. line: null,
  9024. column: null,
  9025. name: null
  9026. };
  9027. }
  9028. return section.consumer.originalPositionFor({
  9029. line: needle.generatedLine -
  9030. (section.generatedOffset.generatedLine - 1),
  9031. column: needle.generatedColumn -
  9032. (section.generatedOffset.generatedLine === needle.generatedLine
  9033. ? section.generatedOffset.generatedColumn - 1
  9034. : 0),
  9035. bias: aArgs.bias
  9036. });
  9037. };
  9038. /**
  9039. * Return true if we have the source content for every source in the source
  9040. * map, false otherwise.
  9041. */
  9042. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  9043. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  9044. return this._sections.every(function (s) {
  9045. return s.consumer.hasContentsOfAllSources();
  9046. });
  9047. };
  9048. /**
  9049. * Returns the original source content. The only argument is the url of the
  9050. * original source file. Returns null if no original source content is
  9051. * available.
  9052. */
  9053. IndexedSourceMapConsumer.prototype.sourceContentFor =
  9054. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9055. for (var i = 0; i < this._sections.length; i++) {
  9056. var section = this._sections[i];
  9057. var content = section.consumer.sourceContentFor(aSource, true);
  9058. if (content) {
  9059. return content;
  9060. }
  9061. }
  9062. if (nullOnMissing) {
  9063. return null;
  9064. }
  9065. else {
  9066. throw new Error('"' + aSource + '" is not in the SourceMap.');
  9067. }
  9068. };
  9069. /**
  9070. * Returns the generated line and column information for the original source,
  9071. * line, and column positions provided. The only argument is an object with
  9072. * the following properties:
  9073. *
  9074. * - source: The filename of the original source.
  9075. * - line: The line number in the original source. The line number
  9076. * is 1-based.
  9077. * - column: The column number in the original source. The column
  9078. * number is 0-based.
  9079. *
  9080. * and an object is returned with the following properties:
  9081. *
  9082. * - line: The line number in the generated source, or null. The
  9083. * line number is 1-based.
  9084. * - column: The column number in the generated source, or null.
  9085. * The column number is 0-based.
  9086. */
  9087. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  9088. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  9089. for (var i = 0; i < this._sections.length; i++) {
  9090. var section = this._sections[i];
  9091. // Only consider this section if the requested source is in the list of
  9092. // sources of the consumer.
  9093. if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) {
  9094. continue;
  9095. }
  9096. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  9097. if (generatedPosition) {
  9098. var ret = {
  9099. line: generatedPosition.line +
  9100. (section.generatedOffset.generatedLine - 1),
  9101. column: generatedPosition.column +
  9102. (section.generatedOffset.generatedLine === generatedPosition.line
  9103. ? section.generatedOffset.generatedColumn - 1
  9104. : 0)
  9105. };
  9106. return ret;
  9107. }
  9108. }
  9109. return {
  9110. line: null,
  9111. column: null
  9112. };
  9113. };
  9114. /**
  9115. * Parse the mappings in a string in to a data structure which we can easily
  9116. * query (the ordered arrays in the `this.__generatedMappings` and
  9117. * `this.__originalMappings` properties).
  9118. */
  9119. IndexedSourceMapConsumer.prototype._parseMappings =
  9120. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9121. this.__generatedMappings = [];
  9122. this.__originalMappings = [];
  9123. for (var i = 0; i < this._sections.length; i++) {
  9124. var section = this._sections[i];
  9125. var sectionMappings = section.consumer._generatedMappings;
  9126. for (var j = 0; j < sectionMappings.length; j++) {
  9127. var mapping = sectionMappings[j];
  9128. var source = section.consumer._sources.at(mapping.source);
  9129. source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  9130. this._sources.add(source);
  9131. source = this._sources.indexOf(source);
  9132. var name = null;
  9133. if (mapping.name) {
  9134. name = section.consumer._names.at(mapping.name);
  9135. this._names.add(name);
  9136. name = this._names.indexOf(name);
  9137. }
  9138. // The mappings coming from the consumer for the section have
  9139. // generated positions relative to the start of the section, so we
  9140. // need to offset them to be relative to the start of the concatenated
  9141. // generated file.
  9142. var adjustedMapping = {
  9143. source: source,
  9144. generatedLine: mapping.generatedLine +
  9145. (section.generatedOffset.generatedLine - 1),
  9146. generatedColumn: mapping.generatedColumn +
  9147. (section.generatedOffset.generatedLine === mapping.generatedLine
  9148. ? section.generatedOffset.generatedColumn - 1
  9149. : 0),
  9150. originalLine: mapping.originalLine,
  9151. originalColumn: mapping.originalColumn,
  9152. name: name
  9153. };
  9154. this.__generatedMappings.push(adjustedMapping);
  9155. if (typeof adjustedMapping.originalLine === 'number') {
  9156. this.__originalMappings.push(adjustedMapping);
  9157. }
  9158. }
  9159. }
  9160. quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  9161. quickSort(this.__originalMappings, util$1.compareByOriginalPositions);
  9162. };
  9163. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  9164. var sourceNode = {};
  9165. /* -*- Mode: js; js-indent-level: 2; -*- */
  9166. /*
  9167. * Copyright 2011 Mozilla Foundation and contributors
  9168. * Licensed under the New BSD license. See LICENSE or:
  9169. * http://opensource.org/licenses/BSD-3-Clause
  9170. */
  9171. var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
  9172. var util = util$5;
  9173. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  9174. // operating systems these days (capturing the result).
  9175. var REGEX_NEWLINE = /(\r?\n)/;
  9176. // Newline character code for charCodeAt() comparisons
  9177. var NEWLINE_CODE = 10;
  9178. // Private symbol for identifying `SourceNode`s when multiple versions of
  9179. // the source-map library are loaded. This MUST NOT CHANGE across
  9180. // versions!
  9181. var isSourceNode = "$$$isSourceNode$$$";
  9182. /**
  9183. * SourceNodes provide a way to abstract over interpolating/concatenating
  9184. * snippets of generated JavaScript source code while maintaining the line and
  9185. * column information associated with the original source code.
  9186. *
  9187. * @param aLine The original line number.
  9188. * @param aColumn The original column number.
  9189. * @param aSource The original source's filename.
  9190. * @param aChunks Optional. An array of strings which are snippets of
  9191. * generated JS, or other SourceNodes.
  9192. * @param aName The original identifier.
  9193. */
  9194. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  9195. this.children = [];
  9196. this.sourceContents = {};
  9197. this.line = aLine == null ? null : aLine;
  9198. this.column = aColumn == null ? null : aColumn;
  9199. this.source = aSource == null ? null : aSource;
  9200. this.name = aName == null ? null : aName;
  9201. this[isSourceNode] = true;
  9202. if (aChunks != null) this.add(aChunks);
  9203. }
  9204. /**
  9205. * Creates a SourceNode from generated code and a SourceMapConsumer.
  9206. *
  9207. * @param aGeneratedCode The generated code
  9208. * @param aSourceMapConsumer The SourceMap for the generated code
  9209. * @param aRelativePath Optional. The path that relative sources in the
  9210. * SourceMapConsumer should be relative to.
  9211. */
  9212. SourceNode.fromStringWithSourceMap =
  9213. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  9214. // The SourceNode we want to fill with the generated code
  9215. // and the SourceMap
  9216. var node = new SourceNode();
  9217. // All even indices of this array are one line of the generated code,
  9218. // while all odd indices are the newlines between two adjacent lines
  9219. // (since `REGEX_NEWLINE` captures its match).
  9220. // Processed fragments are accessed by calling `shiftNextLine`.
  9221. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  9222. var remainingLinesIndex = 0;
  9223. var shiftNextLine = function() {
  9224. var lineContents = getNextLine();
  9225. // The last line of a file might not have a newline.
  9226. var newLine = getNextLine() || "";
  9227. return lineContents + newLine;
  9228. function getNextLine() {
  9229. return remainingLinesIndex < remainingLines.length ?
  9230. remainingLines[remainingLinesIndex++] : undefined;
  9231. }
  9232. };
  9233. // We need to remember the position of "remainingLines"
  9234. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  9235. // The generate SourceNodes we need a code range.
  9236. // To extract it current and last mapping is used.
  9237. // Here we store the last mapping.
  9238. var lastMapping = null;
  9239. aSourceMapConsumer.eachMapping(function (mapping) {
  9240. if (lastMapping !== null) {
  9241. // We add the code from "lastMapping" to "mapping":
  9242. // First check if there is a new line in between.
  9243. if (lastGeneratedLine < mapping.generatedLine) {
  9244. // Associate first line with "lastMapping"
  9245. addMappingWithCode(lastMapping, shiftNextLine());
  9246. lastGeneratedLine++;
  9247. lastGeneratedColumn = 0;
  9248. // The remaining code is added without mapping
  9249. } else {
  9250. // There is no new line in between.
  9251. // Associate the code between "lastGeneratedColumn" and
  9252. // "mapping.generatedColumn" with "lastMapping"
  9253. var nextLine = remainingLines[remainingLinesIndex] || '';
  9254. var code = nextLine.substr(0, mapping.generatedColumn -
  9255. lastGeneratedColumn);
  9256. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  9257. lastGeneratedColumn);
  9258. lastGeneratedColumn = mapping.generatedColumn;
  9259. addMappingWithCode(lastMapping, code);
  9260. // No more remaining code, continue
  9261. lastMapping = mapping;
  9262. return;
  9263. }
  9264. }
  9265. // We add the generated code until the first mapping
  9266. // to the SourceNode without any mapping.
  9267. // Each line is added as separate string.
  9268. while (lastGeneratedLine < mapping.generatedLine) {
  9269. node.add(shiftNextLine());
  9270. lastGeneratedLine++;
  9271. }
  9272. if (lastGeneratedColumn < mapping.generatedColumn) {
  9273. var nextLine = remainingLines[remainingLinesIndex] || '';
  9274. node.add(nextLine.substr(0, mapping.generatedColumn));
  9275. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  9276. lastGeneratedColumn = mapping.generatedColumn;
  9277. }
  9278. lastMapping = mapping;
  9279. }, this);
  9280. // We have processed all mappings.
  9281. if (remainingLinesIndex < remainingLines.length) {
  9282. if (lastMapping) {
  9283. // Associate the remaining code in the current line with "lastMapping"
  9284. addMappingWithCode(lastMapping, shiftNextLine());
  9285. }
  9286. // and add the remaining lines without any mapping
  9287. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  9288. }
  9289. // Copy sourcesContent into SourceNode
  9290. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  9291. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  9292. if (content != null) {
  9293. if (aRelativePath != null) {
  9294. sourceFile = util.join(aRelativePath, sourceFile);
  9295. }
  9296. node.setSourceContent(sourceFile, content);
  9297. }
  9298. });
  9299. return node;
  9300. function addMappingWithCode(mapping, code) {
  9301. if (mapping === null || mapping.source === undefined) {
  9302. node.add(code);
  9303. } else {
  9304. var source = aRelativePath
  9305. ? util.join(aRelativePath, mapping.source)
  9306. : mapping.source;
  9307. node.add(new SourceNode(mapping.originalLine,
  9308. mapping.originalColumn,
  9309. source,
  9310. code,
  9311. mapping.name));
  9312. }
  9313. }
  9314. };
  9315. /**
  9316. * Add a chunk of generated JS to this source node.
  9317. *
  9318. * @param aChunk A string snippet of generated JS code, another instance of
  9319. * SourceNode, or an array where each member is one of those things.
  9320. */
  9321. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  9322. if (Array.isArray(aChunk)) {
  9323. aChunk.forEach(function (chunk) {
  9324. this.add(chunk);
  9325. }, this);
  9326. }
  9327. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  9328. if (aChunk) {
  9329. this.children.push(aChunk);
  9330. }
  9331. }
  9332. else {
  9333. throw new TypeError(
  9334. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  9335. );
  9336. }
  9337. return this;
  9338. };
  9339. /**
  9340. * Add a chunk of generated JS to the beginning of this source node.
  9341. *
  9342. * @param aChunk A string snippet of generated JS code, another instance of
  9343. * SourceNode, or an array where each member is one of those things.
  9344. */
  9345. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  9346. if (Array.isArray(aChunk)) {
  9347. for (var i = aChunk.length-1; i >= 0; i--) {
  9348. this.prepend(aChunk[i]);
  9349. }
  9350. }
  9351. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  9352. this.children.unshift(aChunk);
  9353. }
  9354. else {
  9355. throw new TypeError(
  9356. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  9357. );
  9358. }
  9359. return this;
  9360. };
  9361. /**
  9362. * Walk over the tree of JS snippets in this node and its children. The
  9363. * walking function is called once for each snippet of JS and is passed that
  9364. * snippet and the its original associated source's line/column location.
  9365. *
  9366. * @param aFn The traversal function.
  9367. */
  9368. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  9369. var chunk;
  9370. for (var i = 0, len = this.children.length; i < len; i++) {
  9371. chunk = this.children[i];
  9372. if (chunk[isSourceNode]) {
  9373. chunk.walk(aFn);
  9374. }
  9375. else {
  9376. if (chunk !== '') {
  9377. aFn(chunk, { source: this.source,
  9378. line: this.line,
  9379. column: this.column,
  9380. name: this.name });
  9381. }
  9382. }
  9383. }
  9384. };
  9385. /**
  9386. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  9387. * each of `this.children`.
  9388. *
  9389. * @param aSep The separator.
  9390. */
  9391. SourceNode.prototype.join = function SourceNode_join(aSep) {
  9392. var newChildren;
  9393. var i;
  9394. var len = this.children.length;
  9395. if (len > 0) {
  9396. newChildren = [];
  9397. for (i = 0; i < len-1; i++) {
  9398. newChildren.push(this.children[i]);
  9399. newChildren.push(aSep);
  9400. }
  9401. newChildren.push(this.children[i]);
  9402. this.children = newChildren;
  9403. }
  9404. return this;
  9405. };
  9406. /**
  9407. * Call String.prototype.replace on the very right-most source snippet. Useful
  9408. * for trimming whitespace from the end of a source node, etc.
  9409. *
  9410. * @param aPattern The pattern to replace.
  9411. * @param aReplacement The thing to replace the pattern with.
  9412. */
  9413. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  9414. var lastChild = this.children[this.children.length - 1];
  9415. if (lastChild[isSourceNode]) {
  9416. lastChild.replaceRight(aPattern, aReplacement);
  9417. }
  9418. else if (typeof lastChild === 'string') {
  9419. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  9420. }
  9421. else {
  9422. this.children.push(''.replace(aPattern, aReplacement));
  9423. }
  9424. return this;
  9425. };
  9426. /**
  9427. * Set the source content for a source file. This will be added to the SourceMapGenerator
  9428. * in the sourcesContent field.
  9429. *
  9430. * @param aSourceFile The filename of the source file
  9431. * @param aSourceContent The content of the source file
  9432. */
  9433. SourceNode.prototype.setSourceContent =
  9434. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  9435. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  9436. };
  9437. /**
  9438. * Walk over the tree of SourceNodes. The walking function is called for each
  9439. * source file content and is passed the filename and source content.
  9440. *
  9441. * @param aFn The traversal function.
  9442. */
  9443. SourceNode.prototype.walkSourceContents =
  9444. function SourceNode_walkSourceContents(aFn) {
  9445. for (var i = 0, len = this.children.length; i < len; i++) {
  9446. if (this.children[i][isSourceNode]) {
  9447. this.children[i].walkSourceContents(aFn);
  9448. }
  9449. }
  9450. var sources = Object.keys(this.sourceContents);
  9451. for (var i = 0, len = sources.length; i < len; i++) {
  9452. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  9453. }
  9454. };
  9455. /**
  9456. * Return the string representation of this source node. Walks over the tree
  9457. * and concatenates all the various snippets together to one string.
  9458. */
  9459. SourceNode.prototype.toString = function SourceNode_toString() {
  9460. var str = "";
  9461. this.walk(function (chunk) {
  9462. str += chunk;
  9463. });
  9464. return str;
  9465. };
  9466. /**
  9467. * Returns the string representation of this source node along with a source
  9468. * map.
  9469. */
  9470. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  9471. var generated = {
  9472. code: "",
  9473. line: 1,
  9474. column: 0
  9475. };
  9476. var map = new SourceMapGenerator$1(aArgs);
  9477. var sourceMappingActive = false;
  9478. var lastOriginalSource = null;
  9479. var lastOriginalLine = null;
  9480. var lastOriginalColumn = null;
  9481. var lastOriginalName = null;
  9482. this.walk(function (chunk, original) {
  9483. generated.code += chunk;
  9484. if (original.source !== null
  9485. && original.line !== null
  9486. && original.column !== null) {
  9487. if(lastOriginalSource !== original.source
  9488. || lastOriginalLine !== original.line
  9489. || lastOriginalColumn !== original.column
  9490. || lastOriginalName !== original.name) {
  9491. map.addMapping({
  9492. source: original.source,
  9493. original: {
  9494. line: original.line,
  9495. column: original.column
  9496. },
  9497. generated: {
  9498. line: generated.line,
  9499. column: generated.column
  9500. },
  9501. name: original.name
  9502. });
  9503. }
  9504. lastOriginalSource = original.source;
  9505. lastOriginalLine = original.line;
  9506. lastOriginalColumn = original.column;
  9507. lastOriginalName = original.name;
  9508. sourceMappingActive = true;
  9509. } else if (sourceMappingActive) {
  9510. map.addMapping({
  9511. generated: {
  9512. line: generated.line,
  9513. column: generated.column
  9514. }
  9515. });
  9516. lastOriginalSource = null;
  9517. sourceMappingActive = false;
  9518. }
  9519. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  9520. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  9521. generated.line++;
  9522. generated.column = 0;
  9523. // Mappings end at eol
  9524. if (idx + 1 === length) {
  9525. lastOriginalSource = null;
  9526. sourceMappingActive = false;
  9527. } else if (sourceMappingActive) {
  9528. map.addMapping({
  9529. source: original.source,
  9530. original: {
  9531. line: original.line,
  9532. column: original.column
  9533. },
  9534. generated: {
  9535. line: generated.line,
  9536. column: generated.column
  9537. },
  9538. name: original.name
  9539. });
  9540. }
  9541. } else {
  9542. generated.column++;
  9543. }
  9544. }
  9545. });
  9546. this.walkSourceContents(function (sourceFile, sourceContent) {
  9547. map.setSourceContent(sourceFile, sourceContent);
  9548. });
  9549. return { code: generated.code, map: map };
  9550. };
  9551. sourceNode.SourceNode = SourceNode;
  9552. /*
  9553. * Copyright 2009-2011 Mozilla Foundation and contributors
  9554. * Licensed under the New BSD license. See LICENSE.txt or:
  9555. * http://opensource.org/licenses/BSD-3-Clause
  9556. */
  9557. sourceMap$1.SourceMapGenerator = sourceMapGenerator.SourceMapGenerator;
  9558. sourceMap$1.SourceMapConsumer = sourceMapConsumer.SourceMapConsumer;
  9559. sourceMap$1.SourceNode = sourceNode.SourceNode;
  9560. var sourceMap = sourceMap$1;
  9561. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  9562. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  9563. var mergeSourceMap = merge;
  9564. /**
  9565. * Merge old source map and new source map and return merged.
  9566. * If old or new source map value is falsy, return another one as it is.
  9567. *
  9568. * @param {object|string} [oldMap] old source map object
  9569. * @param {object|string} [newmap] new source map object
  9570. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  9571. */
  9572. function merge(oldMap, newMap) {
  9573. if (!oldMap) return newMap
  9574. if (!newMap) return oldMap
  9575. var oldMapConsumer = new SourceMapConsumer(oldMap);
  9576. var newMapConsumer = new SourceMapConsumer(newMap);
  9577. var mergedMapGenerator = new SourceMapGenerator();
  9578. // iterate on new map and overwrite original position of new map with one of old map
  9579. newMapConsumer.eachMapping(function(m) {
  9580. // pass when `originalLine` is null.
  9581. // It occurs in case that the node does not have origin in original code.
  9582. if (m.originalLine == null) return
  9583. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  9584. line: m.originalLine,
  9585. column: m.originalColumn
  9586. });
  9587. if (origPosInOldMap.source == null) return
  9588. mergedMapGenerator.addMapping({
  9589. original: {
  9590. line: origPosInOldMap.line,
  9591. column: origPosInOldMap.column
  9592. },
  9593. generated: {
  9594. line: m.generatedLine,
  9595. column: m.generatedColumn
  9596. },
  9597. source: origPosInOldMap.source,
  9598. name: origPosInOldMap.name
  9599. });
  9600. });
  9601. var consumers = [oldMapConsumer, newMapConsumer];
  9602. consumers.forEach(function(consumer) {
  9603. consumer.sources.forEach(function(sourceFile) {
  9604. mergedMapGenerator._sources.add(sourceFile);
  9605. var sourceContent = consumer.sourceContentFor(sourceFile);
  9606. if (sourceContent != null) {
  9607. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  9608. }
  9609. });
  9610. });
  9611. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  9612. mergedMapGenerator._file = oldMap.file;
  9613. return JSON.parse(mergedMapGenerator.toString())
  9614. }
  9615. var merge$1 = mergeSourceMap;
  9616. const scss = (source, map, options, load = require) => {
  9617. const nodeSass = load("sass");
  9618. const finalOptions = {
  9619. ...options,
  9620. data: getSource(source, options.filename, options.additionalData),
  9621. file: options.filename,
  9622. outFile: options.filename,
  9623. sourceMap: !!map
  9624. };
  9625. try {
  9626. const result = nodeSass.renderSync(finalOptions);
  9627. const dependencies = result.stats.includedFiles;
  9628. if (map) {
  9629. return {
  9630. code: result.css.toString(),
  9631. map: merge$1(map, JSON.parse(result.map.toString())),
  9632. errors: [],
  9633. dependencies
  9634. };
  9635. }
  9636. return { code: result.css.toString(), errors: [], dependencies };
  9637. } catch (e) {
  9638. return { code: "", errors: [e], dependencies: [] };
  9639. }
  9640. };
  9641. const sass = (source, map, options, load) => scss(
  9642. source,
  9643. map,
  9644. {
  9645. ...options,
  9646. indentedSyntax: true
  9647. },
  9648. load
  9649. );
  9650. const less = (source, map, options, load = require) => {
  9651. const nodeLess = load("less");
  9652. let result;
  9653. let error = null;
  9654. nodeLess.render(
  9655. getSource(source, options.filename, options.additionalData),
  9656. { ...options, syncImport: true },
  9657. (err, output) => {
  9658. error = err;
  9659. result = output;
  9660. }
  9661. );
  9662. if (error)
  9663. return { code: "", errors: [error], dependencies: [] };
  9664. const dependencies = result.imports;
  9665. if (map) {
  9666. return {
  9667. code: result.css.toString(),
  9668. map: merge$1(map, result.map),
  9669. errors: [],
  9670. dependencies
  9671. };
  9672. }
  9673. return {
  9674. code: result.css.toString(),
  9675. errors: [],
  9676. dependencies
  9677. };
  9678. };
  9679. const styl = (source, map, options, load = require) => {
  9680. const nodeStylus = load("stylus");
  9681. try {
  9682. const ref = nodeStylus(source);
  9683. Object.keys(options).forEach((key) => ref.set(key, options[key]));
  9684. if (map)
  9685. ref.set("sourcemap", { inline: false, comment: false });
  9686. const result = ref.render();
  9687. const dependencies = ref.deps();
  9688. if (map) {
  9689. return {
  9690. code: result,
  9691. map: merge$1(map, ref.sourcemap),
  9692. errors: [],
  9693. dependencies
  9694. };
  9695. }
  9696. return { code: result, errors: [], dependencies };
  9697. } catch (e) {
  9698. return { code: "", errors: [e], dependencies: [] };
  9699. }
  9700. };
  9701. function getSource(source, filename, additionalData) {
  9702. if (!additionalData)
  9703. return source;
  9704. if (shared.isFunction(additionalData)) {
  9705. return additionalData(source, filename);
  9706. }
  9707. return additionalData + source;
  9708. }
  9709. const processors = {
  9710. less,
  9711. sass,
  9712. scss,
  9713. styl,
  9714. stylus: styl
  9715. };
  9716. var buildExports = {};
  9717. var build = {
  9718. get exports(){ return buildExports; },
  9719. set exports(v){ buildExports = v; },
  9720. };
  9721. /**
  9722. * lodash (Custom Build) <https://lodash.com/>
  9723. * Build: `lodash modularize exports="npm" -o ./`
  9724. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  9725. * Released under MIT license <https://lodash.com/license>
  9726. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  9727. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  9728. */
  9729. /** Used as references for various `Number` constants. */
  9730. var INFINITY = 1 / 0;
  9731. /** `Object#toString` result references. */
  9732. var symbolTag = '[object Symbol]';
  9733. /** Used to match words composed of alphanumeric characters. */
  9734. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  9735. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  9736. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  9737. /** Used to compose unicode character classes. */
  9738. var rsAstralRange = '\\ud800-\\udfff',
  9739. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  9740. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  9741. rsDingbatRange = '\\u2700-\\u27bf',
  9742. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  9743. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  9744. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  9745. rsPunctuationRange = '\\u2000-\\u206f',
  9746. 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',
  9747. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  9748. rsVarRange = '\\ufe0e\\ufe0f',
  9749. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  9750. /** Used to compose unicode capture groups. */
  9751. var rsApos = "['\u2019]",
  9752. rsAstral = '[' + rsAstralRange + ']',
  9753. rsBreak = '[' + rsBreakRange + ']',
  9754. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  9755. rsDigits = '\\d+',
  9756. rsDingbat = '[' + rsDingbatRange + ']',
  9757. rsLower = '[' + rsLowerRange + ']',
  9758. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  9759. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  9760. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  9761. rsNonAstral = '[^' + rsAstralRange + ']',
  9762. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  9763. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  9764. rsUpper = '[' + rsUpperRange + ']',
  9765. rsZWJ = '\\u200d';
  9766. /** Used to compose unicode regexes. */
  9767. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  9768. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  9769. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  9770. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  9771. reOptMod = rsModifier + '?',
  9772. rsOptVar = '[' + rsVarRange + ']?',
  9773. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  9774. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  9775. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  9776. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  9777. /** Used to match apostrophes. */
  9778. var reApos = RegExp(rsApos, 'g');
  9779. /**
  9780. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  9781. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  9782. */
  9783. var reComboMark = RegExp(rsCombo, 'g');
  9784. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  9785. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  9786. /** Used to match complex or compound words. */
  9787. var reUnicodeWord = RegExp([
  9788. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  9789. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  9790. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  9791. rsUpper + '+' + rsOptUpperContr,
  9792. rsDigits,
  9793. rsEmoji
  9794. ].join('|'), 'g');
  9795. /** 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/). */
  9796. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  9797. /** Used to detect strings that need a more robust regexp to match words. */
  9798. 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 ]/;
  9799. /** Used to map Latin Unicode letters to basic Latin letters. */
  9800. var deburredLetters = {
  9801. // Latin-1 Supplement block.
  9802. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  9803. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  9804. '\xc7': 'C', '\xe7': 'c',
  9805. '\xd0': 'D', '\xf0': 'd',
  9806. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  9807. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  9808. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  9809. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  9810. '\xd1': 'N', '\xf1': 'n',
  9811. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  9812. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  9813. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  9814. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  9815. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  9816. '\xc6': 'Ae', '\xe6': 'ae',
  9817. '\xde': 'Th', '\xfe': 'th',
  9818. '\xdf': 'ss',
  9819. // Latin Extended-A block.
  9820. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  9821. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  9822. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  9823. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  9824. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  9825. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  9826. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  9827. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  9828. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  9829. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  9830. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  9831. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  9832. '\u0134': 'J', '\u0135': 'j',
  9833. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  9834. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  9835. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  9836. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  9837. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  9838. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  9839. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  9840. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  9841. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  9842. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  9843. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  9844. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  9845. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  9846. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  9847. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  9848. '\u0174': 'W', '\u0175': 'w',
  9849. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  9850. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  9851. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  9852. '\u0132': 'IJ', '\u0133': 'ij',
  9853. '\u0152': 'Oe', '\u0153': 'oe',
  9854. '\u0149': "'n", '\u017f': 'ss'
  9855. };
  9856. /** Detect free variable `global` from Node.js. */
  9857. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  9858. /** Detect free variable `self`. */
  9859. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  9860. /** Used as a reference to the global object. */
  9861. var root = freeGlobal || freeSelf || Function('return this')();
  9862. /**
  9863. * A specialized version of `_.reduce` for arrays without support for
  9864. * iteratee shorthands.
  9865. *
  9866. * @private
  9867. * @param {Array} [array] The array to iterate over.
  9868. * @param {Function} iteratee The function invoked per iteration.
  9869. * @param {*} [accumulator] The initial value.
  9870. * @param {boolean} [initAccum] Specify using the first element of `array` as
  9871. * the initial value.
  9872. * @returns {*} Returns the accumulated value.
  9873. */
  9874. function arrayReduce(array, iteratee, accumulator, initAccum) {
  9875. var index = -1,
  9876. length = array ? array.length : 0;
  9877. if (initAccum && length) {
  9878. accumulator = array[++index];
  9879. }
  9880. while (++index < length) {
  9881. accumulator = iteratee(accumulator, array[index], index, array);
  9882. }
  9883. return accumulator;
  9884. }
  9885. /**
  9886. * Converts an ASCII `string` to an array.
  9887. *
  9888. * @private
  9889. * @param {string} string The string to convert.
  9890. * @returns {Array} Returns the converted array.
  9891. */
  9892. function asciiToArray(string) {
  9893. return string.split('');
  9894. }
  9895. /**
  9896. * Splits an ASCII `string` into an array of its words.
  9897. *
  9898. * @private
  9899. * @param {string} The string to inspect.
  9900. * @returns {Array} Returns the words of `string`.
  9901. */
  9902. function asciiWords(string) {
  9903. return string.match(reAsciiWord) || [];
  9904. }
  9905. /**
  9906. * The base implementation of `_.propertyOf` without support for deep paths.
  9907. *
  9908. * @private
  9909. * @param {Object} object The object to query.
  9910. * @returns {Function} Returns the new accessor function.
  9911. */
  9912. function basePropertyOf(object) {
  9913. return function(key) {
  9914. return object == null ? undefined : object[key];
  9915. };
  9916. }
  9917. /**
  9918. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  9919. * letters to basic Latin letters.
  9920. *
  9921. * @private
  9922. * @param {string} letter The matched letter to deburr.
  9923. * @returns {string} Returns the deburred letter.
  9924. */
  9925. var deburrLetter = basePropertyOf(deburredLetters);
  9926. /**
  9927. * Checks if `string` contains Unicode symbols.
  9928. *
  9929. * @private
  9930. * @param {string} string The string to inspect.
  9931. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  9932. */
  9933. function hasUnicode(string) {
  9934. return reHasUnicode.test(string);
  9935. }
  9936. /**
  9937. * Checks if `string` contains a word composed of Unicode symbols.
  9938. *
  9939. * @private
  9940. * @param {string} string The string to inspect.
  9941. * @returns {boolean} Returns `true` if a word is found, else `false`.
  9942. */
  9943. function hasUnicodeWord(string) {
  9944. return reHasUnicodeWord.test(string);
  9945. }
  9946. /**
  9947. * Converts `string` to an array.
  9948. *
  9949. * @private
  9950. * @param {string} string The string to convert.
  9951. * @returns {Array} Returns the converted array.
  9952. */
  9953. function stringToArray(string) {
  9954. return hasUnicode(string)
  9955. ? unicodeToArray(string)
  9956. : asciiToArray(string);
  9957. }
  9958. /**
  9959. * Converts a Unicode `string` to an array.
  9960. *
  9961. * @private
  9962. * @param {string} string The string to convert.
  9963. * @returns {Array} Returns the converted array.
  9964. */
  9965. function unicodeToArray(string) {
  9966. return string.match(reUnicode) || [];
  9967. }
  9968. /**
  9969. * Splits a Unicode `string` into an array of its words.
  9970. *
  9971. * @private
  9972. * @param {string} The string to inspect.
  9973. * @returns {Array} Returns the words of `string`.
  9974. */
  9975. function unicodeWords(string) {
  9976. return string.match(reUnicodeWord) || [];
  9977. }
  9978. /** Used for built-in method references. */
  9979. var objectProto = Object.prototype;
  9980. /**
  9981. * Used to resolve the
  9982. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  9983. * of values.
  9984. */
  9985. var objectToString = objectProto.toString;
  9986. /** Built-in value references. */
  9987. var Symbol$1 = root.Symbol;
  9988. /** Used to convert symbols to primitives and strings. */
  9989. var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
  9990. symbolToString = symbolProto ? symbolProto.toString : undefined;
  9991. /**
  9992. * The base implementation of `_.slice` without an iteratee call guard.
  9993. *
  9994. * @private
  9995. * @param {Array} array The array to slice.
  9996. * @param {number} [start=0] The start position.
  9997. * @param {number} [end=array.length] The end position.
  9998. * @returns {Array} Returns the slice of `array`.
  9999. */
  10000. function baseSlice(array, start, end) {
  10001. var index = -1,
  10002. length = array.length;
  10003. if (start < 0) {
  10004. start = -start > length ? 0 : (length + start);
  10005. }
  10006. end = end > length ? length : end;
  10007. if (end < 0) {
  10008. end += length;
  10009. }
  10010. length = start > end ? 0 : ((end - start) >>> 0);
  10011. start >>>= 0;
  10012. var result = Array(length);
  10013. while (++index < length) {
  10014. result[index] = array[index + start];
  10015. }
  10016. return result;
  10017. }
  10018. /**
  10019. * The base implementation of `_.toString` which doesn't convert nullish
  10020. * values to empty strings.
  10021. *
  10022. * @private
  10023. * @param {*} value The value to process.
  10024. * @returns {string} Returns the string.
  10025. */
  10026. function baseToString(value) {
  10027. // Exit early for strings to avoid a performance hit in some environments.
  10028. if (typeof value == 'string') {
  10029. return value;
  10030. }
  10031. if (isSymbol(value)) {
  10032. return symbolToString ? symbolToString.call(value) : '';
  10033. }
  10034. var result = (value + '');
  10035. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  10036. }
  10037. /**
  10038. * Casts `array` to a slice if it's needed.
  10039. *
  10040. * @private
  10041. * @param {Array} array The array to inspect.
  10042. * @param {number} start The start position.
  10043. * @param {number} [end=array.length] The end position.
  10044. * @returns {Array} Returns the cast slice.
  10045. */
  10046. function castSlice(array, start, end) {
  10047. var length = array.length;
  10048. end = end === undefined ? length : end;
  10049. return (!start && end >= length) ? array : baseSlice(array, start, end);
  10050. }
  10051. /**
  10052. * Creates a function like `_.lowerFirst`.
  10053. *
  10054. * @private
  10055. * @param {string} methodName The name of the `String` case method to use.
  10056. * @returns {Function} Returns the new case function.
  10057. */
  10058. function createCaseFirst(methodName) {
  10059. return function(string) {
  10060. string = toString(string);
  10061. var strSymbols = hasUnicode(string)
  10062. ? stringToArray(string)
  10063. : undefined;
  10064. var chr = strSymbols
  10065. ? strSymbols[0]
  10066. : string.charAt(0);
  10067. var trailing = strSymbols
  10068. ? castSlice(strSymbols, 1).join('')
  10069. : string.slice(1);
  10070. return chr[methodName]() + trailing;
  10071. };
  10072. }
  10073. /**
  10074. * Creates a function like `_.camelCase`.
  10075. *
  10076. * @private
  10077. * @param {Function} callback The function to combine each word.
  10078. * @returns {Function} Returns the new compounder function.
  10079. */
  10080. function createCompounder(callback) {
  10081. return function(string) {
  10082. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  10083. };
  10084. }
  10085. /**
  10086. * Checks if `value` is object-like. A value is object-like if it's not `null`
  10087. * and has a `typeof` result of "object".
  10088. *
  10089. * @static
  10090. * @memberOf _
  10091. * @since 4.0.0
  10092. * @category Lang
  10093. * @param {*} value The value to check.
  10094. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  10095. * @example
  10096. *
  10097. * _.isObjectLike({});
  10098. * // => true
  10099. *
  10100. * _.isObjectLike([1, 2, 3]);
  10101. * // => true
  10102. *
  10103. * _.isObjectLike(_.noop);
  10104. * // => false
  10105. *
  10106. * _.isObjectLike(null);
  10107. * // => false
  10108. */
  10109. function isObjectLike(value) {
  10110. return !!value && typeof value == 'object';
  10111. }
  10112. /**
  10113. * Checks if `value` is classified as a `Symbol` primitive or object.
  10114. *
  10115. * @static
  10116. * @memberOf _
  10117. * @since 4.0.0
  10118. * @category Lang
  10119. * @param {*} value The value to check.
  10120. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  10121. * @example
  10122. *
  10123. * _.isSymbol(Symbol.iterator);
  10124. * // => true
  10125. *
  10126. * _.isSymbol('abc');
  10127. * // => false
  10128. */
  10129. function isSymbol(value) {
  10130. return typeof value == 'symbol' ||
  10131. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  10132. }
  10133. /**
  10134. * Converts `value` to a string. An empty string is returned for `null`
  10135. * and `undefined` values. The sign of `-0` is preserved.
  10136. *
  10137. * @static
  10138. * @memberOf _
  10139. * @since 4.0.0
  10140. * @category Lang
  10141. * @param {*} value The value to process.
  10142. * @returns {string} Returns the string.
  10143. * @example
  10144. *
  10145. * _.toString(null);
  10146. * // => ''
  10147. *
  10148. * _.toString(-0);
  10149. * // => '-0'
  10150. *
  10151. * _.toString([1, 2, 3]);
  10152. * // => '1,2,3'
  10153. */
  10154. function toString(value) {
  10155. return value == null ? '' : baseToString(value);
  10156. }
  10157. /**
  10158. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  10159. *
  10160. * @static
  10161. * @memberOf _
  10162. * @since 3.0.0
  10163. * @category String
  10164. * @param {string} [string=''] The string to convert.
  10165. * @returns {string} Returns the camel cased string.
  10166. * @example
  10167. *
  10168. * _.camelCase('Foo Bar');
  10169. * // => 'fooBar'
  10170. *
  10171. * _.camelCase('--foo-bar--');
  10172. * // => 'fooBar'
  10173. *
  10174. * _.camelCase('__FOO_BAR__');
  10175. * // => 'fooBar'
  10176. */
  10177. var camelCase = createCompounder(function(result, word, index) {
  10178. word = word.toLowerCase();
  10179. return result + (index ? capitalize(word) : word);
  10180. });
  10181. /**
  10182. * Converts the first character of `string` to upper case and the remaining
  10183. * to lower case.
  10184. *
  10185. * @static
  10186. * @memberOf _
  10187. * @since 3.0.0
  10188. * @category String
  10189. * @param {string} [string=''] The string to capitalize.
  10190. * @returns {string} Returns the capitalized string.
  10191. * @example
  10192. *
  10193. * _.capitalize('FRED');
  10194. * // => 'Fred'
  10195. */
  10196. function capitalize(string) {
  10197. return upperFirst(toString(string).toLowerCase());
  10198. }
  10199. /**
  10200. * Deburrs `string` by converting
  10201. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  10202. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  10203. * letters to basic Latin letters and removing
  10204. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  10205. *
  10206. * @static
  10207. * @memberOf _
  10208. * @since 3.0.0
  10209. * @category String
  10210. * @param {string} [string=''] The string to deburr.
  10211. * @returns {string} Returns the deburred string.
  10212. * @example
  10213. *
  10214. * _.deburr('déjà vu');
  10215. * // => 'deja vu'
  10216. */
  10217. function deburr(string) {
  10218. string = toString(string);
  10219. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  10220. }
  10221. /**
  10222. * Converts the first character of `string` to upper case.
  10223. *
  10224. * @static
  10225. * @memberOf _
  10226. * @since 4.0.0
  10227. * @category String
  10228. * @param {string} [string=''] The string to convert.
  10229. * @returns {string} Returns the converted string.
  10230. * @example
  10231. *
  10232. * _.upperFirst('fred');
  10233. * // => 'Fred'
  10234. *
  10235. * _.upperFirst('FRED');
  10236. * // => 'FRED'
  10237. */
  10238. var upperFirst = createCaseFirst('toUpperCase');
  10239. /**
  10240. * Splits `string` into an array of its words.
  10241. *
  10242. * @static
  10243. * @memberOf _
  10244. * @since 3.0.0
  10245. * @category String
  10246. * @param {string} [string=''] The string to inspect.
  10247. * @param {RegExp|string} [pattern] The pattern to match words.
  10248. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  10249. * @returns {Array} Returns the words of `string`.
  10250. * @example
  10251. *
  10252. * _.words('fred, barney, & pebbles');
  10253. * // => ['fred', 'barney', 'pebbles']
  10254. *
  10255. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  10256. * // => ['fred', 'barney', '&', 'pebbles']
  10257. */
  10258. function words(string, pattern, guard) {
  10259. string = toString(string);
  10260. pattern = guard ? undefined : pattern;
  10261. if (pattern === undefined) {
  10262. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  10263. }
  10264. return string.match(pattern) || [];
  10265. }
  10266. var lodash_camelcase = camelCase;
  10267. var wasmHashExports = {};
  10268. var wasmHash = {
  10269. get exports(){ return wasmHashExports; },
  10270. set exports(v){ wasmHashExports = v; },
  10271. };
  10272. /*
  10273. MIT License http://www.opensource.org/licenses/mit-license.php
  10274. Author Tobias Koppers @sokra
  10275. */
  10276. var hasRequiredWasmHash;
  10277. function requireWasmHash () {
  10278. if (hasRequiredWasmHash) return wasmHashExports;
  10279. hasRequiredWasmHash = 1;
  10280. // 65536 is the size of a wasm memory page
  10281. // 64 is the maximum chunk size for every possible wasm hash implementation
  10282. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  10283. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  10284. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
  10285. class WasmHash {
  10286. /**
  10287. * @param {WebAssembly.Instance} instance wasm instance
  10288. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  10289. * @param {number} chunkSize size of data chunks passed to wasm
  10290. * @param {number} digestSize size of digest returned by wasm
  10291. */
  10292. constructor(instance, instancesPool, chunkSize, digestSize) {
  10293. const exports = /** @type {any} */ (instance.exports);
  10294. exports.init();
  10295. this.exports = exports;
  10296. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  10297. this.buffered = 0;
  10298. this.instancesPool = instancesPool;
  10299. this.chunkSize = chunkSize;
  10300. this.digestSize = digestSize;
  10301. }
  10302. reset() {
  10303. this.buffered = 0;
  10304. this.exports.init();
  10305. }
  10306. /**
  10307. * @param {Buffer | string} data data
  10308. * @param {BufferEncoding=} encoding encoding
  10309. * @returns {this} itself
  10310. */
  10311. update(data, encoding) {
  10312. if (typeof data === "string") {
  10313. while (data.length > MAX_SHORT_STRING) {
  10314. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  10315. data = data.slice(MAX_SHORT_STRING);
  10316. }
  10317. this._updateWithShortString(data, encoding);
  10318. return this;
  10319. }
  10320. this._updateWithBuffer(data);
  10321. return this;
  10322. }
  10323. /**
  10324. * @param {string} data data
  10325. * @param {BufferEncoding=} encoding encoding
  10326. * @returns {void}
  10327. */
  10328. _updateWithShortString(data, encoding) {
  10329. const { exports, buffered, mem, chunkSize } = this;
  10330. let endPos;
  10331. if (data.length < 70) {
  10332. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  10333. endPos = buffered;
  10334. for (let i = 0; i < data.length; i++) {
  10335. const cc = data.charCodeAt(i);
  10336. if (cc < 0x80) {
  10337. mem[endPos++] = cc;
  10338. } else if (cc < 0x800) {
  10339. mem[endPos] = (cc >> 6) | 0xc0;
  10340. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  10341. endPos += 2;
  10342. } else {
  10343. // bail-out for weird chars
  10344. endPos += mem.write(data.slice(i), endPos, encoding);
  10345. break;
  10346. }
  10347. }
  10348. } else if (encoding === "latin1") {
  10349. endPos = buffered;
  10350. for (let i = 0; i < data.length; i++) {
  10351. const cc = data.charCodeAt(i);
  10352. mem[endPos++] = cc;
  10353. }
  10354. } else {
  10355. endPos = buffered + mem.write(data, buffered, encoding);
  10356. }
  10357. } else {
  10358. endPos = buffered + mem.write(data, buffered, encoding);
  10359. }
  10360. if (endPos < chunkSize) {
  10361. this.buffered = endPos;
  10362. } else {
  10363. const l = endPos & ~(this.chunkSize - 1);
  10364. exports.update(l);
  10365. const newBuffered = endPos - l;
  10366. this.buffered = newBuffered;
  10367. if (newBuffered > 0) {
  10368. mem.copyWithin(0, l, endPos);
  10369. }
  10370. }
  10371. }
  10372. /**
  10373. * @param {Buffer} data data
  10374. * @returns {void}
  10375. */
  10376. _updateWithBuffer(data) {
  10377. const { exports, buffered, mem } = this;
  10378. const length = data.length;
  10379. if (buffered + length < this.chunkSize) {
  10380. data.copy(mem, buffered, 0, length);
  10381. this.buffered += length;
  10382. } else {
  10383. const l = (buffered + length) & ~(this.chunkSize - 1);
  10384. if (l > 65536) {
  10385. let i = 65536 - buffered;
  10386. data.copy(mem, buffered, 0, i);
  10387. exports.update(65536);
  10388. const stop = l - buffered - 65536;
  10389. while (i < stop) {
  10390. data.copy(mem, 0, i, i + 65536);
  10391. exports.update(65536);
  10392. i += 65536;
  10393. }
  10394. data.copy(mem, 0, i, l - buffered);
  10395. exports.update(l - buffered - i);
  10396. } else {
  10397. data.copy(mem, buffered, 0, l - buffered);
  10398. exports.update(l);
  10399. }
  10400. const newBuffered = length + buffered - l;
  10401. this.buffered = newBuffered;
  10402. if (newBuffered > 0) {
  10403. data.copy(mem, 0, length - newBuffered, length);
  10404. }
  10405. }
  10406. }
  10407. digest(type) {
  10408. const { exports, buffered, mem, digestSize } = this;
  10409. exports.final(buffered);
  10410. this.instancesPool.push(this);
  10411. const hex = mem.toString("latin1", 0, digestSize);
  10412. if (type === "hex") {
  10413. return hex;
  10414. }
  10415. if (type === "binary" || !type) {
  10416. return Buffer.from(hex, "hex");
  10417. }
  10418. return Buffer.from(hex, "hex").toString(type);
  10419. }
  10420. }
  10421. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  10422. if (instancesPool.length > 0) {
  10423. const old = instancesPool.pop();
  10424. old.reset();
  10425. return old;
  10426. } else {
  10427. return new WasmHash(
  10428. new WebAssembly.Instance(wasmModule),
  10429. instancesPool,
  10430. chunkSize,
  10431. digestSize
  10432. );
  10433. }
  10434. };
  10435. wasmHash.exports = create;
  10436. wasmHashExports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  10437. return wasmHashExports;
  10438. }
  10439. /*
  10440. MIT License http://www.opensource.org/licenses/mit-license.php
  10441. Author Tobias Koppers @sokra
  10442. */
  10443. var xxhash64_1;
  10444. var hasRequiredXxhash64;
  10445. function requireXxhash64 () {
  10446. if (hasRequiredXxhash64) return xxhash64_1;
  10447. hasRequiredXxhash64 = 1;
  10448. const create = requireWasmHash();
  10449. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  10450. const xxhash64 = new WebAssembly.Module(
  10451. Buffer.from(
  10452. // 1173 bytes
  10453. "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",
  10454. "base64"
  10455. )
  10456. );
  10457. //#endregion
  10458. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  10459. return xxhash64_1;
  10460. }
  10461. var BatchedHash_1;
  10462. var hasRequiredBatchedHash;
  10463. function requireBatchedHash () {
  10464. if (hasRequiredBatchedHash) return BatchedHash_1;
  10465. hasRequiredBatchedHash = 1;
  10466. const MAX_SHORT_STRING = requireWasmHash().MAX_SHORT_STRING;
  10467. class BatchedHash {
  10468. constructor(hash) {
  10469. this.string = undefined;
  10470. this.encoding = undefined;
  10471. this.hash = hash;
  10472. }
  10473. /**
  10474. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  10475. * @param {string|Buffer} data data
  10476. * @param {string=} inputEncoding data encoding
  10477. * @returns {this} updated hash
  10478. */
  10479. update(data, inputEncoding) {
  10480. if (this.string !== undefined) {
  10481. if (
  10482. typeof data === "string" &&
  10483. inputEncoding === this.encoding &&
  10484. this.string.length + data.length < MAX_SHORT_STRING
  10485. ) {
  10486. this.string += data;
  10487. return this;
  10488. }
  10489. this.hash.update(this.string, this.encoding);
  10490. this.string = undefined;
  10491. }
  10492. if (typeof data === "string") {
  10493. if (
  10494. data.length < MAX_SHORT_STRING &&
  10495. // base64 encoding is not valid since it may contain padding chars
  10496. (!inputEncoding || !inputEncoding.startsWith("ba"))
  10497. ) {
  10498. this.string = data;
  10499. this.encoding = inputEncoding;
  10500. } else {
  10501. this.hash.update(data, inputEncoding);
  10502. }
  10503. } else {
  10504. this.hash.update(data);
  10505. }
  10506. return this;
  10507. }
  10508. /**
  10509. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  10510. * @param {string=} encoding encoding of the return value
  10511. * @returns {string|Buffer} digest
  10512. */
  10513. digest(encoding) {
  10514. if (this.string !== undefined) {
  10515. this.hash.update(this.string, this.encoding);
  10516. }
  10517. return this.hash.digest(encoding);
  10518. }
  10519. }
  10520. BatchedHash_1 = BatchedHash;
  10521. return BatchedHash_1;
  10522. }
  10523. /*
  10524. MIT License http://www.opensource.org/licenses/mit-license.php
  10525. Author Tobias Koppers @sokra
  10526. */
  10527. var md4_1;
  10528. var hasRequiredMd4;
  10529. function requireMd4 () {
  10530. if (hasRequiredMd4) return md4_1;
  10531. hasRequiredMd4 = 1;
  10532. const create = requireWasmHash();
  10533. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  10534. const md4 = new WebAssembly.Module(
  10535. Buffer.from(
  10536. // 2150 bytes
  10537. "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=",
  10538. "base64"
  10539. )
  10540. );
  10541. //#endregion
  10542. md4_1 = create.bind(null, md4, [], 64, 32);
  10543. return md4_1;
  10544. }
  10545. var BulkUpdateDecorator_1;
  10546. var hasRequiredBulkUpdateDecorator;
  10547. function requireBulkUpdateDecorator () {
  10548. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  10549. hasRequiredBulkUpdateDecorator = 1;
  10550. const BULK_SIZE = 2000;
  10551. // We are using an object instead of a Map as this will stay static during the runtime
  10552. // so access to it can be optimized by v8
  10553. const digestCaches = {};
  10554. class BulkUpdateDecorator {
  10555. /**
  10556. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  10557. * @param {string=} hashKey key for caching
  10558. */
  10559. constructor(hashOrFactory, hashKey) {
  10560. this.hashKey = hashKey;
  10561. if (typeof hashOrFactory === "function") {
  10562. this.hashFactory = hashOrFactory;
  10563. this.hash = undefined;
  10564. } else {
  10565. this.hashFactory = undefined;
  10566. this.hash = hashOrFactory;
  10567. }
  10568. this.buffer = "";
  10569. }
  10570. /**
  10571. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  10572. * @param {string|Buffer} data data
  10573. * @param {string=} inputEncoding data encoding
  10574. * @returns {this} updated hash
  10575. */
  10576. update(data, inputEncoding) {
  10577. if (
  10578. inputEncoding !== undefined ||
  10579. typeof data !== "string" ||
  10580. data.length > BULK_SIZE
  10581. ) {
  10582. if (this.hash === undefined) {
  10583. this.hash = this.hashFactory();
  10584. }
  10585. if (this.buffer.length > 0) {
  10586. this.hash.update(this.buffer);
  10587. this.buffer = "";
  10588. }
  10589. this.hash.update(data, inputEncoding);
  10590. } else {
  10591. this.buffer += data;
  10592. if (this.buffer.length > BULK_SIZE) {
  10593. if (this.hash === undefined) {
  10594. this.hash = this.hashFactory();
  10595. }
  10596. this.hash.update(this.buffer);
  10597. this.buffer = "";
  10598. }
  10599. }
  10600. return this;
  10601. }
  10602. /**
  10603. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  10604. * @param {string=} encoding encoding of the return value
  10605. * @returns {string|Buffer} digest
  10606. */
  10607. digest(encoding) {
  10608. let digestCache;
  10609. const buffer = this.buffer;
  10610. if (this.hash === undefined) {
  10611. // short data for hash, we can use caching
  10612. const cacheKey = `${this.hashKey}-${encoding}`;
  10613. digestCache = digestCaches[cacheKey];
  10614. if (digestCache === undefined) {
  10615. digestCache = digestCaches[cacheKey] = new Map();
  10616. }
  10617. const cacheEntry = digestCache.get(buffer);
  10618. if (cacheEntry !== undefined) {
  10619. return cacheEntry;
  10620. }
  10621. this.hash = this.hashFactory();
  10622. }
  10623. if (buffer.length > 0) {
  10624. this.hash.update(buffer);
  10625. }
  10626. const digestResult = this.hash.digest(encoding);
  10627. if (digestCache !== undefined) {
  10628. digestCache.set(buffer, digestResult);
  10629. }
  10630. return digestResult;
  10631. }
  10632. }
  10633. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  10634. return BulkUpdateDecorator_1;
  10635. }
  10636. const baseEncodeTables = {
  10637. 26: "abcdefghijklmnopqrstuvwxyz",
  10638. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  10639. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  10640. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  10641. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  10642. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  10643. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  10644. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  10645. };
  10646. /**
  10647. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  10648. * @param {number} divisor The divisor
  10649. * @return {number} Modulo (remainder) of the division
  10650. */
  10651. function divmod32(uint32Array, divisor) {
  10652. let carry = 0;
  10653. for (let i = uint32Array.length - 1; i >= 0; i--) {
  10654. const value = carry * 0x100000000 + uint32Array[i];
  10655. carry = value % divisor;
  10656. uint32Array[i] = Math.floor(value / divisor);
  10657. }
  10658. return carry;
  10659. }
  10660. function encodeBufferToBase(buffer, base, length) {
  10661. const encodeTable = baseEncodeTables[base];
  10662. if (!encodeTable) {
  10663. throw new Error("Unknown encoding base" + base);
  10664. }
  10665. // Input bits are only enough to generate this many characters
  10666. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  10667. length = Math.min(length, limit);
  10668. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  10669. // Fewer numbers in the array means faster math.
  10670. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  10671. // Make sure the input buffer data is copied and is not mutated by reference.
  10672. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  10673. buffer.copy(Buffer.from(uint32Array.buffer));
  10674. let output = "";
  10675. for (let i = 0; i < length; i++) {
  10676. output = encodeTable[divmod32(uint32Array, base)] + output;
  10677. }
  10678. return output;
  10679. }
  10680. let crypto = undefined;
  10681. let createXXHash64 = undefined;
  10682. let createMd4 = undefined;
  10683. let BatchedHash = undefined;
  10684. let BulkUpdateDecorator = undefined;
  10685. function getHashDigest$1(buffer, algorithm, digestType, maxLength) {
  10686. algorithm = algorithm || "xxhash64";
  10687. maxLength = maxLength || 9999;
  10688. let hash;
  10689. if (algorithm === "xxhash64") {
  10690. if (createXXHash64 === undefined) {
  10691. createXXHash64 = requireXxhash64();
  10692. if (BatchedHash === undefined) {
  10693. BatchedHash = requireBatchedHash();
  10694. }
  10695. }
  10696. hash = new BatchedHash(createXXHash64());
  10697. } else if (algorithm === "md4") {
  10698. if (createMd4 === undefined) {
  10699. createMd4 = requireMd4();
  10700. if (BatchedHash === undefined) {
  10701. BatchedHash = requireBatchedHash();
  10702. }
  10703. }
  10704. hash = new BatchedHash(createMd4());
  10705. } else if (algorithm === "native-md4") {
  10706. if (typeof crypto === "undefined") {
  10707. crypto = require("crypto");
  10708. if (BulkUpdateDecorator === undefined) {
  10709. BulkUpdateDecorator = requireBulkUpdateDecorator();
  10710. }
  10711. }
  10712. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  10713. } else {
  10714. if (typeof crypto === "undefined") {
  10715. crypto = require("crypto");
  10716. if (BulkUpdateDecorator === undefined) {
  10717. BulkUpdateDecorator = requireBulkUpdateDecorator();
  10718. }
  10719. }
  10720. hash = new BulkUpdateDecorator(
  10721. () => crypto.createHash(algorithm),
  10722. algorithm
  10723. );
  10724. }
  10725. hash.update(buffer);
  10726. if (
  10727. digestType === "base26" ||
  10728. digestType === "base32" ||
  10729. digestType === "base36" ||
  10730. digestType === "base49" ||
  10731. digestType === "base52" ||
  10732. digestType === "base58" ||
  10733. digestType === "base62"
  10734. ) {
  10735. return encodeBufferToBase(hash.digest(), digestType.substr(4), maxLength);
  10736. } else {
  10737. return hash.digest(digestType || "hex").substr(0, maxLength);
  10738. }
  10739. }
  10740. var getHashDigest_1 = getHashDigest$1;
  10741. const path$2 = path$3;
  10742. const getHashDigest = getHashDigest_1;
  10743. function interpolateName$1(loaderContext, name, options = {}) {
  10744. let filename;
  10745. const hasQuery =
  10746. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  10747. if (typeof name === "function") {
  10748. filename = name(
  10749. loaderContext.resourcePath,
  10750. hasQuery ? loaderContext.resourceQuery : undefined
  10751. );
  10752. } else {
  10753. filename = name || "[hash].[ext]";
  10754. }
  10755. const context = options.context;
  10756. const content = options.content;
  10757. const regExp = options.regExp;
  10758. let ext = "bin";
  10759. let basename = "file";
  10760. let directory = "";
  10761. let folder = "";
  10762. let query = "";
  10763. if (loaderContext.resourcePath) {
  10764. const parsed = path$2.parse(loaderContext.resourcePath);
  10765. let resourcePath = loaderContext.resourcePath;
  10766. if (parsed.ext) {
  10767. ext = parsed.ext.substr(1);
  10768. }
  10769. if (parsed.dir) {
  10770. basename = parsed.name;
  10771. resourcePath = parsed.dir + path$2.sep;
  10772. }
  10773. if (typeof context !== "undefined") {
  10774. directory = path$2
  10775. .relative(context, resourcePath + "_")
  10776. .replace(/\\/g, "/")
  10777. .replace(/\.\.(\/)?/g, "_$1");
  10778. directory = directory.substr(0, directory.length - 1);
  10779. } else {
  10780. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  10781. }
  10782. if (directory.length === 1) {
  10783. directory = "";
  10784. } else if (directory.length > 1) {
  10785. folder = path$2.basename(directory);
  10786. }
  10787. }
  10788. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  10789. query = loaderContext.resourceQuery;
  10790. const hashIdx = query.indexOf("#");
  10791. if (hashIdx >= 0) {
  10792. query = query.substr(0, hashIdx);
  10793. }
  10794. }
  10795. let url = filename;
  10796. if (content) {
  10797. // Match hash template
  10798. url = url
  10799. // `hash` and `contenthash` are same in `loader-utils` context
  10800. // let's keep `hash` for backward compatibility
  10801. .replace(
  10802. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi,
  10803. (all, hashType, digestType, maxLength) =>
  10804. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  10805. );
  10806. }
  10807. url = url
  10808. .replace(/\[ext\]/gi, () => ext)
  10809. .replace(/\[name\]/gi, () => basename)
  10810. .replace(/\[path\]/gi, () => directory)
  10811. .replace(/\[folder\]/gi, () => folder)
  10812. .replace(/\[query\]/gi, () => query);
  10813. if (regExp && loaderContext.resourcePath) {
  10814. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  10815. match &&
  10816. match.forEach((matched, i) => {
  10817. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  10818. });
  10819. }
  10820. if (
  10821. typeof loaderContext.options === "object" &&
  10822. typeof loaderContext.options.customInterpolateName === "function"
  10823. ) {
  10824. url = loaderContext.options.customInterpolateName.call(
  10825. loaderContext,
  10826. url,
  10827. name,
  10828. options
  10829. );
  10830. }
  10831. return url;
  10832. }
  10833. var interpolateName_1 = interpolateName$1;
  10834. var interpolateName = interpolateName_1;
  10835. var path$1 = path$3;
  10836. /**
  10837. * @param {string} pattern
  10838. * @param {object} options
  10839. * @param {string} options.context
  10840. * @param {string} options.hashPrefix
  10841. * @return {function}
  10842. */
  10843. var genericNames = function createGenerator(pattern, options) {
  10844. options = options || {};
  10845. var context =
  10846. options && typeof options.context === "string"
  10847. ? options.context
  10848. : process.cwd();
  10849. var hashPrefix =
  10850. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  10851. /**
  10852. * @param {string} localName Usually a class name
  10853. * @param {string} filepath Absolute path
  10854. * @return {string}
  10855. */
  10856. return function generate(localName, filepath) {
  10857. var name = pattern.replace(/\[local\]/gi, localName);
  10858. var loaderContext = {
  10859. resourcePath: filepath,
  10860. };
  10861. var loaderOptions = {
  10862. content:
  10863. hashPrefix +
  10864. path$1.relative(context, filepath).replace(/\\/g, "/") +
  10865. "\x00" +
  10866. localName,
  10867. context: context,
  10868. };
  10869. var genericName = interpolateName(loaderContext, name, loaderOptions);
  10870. return genericName
  10871. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  10872. .replace(/^((-?[0-9])|--)/, "_$1");
  10873. };
  10874. };
  10875. var unquote$1 = {};
  10876. Object.defineProperty(unquote$1, "__esModule", {
  10877. value: true
  10878. });
  10879. unquote$1.default = unquote;
  10880. // copied from https://github.com/lakenen/node-unquote
  10881. var reg = /['"]/;
  10882. function unquote(str) {
  10883. if (!str) {
  10884. return "";
  10885. }
  10886. if (reg.test(str.charAt(0))) {
  10887. str = str.substr(1);
  10888. }
  10889. if (reg.test(str.charAt(str.length - 1))) {
  10890. str = str.substr(0, str.length - 1);
  10891. }
  10892. return str;
  10893. }
  10894. var parser = {};
  10895. var lib$1 = {};
  10896. Object.defineProperty(lib$1, "__esModule", {
  10897. value: true
  10898. });
  10899. lib$1.replaceAll = replaceAll;
  10900. var matchConstName = /[$#]?[\w-\.]+/g;
  10901. function replaceAll(replacements, text) {
  10902. var matches = void 0;
  10903. while (matches = matchConstName.exec(text)) {
  10904. var replacement = replacements[matches[0]];
  10905. if (replacement) {
  10906. text = text.slice(0, matches.index) + replacement + text.slice(matchConstName.lastIndex);
  10907. matchConstName.lastIndex -= matches[0].length - replacement.length;
  10908. }
  10909. }
  10910. return text;
  10911. }
  10912. lib$1.default = function (css, translations) {
  10913. css.walkDecls(function (decl) {
  10914. return decl.value = replaceAll(translations, decl.value);
  10915. });
  10916. css.walkAtRules('media', function (atRule) {
  10917. return atRule.params = replaceAll(translations, atRule.params);
  10918. });
  10919. };
  10920. Object.defineProperty(parser, "__esModule", {
  10921. value: true
  10922. });
  10923. var _icssReplaceSymbols = lib$1;
  10924. var _icssReplaceSymbols2 = _interopRequireDefault$4(_icssReplaceSymbols);
  10925. function _interopRequireDefault$4(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10926. // Copied from https://github.com/css-modules/css-modules-loader-core
  10927. const importRegexp = /^:import\((.+)\)$/;
  10928. class Parser {
  10929. constructor(pathFetcher, trace) {
  10930. this.pathFetcher = pathFetcher;
  10931. this.plugin = this.plugin.bind(this);
  10932. this.exportTokens = {};
  10933. this.translations = {};
  10934. this.trace = trace;
  10935. }
  10936. plugin() {
  10937. const parser = this;
  10938. return {
  10939. postcssPlugin: "css-modules-parser",
  10940. OnceExit(css) {
  10941. return Promise.all(parser.fetchAllImports(css)).then(() => parser.linkImportedSymbols(css)).then(() => parser.extractExports(css));
  10942. }
  10943. };
  10944. }
  10945. fetchAllImports(css) {
  10946. let imports = [];
  10947. css.each(node => {
  10948. if (node.type == "rule" && node.selector.match(importRegexp)) {
  10949. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  10950. }
  10951. });
  10952. return imports;
  10953. }
  10954. linkImportedSymbols(css) {
  10955. (0, _icssReplaceSymbols2.default)(css, this.translations);
  10956. }
  10957. extractExports(css) {
  10958. css.each(node => {
  10959. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  10960. });
  10961. }
  10962. handleExport(exportNode) {
  10963. exportNode.each(decl => {
  10964. if (decl.type == "decl") {
  10965. Object.keys(this.translations).forEach(translation => {
  10966. decl.value = decl.value.replace(translation, this.translations[translation]);
  10967. });
  10968. this.exportTokens[decl.prop] = decl.value;
  10969. }
  10970. });
  10971. exportNode.remove();
  10972. }
  10973. fetchImport(importNode, relativeTo, depNr) {
  10974. let file = importNode.selector.match(importRegexp)[1],
  10975. depTrace = this.trace + String.fromCharCode(depNr);
  10976. return this.pathFetcher(file, relativeTo, depTrace).then(exports => {
  10977. importNode.each(decl => {
  10978. if (decl.type == "decl") {
  10979. this.translations[decl.prop] = exports[decl.value];
  10980. }
  10981. });
  10982. importNode.remove();
  10983. }, err => console.log(err));
  10984. }
  10985. }
  10986. parser.default = Parser;
  10987. var loader = {};
  10988. Object.defineProperty(loader, "__esModule", {
  10989. value: true
  10990. });
  10991. var _postcss$1 = require$$0$1;
  10992. var _postcss2$1 = _interopRequireDefault$3(_postcss$1);
  10993. var _fs$1 = require$$0;
  10994. var _fs2 = _interopRequireDefault$3(_fs$1);
  10995. var _path = path$3;
  10996. var _path2 = _interopRequireDefault$3(_path);
  10997. var _parser$1 = parser;
  10998. var _parser2$1 = _interopRequireDefault$3(_parser$1);
  10999. function _interopRequireDefault$3(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11000. // Copied from https://github.com/css-modules/css-modules-loader-core
  11001. class Core {
  11002. constructor(plugins) {
  11003. this.plugins = plugins || Core.defaultPlugins;
  11004. }
  11005. load(sourceString, sourcePath, trace, pathFetcher) {
  11006. let parser = new _parser2$1.default(pathFetcher, trace);
  11007. return (0, _postcss2$1.default)(this.plugins.concat([parser.plugin()])).process(sourceString, { from: "/" + sourcePath }).then(result => {
  11008. return {
  11009. injectableSource: result.css,
  11010. exportTokens: parser.exportTokens
  11011. };
  11012. });
  11013. }
  11014. }
  11015. // Sorts dependencies in the following way:
  11016. // AAA comes before AA and A
  11017. // AB comes after AA and before A
  11018. // All Bs come after all As
  11019. // This ensures that the files are always returned in the following order:
  11020. // - In the order they were required, except
  11021. // - After all their dependencies
  11022. const traceKeySorter = (a, b) => {
  11023. if (a.length < b.length) {
  11024. return a < b.substring(0, a.length) ? -1 : 1;
  11025. } else if (a.length > b.length) {
  11026. return a.substring(0, b.length) <= b ? -1 : 1;
  11027. } else {
  11028. return a < b ? -1 : 1;
  11029. }
  11030. };
  11031. class FileSystemLoader {
  11032. constructor(root, plugins) {
  11033. this.root = root;
  11034. this.sources = {};
  11035. this.traces = {};
  11036. this.importNr = 0;
  11037. this.core = new Core(plugins);
  11038. this.tokensByFile = {};
  11039. }
  11040. fetch(_newPath, relativeTo, _trace) {
  11041. let newPath = _newPath.replace(/^["']|["']$/g, ""),
  11042. trace = _trace || String.fromCharCode(this.importNr++);
  11043. return new Promise((resolve, reject) => {
  11044. let relativeDir = _path2.default.dirname(relativeTo),
  11045. rootRelativePath = _path2.default.resolve(relativeDir, newPath),
  11046. fileRelativePath = _path2.default.resolve(_path2.default.join(this.root, relativeDir), newPath);
  11047. // if the path is not relative or absolute, try to resolve it in node_modules
  11048. if (newPath[0] !== "." && newPath[0] !== "/") {
  11049. try {
  11050. fileRelativePath = require.resolve(newPath);
  11051. } catch (e) {
  11052. // noop
  11053. }
  11054. }
  11055. const tokens = this.tokensByFile[fileRelativePath];
  11056. if (tokens) {
  11057. return resolve(tokens);
  11058. }
  11059. _fs2.default.readFile(fileRelativePath, "utf-8", (err, source) => {
  11060. if (err) reject(err);
  11061. this.core.load(source, rootRelativePath, trace, this.fetch.bind(this)).then(({ injectableSource, exportTokens }) => {
  11062. this.sources[fileRelativePath] = injectableSource;
  11063. this.traces[trace] = fileRelativePath;
  11064. this.tokensByFile[fileRelativePath] = exportTokens;
  11065. resolve(exportTokens);
  11066. }, reject);
  11067. });
  11068. });
  11069. }
  11070. get finalSource() {
  11071. const traces = this.traces;
  11072. const sources = this.sources;
  11073. let written = new Set();
  11074. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11075. const filename = traces[key];
  11076. if (written.has(filename)) {
  11077. return null;
  11078. }
  11079. written.add(filename);
  11080. return sources[filename];
  11081. }).join("");
  11082. }
  11083. }
  11084. loader.default = FileSystemLoader;
  11085. var generateScopedName$1 = {};
  11086. function hash(str) {
  11087. var hash = 5381,
  11088. i = str.length;
  11089. while(i) {
  11090. hash = (hash * 33) ^ str.charCodeAt(--i);
  11091. }
  11092. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  11093. * integers. Since we want the results to be always positive, convert the
  11094. * signed int to an unsigned by doing an unsigned bitshift. */
  11095. return hash >>> 0;
  11096. }
  11097. var stringHash = hash;
  11098. Object.defineProperty(generateScopedName$1, "__esModule", {
  11099. value: true
  11100. });
  11101. generateScopedName$1.default = generateScopedName;
  11102. var _stringHash = stringHash;
  11103. var _stringHash2 = _interopRequireDefault$2(_stringHash);
  11104. function _interopRequireDefault$2(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11105. function generateScopedName(name, filename, css) {
  11106. const i = css.indexOf(`.${name}`);
  11107. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  11108. const hash = (0, _stringHash2.default)(css).toString(36).substr(0, 5);
  11109. return `_${name}_${hash}_${lineNumber}`;
  11110. }
  11111. var saveJSON$1 = {};
  11112. Object.defineProperty(saveJSON$1, "__esModule", {
  11113. value: true
  11114. });
  11115. saveJSON$1.default = saveJSON;
  11116. var _fs = require$$0;
  11117. function saveJSON(cssFile, json) {
  11118. return new Promise((resolve, reject) => {
  11119. (0, _fs.writeFile)(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11120. });
  11121. }
  11122. var behaviours$1 = {};
  11123. var srcExports$2 = {};
  11124. var src$4 = {
  11125. get exports(){ return srcExports$2; },
  11126. set exports(v){ srcExports$2 = v; },
  11127. };
  11128. var openParentheses = "(".charCodeAt(0);
  11129. var closeParentheses = ")".charCodeAt(0);
  11130. var singleQuote = "'".charCodeAt(0);
  11131. var doubleQuote = '"'.charCodeAt(0);
  11132. var backslash = "\\".charCodeAt(0);
  11133. var slash = "/".charCodeAt(0);
  11134. var comma = ",".charCodeAt(0);
  11135. var colon = ":".charCodeAt(0);
  11136. var star$2 = "*".charCodeAt(0);
  11137. var uLower = "u".charCodeAt(0);
  11138. var uUpper = "U".charCodeAt(0);
  11139. var plus = "+".charCodeAt(0);
  11140. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  11141. var parse$1 = function(input) {
  11142. var tokens = [];
  11143. var value = input;
  11144. var next,
  11145. quote,
  11146. prev,
  11147. token,
  11148. escape,
  11149. escapePos,
  11150. whitespacePos,
  11151. parenthesesOpenPos;
  11152. var pos = 0;
  11153. var code = value.charCodeAt(pos);
  11154. var max = value.length;
  11155. var stack = [{ nodes: tokens }];
  11156. var balanced = 0;
  11157. var parent;
  11158. var name = "";
  11159. var before = "";
  11160. var after = "";
  11161. while (pos < max) {
  11162. // Whitespaces
  11163. if (code <= 32) {
  11164. next = pos;
  11165. do {
  11166. next += 1;
  11167. code = value.charCodeAt(next);
  11168. } while (code <= 32);
  11169. token = value.slice(pos, next);
  11170. prev = tokens[tokens.length - 1];
  11171. if (code === closeParentheses && balanced) {
  11172. after = token;
  11173. } else if (prev && prev.type === "div") {
  11174. prev.after = token;
  11175. prev.sourceEndIndex += token.length;
  11176. } else if (
  11177. code === comma ||
  11178. code === colon ||
  11179. (code === slash &&
  11180. value.charCodeAt(next + 1) !== star$2 &&
  11181. (!parent ||
  11182. (parent && parent.type === "function" && parent.value !== "calc")))
  11183. ) {
  11184. before = token;
  11185. } else {
  11186. tokens.push({
  11187. type: "space",
  11188. sourceIndex: pos,
  11189. sourceEndIndex: next,
  11190. value: token
  11191. });
  11192. }
  11193. pos = next;
  11194. // Quotes
  11195. } else if (code === singleQuote || code === doubleQuote) {
  11196. next = pos;
  11197. quote = code === singleQuote ? "'" : '"';
  11198. token = {
  11199. type: "string",
  11200. sourceIndex: pos,
  11201. quote: quote
  11202. };
  11203. do {
  11204. escape = false;
  11205. next = value.indexOf(quote, next + 1);
  11206. if (~next) {
  11207. escapePos = next;
  11208. while (value.charCodeAt(escapePos - 1) === backslash) {
  11209. escapePos -= 1;
  11210. escape = !escape;
  11211. }
  11212. } else {
  11213. value += quote;
  11214. next = value.length - 1;
  11215. token.unclosed = true;
  11216. }
  11217. } while (escape);
  11218. token.value = value.slice(pos + 1, next);
  11219. token.sourceEndIndex = token.unclosed ? next : next + 1;
  11220. tokens.push(token);
  11221. pos = next + 1;
  11222. code = value.charCodeAt(pos);
  11223. // Comments
  11224. } else if (code === slash && value.charCodeAt(pos + 1) === star$2) {
  11225. next = value.indexOf("*/", pos);
  11226. token = {
  11227. type: "comment",
  11228. sourceIndex: pos,
  11229. sourceEndIndex: next + 2
  11230. };
  11231. if (next === -1) {
  11232. token.unclosed = true;
  11233. next = value.length;
  11234. token.sourceEndIndex = next;
  11235. }
  11236. token.value = value.slice(pos + 2, next);
  11237. tokens.push(token);
  11238. pos = next + 2;
  11239. code = value.charCodeAt(pos);
  11240. // Operation within calc
  11241. } else if (
  11242. (code === slash || code === star$2) &&
  11243. parent &&
  11244. parent.type === "function" &&
  11245. parent.value === "calc"
  11246. ) {
  11247. token = value[pos];
  11248. tokens.push({
  11249. type: "word",
  11250. sourceIndex: pos - before.length,
  11251. sourceEndIndex: pos + token.length,
  11252. value: token
  11253. });
  11254. pos += 1;
  11255. code = value.charCodeAt(pos);
  11256. // Dividers
  11257. } else if (code === slash || code === comma || code === colon) {
  11258. token = value[pos];
  11259. tokens.push({
  11260. type: "div",
  11261. sourceIndex: pos - before.length,
  11262. sourceEndIndex: pos + token.length,
  11263. value: token,
  11264. before: before,
  11265. after: ""
  11266. });
  11267. before = "";
  11268. pos += 1;
  11269. code = value.charCodeAt(pos);
  11270. // Open parentheses
  11271. } else if (openParentheses === code) {
  11272. // Whitespaces after open parentheses
  11273. next = pos;
  11274. do {
  11275. next += 1;
  11276. code = value.charCodeAt(next);
  11277. } while (code <= 32);
  11278. parenthesesOpenPos = pos;
  11279. token = {
  11280. type: "function",
  11281. sourceIndex: pos - name.length,
  11282. value: name,
  11283. before: value.slice(parenthesesOpenPos + 1, next)
  11284. };
  11285. pos = next;
  11286. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  11287. next -= 1;
  11288. do {
  11289. escape = false;
  11290. next = value.indexOf(")", next + 1);
  11291. if (~next) {
  11292. escapePos = next;
  11293. while (value.charCodeAt(escapePos - 1) === backslash) {
  11294. escapePos -= 1;
  11295. escape = !escape;
  11296. }
  11297. } else {
  11298. value += ")";
  11299. next = value.length - 1;
  11300. token.unclosed = true;
  11301. }
  11302. } while (escape);
  11303. // Whitespaces before closed
  11304. whitespacePos = next;
  11305. do {
  11306. whitespacePos -= 1;
  11307. code = value.charCodeAt(whitespacePos);
  11308. } while (code <= 32);
  11309. if (parenthesesOpenPos < whitespacePos) {
  11310. if (pos !== whitespacePos + 1) {
  11311. token.nodes = [
  11312. {
  11313. type: "word",
  11314. sourceIndex: pos,
  11315. sourceEndIndex: whitespacePos + 1,
  11316. value: value.slice(pos, whitespacePos + 1)
  11317. }
  11318. ];
  11319. } else {
  11320. token.nodes = [];
  11321. }
  11322. if (token.unclosed && whitespacePos + 1 !== next) {
  11323. token.after = "";
  11324. token.nodes.push({
  11325. type: "space",
  11326. sourceIndex: whitespacePos + 1,
  11327. sourceEndIndex: next,
  11328. value: value.slice(whitespacePos + 1, next)
  11329. });
  11330. } else {
  11331. token.after = value.slice(whitespacePos + 1, next);
  11332. token.sourceEndIndex = next;
  11333. }
  11334. } else {
  11335. token.after = "";
  11336. token.nodes = [];
  11337. }
  11338. pos = next + 1;
  11339. token.sourceEndIndex = token.unclosed ? next : pos;
  11340. code = value.charCodeAt(pos);
  11341. tokens.push(token);
  11342. } else {
  11343. balanced += 1;
  11344. token.after = "";
  11345. token.sourceEndIndex = pos + 1;
  11346. tokens.push(token);
  11347. stack.push(token);
  11348. tokens = token.nodes = [];
  11349. parent = token;
  11350. }
  11351. name = "";
  11352. // Close parentheses
  11353. } else if (closeParentheses === code && balanced) {
  11354. pos += 1;
  11355. code = value.charCodeAt(pos);
  11356. parent.after = after;
  11357. parent.sourceEndIndex += after.length;
  11358. after = "";
  11359. balanced -= 1;
  11360. stack[stack.length - 1].sourceEndIndex = pos;
  11361. stack.pop();
  11362. parent = stack[balanced];
  11363. tokens = parent.nodes;
  11364. // Words
  11365. } else {
  11366. next = pos;
  11367. do {
  11368. if (code === backslash) {
  11369. next += 1;
  11370. }
  11371. next += 1;
  11372. code = value.charCodeAt(next);
  11373. } while (
  11374. next < max &&
  11375. !(
  11376. code <= 32 ||
  11377. code === singleQuote ||
  11378. code === doubleQuote ||
  11379. code === comma ||
  11380. code === colon ||
  11381. code === slash ||
  11382. code === openParentheses ||
  11383. (code === star$2 &&
  11384. parent &&
  11385. parent.type === "function" &&
  11386. parent.value === "calc") ||
  11387. (code === slash &&
  11388. parent.type === "function" &&
  11389. parent.value === "calc") ||
  11390. (code === closeParentheses && balanced)
  11391. )
  11392. );
  11393. token = value.slice(pos, next);
  11394. if (openParentheses === code) {
  11395. name = token;
  11396. } else if (
  11397. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  11398. plus === token.charCodeAt(1) &&
  11399. isUnicodeRange.test(token.slice(2))
  11400. ) {
  11401. tokens.push({
  11402. type: "unicode-range",
  11403. sourceIndex: pos,
  11404. sourceEndIndex: next,
  11405. value: token
  11406. });
  11407. } else {
  11408. tokens.push({
  11409. type: "word",
  11410. sourceIndex: pos,
  11411. sourceEndIndex: next,
  11412. value: token
  11413. });
  11414. }
  11415. pos = next;
  11416. }
  11417. }
  11418. for (pos = stack.length - 1; pos; pos -= 1) {
  11419. stack[pos].unclosed = true;
  11420. stack[pos].sourceEndIndex = value.length;
  11421. }
  11422. return stack[0].nodes;
  11423. };
  11424. var walk$2 = function walk(nodes, cb, bubble) {
  11425. var i, max, node, result;
  11426. for (i = 0, max = nodes.length; i < max; i += 1) {
  11427. node = nodes[i];
  11428. if (!bubble) {
  11429. result = cb(node, i, nodes);
  11430. }
  11431. if (
  11432. result !== false &&
  11433. node.type === "function" &&
  11434. Array.isArray(node.nodes)
  11435. ) {
  11436. walk(node.nodes, cb, bubble);
  11437. }
  11438. if (bubble) {
  11439. cb(node, i, nodes);
  11440. }
  11441. }
  11442. };
  11443. function stringifyNode(node, custom) {
  11444. var type = node.type;
  11445. var value = node.value;
  11446. var buf;
  11447. var customResult;
  11448. if (custom && (customResult = custom(node)) !== undefined) {
  11449. return customResult;
  11450. } else if (type === "word" || type === "space") {
  11451. return value;
  11452. } else if (type === "string") {
  11453. buf = node.quote || "";
  11454. return buf + value + (node.unclosed ? "" : buf);
  11455. } else if (type === "comment") {
  11456. return "/*" + value + (node.unclosed ? "" : "*/");
  11457. } else if (type === "div") {
  11458. return (node.before || "") + value + (node.after || "");
  11459. } else if (Array.isArray(node.nodes)) {
  11460. buf = stringify$1(node.nodes, custom);
  11461. if (type !== "function") {
  11462. return buf;
  11463. }
  11464. return (
  11465. value +
  11466. "(" +
  11467. (node.before || "") +
  11468. buf +
  11469. (node.after || "") +
  11470. (node.unclosed ? "" : ")")
  11471. );
  11472. }
  11473. return value;
  11474. }
  11475. function stringify$1(nodes, custom) {
  11476. var result, i;
  11477. if (Array.isArray(nodes)) {
  11478. result = "";
  11479. for (i = nodes.length - 1; ~i; i -= 1) {
  11480. result = stringifyNode(nodes[i], custom) + result;
  11481. }
  11482. return result;
  11483. }
  11484. return stringifyNode(nodes, custom);
  11485. }
  11486. var stringify_1 = stringify$1;
  11487. var unit;
  11488. var hasRequiredUnit;
  11489. function requireUnit () {
  11490. if (hasRequiredUnit) return unit;
  11491. hasRequiredUnit = 1;
  11492. var minus = "-".charCodeAt(0);
  11493. var plus = "+".charCodeAt(0);
  11494. var dot = ".".charCodeAt(0);
  11495. var exp = "e".charCodeAt(0);
  11496. var EXP = "E".charCodeAt(0);
  11497. // Check if three code points would start a number
  11498. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  11499. function likeNumber(value) {
  11500. var code = value.charCodeAt(0);
  11501. var nextCode;
  11502. if (code === plus || code === minus) {
  11503. nextCode = value.charCodeAt(1);
  11504. if (nextCode >= 48 && nextCode <= 57) {
  11505. return true;
  11506. }
  11507. var nextNextCode = value.charCodeAt(2);
  11508. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  11509. return true;
  11510. }
  11511. return false;
  11512. }
  11513. if (code === dot) {
  11514. nextCode = value.charCodeAt(1);
  11515. if (nextCode >= 48 && nextCode <= 57) {
  11516. return true;
  11517. }
  11518. return false;
  11519. }
  11520. if (code >= 48 && code <= 57) {
  11521. return true;
  11522. }
  11523. return false;
  11524. }
  11525. // Consume a number
  11526. // https://www.w3.org/TR/css-syntax-3/#consume-number
  11527. unit = function(value) {
  11528. var pos = 0;
  11529. var length = value.length;
  11530. var code;
  11531. var nextCode;
  11532. var nextNextCode;
  11533. if (length === 0 || !likeNumber(value)) {
  11534. return false;
  11535. }
  11536. code = value.charCodeAt(pos);
  11537. if (code === plus || code === minus) {
  11538. pos++;
  11539. }
  11540. while (pos < length) {
  11541. code = value.charCodeAt(pos);
  11542. if (code < 48 || code > 57) {
  11543. break;
  11544. }
  11545. pos += 1;
  11546. }
  11547. code = value.charCodeAt(pos);
  11548. nextCode = value.charCodeAt(pos + 1);
  11549. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  11550. pos += 2;
  11551. while (pos < length) {
  11552. code = value.charCodeAt(pos);
  11553. if (code < 48 || code > 57) {
  11554. break;
  11555. }
  11556. pos += 1;
  11557. }
  11558. }
  11559. code = value.charCodeAt(pos);
  11560. nextCode = value.charCodeAt(pos + 1);
  11561. nextNextCode = value.charCodeAt(pos + 2);
  11562. if (
  11563. (code === exp || code === EXP) &&
  11564. ((nextCode >= 48 && nextCode <= 57) ||
  11565. ((nextCode === plus || nextCode === minus) &&
  11566. nextNextCode >= 48 &&
  11567. nextNextCode <= 57))
  11568. ) {
  11569. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  11570. while (pos < length) {
  11571. code = value.charCodeAt(pos);
  11572. if (code < 48 || code > 57) {
  11573. break;
  11574. }
  11575. pos += 1;
  11576. }
  11577. }
  11578. return {
  11579. number: value.slice(0, pos),
  11580. unit: value.slice(pos)
  11581. };
  11582. };
  11583. return unit;
  11584. }
  11585. var parse = parse$1;
  11586. var walk$1 = walk$2;
  11587. var stringify = stringify_1;
  11588. function ValueParser(value) {
  11589. if (this instanceof ValueParser) {
  11590. this.nodes = parse(value);
  11591. return this;
  11592. }
  11593. return new ValueParser(value);
  11594. }
  11595. ValueParser.prototype.toString = function() {
  11596. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  11597. };
  11598. ValueParser.prototype.walk = function(cb, bubble) {
  11599. walk$1(this.nodes, cb, bubble);
  11600. return this;
  11601. };
  11602. ValueParser.unit = requireUnit();
  11603. ValueParser.walk = walk$1;
  11604. ValueParser.stringify = stringify;
  11605. var lib = ValueParser;
  11606. const matchValueName = /[$]?[\w-]+/g;
  11607. const replaceValueSymbols$2 = (value, replacements) => {
  11608. let matches;
  11609. while ((matches = matchValueName.exec(value))) {
  11610. const replacement = replacements[matches[0]];
  11611. if (replacement) {
  11612. value =
  11613. value.slice(0, matches.index) +
  11614. replacement +
  11615. value.slice(matchValueName.lastIndex);
  11616. matchValueName.lastIndex -= matches[0].length - replacement.length;
  11617. }
  11618. }
  11619. return value;
  11620. };
  11621. var replaceValueSymbols_1 = replaceValueSymbols$2;
  11622. const replaceValueSymbols$1 = replaceValueSymbols_1;
  11623. const replaceSymbols$1 = (css, replacements) => {
  11624. css.walk((node) => {
  11625. if (node.type === "decl" && node.value) {
  11626. node.value = replaceValueSymbols$1(node.value.toString(), replacements);
  11627. } else if (node.type === "rule" && node.selector) {
  11628. node.selector = replaceValueSymbols$1(
  11629. node.selector.toString(),
  11630. replacements
  11631. );
  11632. } else if (node.type === "atrule" && node.params) {
  11633. node.params = replaceValueSymbols$1(node.params.toString(), replacements);
  11634. }
  11635. });
  11636. };
  11637. var replaceSymbols_1 = replaceSymbols$1;
  11638. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  11639. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  11640. const getDeclsObject = (rule) => {
  11641. const object = {};
  11642. rule.walkDecls((decl) => {
  11643. const before = decl.raws.before ? decl.raws.before.trim() : "";
  11644. object[before + decl.prop] = decl.value;
  11645. });
  11646. return object;
  11647. };
  11648. /**
  11649. *
  11650. * @param {string} css
  11651. * @param {boolean} removeRules
  11652. * @param {'auto' | 'rule' | 'at-rule'} mode
  11653. */
  11654. const extractICSS$2 = (css, removeRules = true, mode = "auto") => {
  11655. const icssImports = {};
  11656. const icssExports = {};
  11657. function addImports(node, path) {
  11658. const unquoted = path.replace(/'|"/g, "");
  11659. icssImports[unquoted] = Object.assign(
  11660. icssImports[unquoted] || {},
  11661. getDeclsObject(node)
  11662. );
  11663. if (removeRules) {
  11664. node.remove();
  11665. }
  11666. }
  11667. function addExports(node) {
  11668. Object.assign(icssExports, getDeclsObject(node));
  11669. if (removeRules) {
  11670. node.remove();
  11671. }
  11672. }
  11673. css.each((node) => {
  11674. if (node.type === "rule" && mode !== "at-rule") {
  11675. if (node.selector.slice(0, 7) === ":import") {
  11676. const matches = importPattern.exec(node.selector);
  11677. if (matches) {
  11678. addImports(node, matches[1]);
  11679. }
  11680. }
  11681. if (node.selector === ":export") {
  11682. addExports(node);
  11683. }
  11684. }
  11685. if (node.type === "atrule" && mode !== "rule") {
  11686. if (node.name === "icss-import") {
  11687. const matches = balancedQuotes.exec(node.params);
  11688. if (matches) {
  11689. addImports(node, matches[1]);
  11690. }
  11691. }
  11692. if (node.name === "icss-export") {
  11693. addExports(node);
  11694. }
  11695. }
  11696. });
  11697. return { icssImports, icssExports };
  11698. };
  11699. var extractICSS_1 = extractICSS$2;
  11700. const createImports = (imports, postcss, mode = "rule") => {
  11701. return Object.keys(imports).map((path) => {
  11702. const aliases = imports[path];
  11703. const declarations = Object.keys(aliases).map((key) =>
  11704. postcss.decl({
  11705. prop: key,
  11706. value: aliases[key],
  11707. raws: { before: "\n " },
  11708. })
  11709. );
  11710. const hasDeclarations = declarations.length > 0;
  11711. const rule =
  11712. mode === "rule"
  11713. ? postcss.rule({
  11714. selector: `:import('${path}')`,
  11715. raws: { after: hasDeclarations ? "\n" : "" },
  11716. })
  11717. : postcss.atRule({
  11718. name: "icss-import",
  11719. params: `'${path}'`,
  11720. raws: { after: hasDeclarations ? "\n" : "" },
  11721. });
  11722. if (hasDeclarations) {
  11723. rule.append(declarations);
  11724. }
  11725. return rule;
  11726. });
  11727. };
  11728. const createExports = (exports, postcss, mode = "rule") => {
  11729. const declarations = Object.keys(exports).map((key) =>
  11730. postcss.decl({
  11731. prop: key,
  11732. value: exports[key],
  11733. raws: { before: "\n " },
  11734. })
  11735. );
  11736. if (declarations.length === 0) {
  11737. return [];
  11738. }
  11739. const rule =
  11740. mode === "rule"
  11741. ? postcss.rule({
  11742. selector: `:export`,
  11743. raws: { after: "\n" },
  11744. })
  11745. : postcss.atRule({
  11746. name: "icss-export",
  11747. raws: { after: "\n" },
  11748. });
  11749. rule.append(declarations);
  11750. return [rule];
  11751. };
  11752. const createICSSRules$1 = (imports, exports, postcss, mode) => [
  11753. ...createImports(imports, postcss, mode),
  11754. ...createExports(exports, postcss, mode),
  11755. ];
  11756. var createICSSRules_1 = createICSSRules$1;
  11757. const replaceValueSymbols = replaceValueSymbols_1;
  11758. const replaceSymbols = replaceSymbols_1;
  11759. const extractICSS$1 = extractICSS_1;
  11760. const createICSSRules = createICSSRules_1;
  11761. var src$3 = {
  11762. replaceValueSymbols,
  11763. replaceSymbols,
  11764. extractICSS: extractICSS$1,
  11765. createICSSRules,
  11766. };
  11767. const selectorParser$1 = distExports;
  11768. const valueParser = lib;
  11769. const { extractICSS } = src$3;
  11770. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  11771. function normalizeNodeArray(nodes) {
  11772. const array = [];
  11773. nodes.forEach((x) => {
  11774. if (Array.isArray(x)) {
  11775. normalizeNodeArray(x).forEach((item) => {
  11776. array.push(item);
  11777. });
  11778. } else if (x) {
  11779. array.push(x);
  11780. }
  11781. });
  11782. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  11783. array.pop();
  11784. }
  11785. return array;
  11786. }
  11787. function localizeNode(rule, mode, localAliasMap) {
  11788. const transform = (node, context) => {
  11789. if (context.ignoreNextSpacing && !isSpacing(node)) {
  11790. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  11791. }
  11792. if (context.enforceNoSpacing && isSpacing(node)) {
  11793. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  11794. }
  11795. let newNodes;
  11796. switch (node.type) {
  11797. case "root": {
  11798. let resultingGlobal;
  11799. context.hasPureGlobals = false;
  11800. newNodes = node.nodes.map((n) => {
  11801. const nContext = {
  11802. global: context.global,
  11803. lastWasSpacing: true,
  11804. hasLocals: false,
  11805. explicit: false,
  11806. };
  11807. n = transform(n, nContext);
  11808. if (typeof resultingGlobal === "undefined") {
  11809. resultingGlobal = nContext.global;
  11810. } else if (resultingGlobal !== nContext.global) {
  11811. throw new Error(
  11812. 'Inconsistent rule global/local result in rule "' +
  11813. node +
  11814. '" (multiple selectors must result in the same mode for the rule)'
  11815. );
  11816. }
  11817. if (!nContext.hasLocals) {
  11818. context.hasPureGlobals = true;
  11819. }
  11820. return n;
  11821. });
  11822. context.global = resultingGlobal;
  11823. node.nodes = normalizeNodeArray(newNodes);
  11824. break;
  11825. }
  11826. case "selector": {
  11827. newNodes = node.map((childNode) => transform(childNode, context));
  11828. node = node.clone();
  11829. node.nodes = normalizeNodeArray(newNodes);
  11830. break;
  11831. }
  11832. case "combinator": {
  11833. if (isSpacing(node)) {
  11834. if (context.ignoreNextSpacing) {
  11835. context.ignoreNextSpacing = false;
  11836. context.lastWasSpacing = false;
  11837. context.enforceNoSpacing = false;
  11838. return null;
  11839. }
  11840. context.lastWasSpacing = true;
  11841. return node;
  11842. }
  11843. break;
  11844. }
  11845. case "pseudo": {
  11846. let childContext;
  11847. const isNested = !!node.length;
  11848. const isScoped = node.value === ":local" || node.value === ":global";
  11849. const isImportExport =
  11850. node.value === ":import" || node.value === ":export";
  11851. if (isImportExport) {
  11852. context.hasLocals = true;
  11853. // :local(.foo)
  11854. } else if (isNested) {
  11855. if (isScoped) {
  11856. if (node.nodes.length === 0) {
  11857. throw new Error(`${node.value}() can't be empty`);
  11858. }
  11859. if (context.inside) {
  11860. throw new Error(
  11861. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  11862. );
  11863. }
  11864. childContext = {
  11865. global: node.value === ":global",
  11866. inside: node.value,
  11867. hasLocals: false,
  11868. explicit: true,
  11869. };
  11870. newNodes = node
  11871. .map((childNode) => transform(childNode, childContext))
  11872. .reduce((acc, next) => acc.concat(next.nodes), []);
  11873. if (newNodes.length) {
  11874. const { before, after } = node.spaces;
  11875. const first = newNodes[0];
  11876. const last = newNodes[newNodes.length - 1];
  11877. first.spaces = { before, after: first.spaces.after };
  11878. last.spaces = { before: last.spaces.before, after };
  11879. }
  11880. node = newNodes;
  11881. break;
  11882. } else {
  11883. childContext = {
  11884. global: context.global,
  11885. inside: context.inside,
  11886. lastWasSpacing: true,
  11887. hasLocals: false,
  11888. explicit: context.explicit,
  11889. };
  11890. newNodes = node.map((childNode) =>
  11891. transform(childNode, childContext)
  11892. );
  11893. node = node.clone();
  11894. node.nodes = normalizeNodeArray(newNodes);
  11895. if (childContext.hasLocals) {
  11896. context.hasLocals = true;
  11897. }
  11898. }
  11899. break;
  11900. //:local .foo .bar
  11901. } else if (isScoped) {
  11902. if (context.inside) {
  11903. throw new Error(
  11904. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  11905. );
  11906. }
  11907. const addBackSpacing = !!node.spaces.before;
  11908. context.ignoreNextSpacing = context.lastWasSpacing
  11909. ? node.value
  11910. : false;
  11911. context.enforceNoSpacing = context.lastWasSpacing
  11912. ? false
  11913. : node.value;
  11914. context.global = node.value === ":global";
  11915. context.explicit = true;
  11916. // because this node has spacing that is lost when we remove it
  11917. // we make up for it by adding an extra combinator in since adding
  11918. // spacing on the parent selector doesn't work
  11919. return addBackSpacing
  11920. ? selectorParser$1.combinator({ value: " " })
  11921. : null;
  11922. }
  11923. break;
  11924. }
  11925. case "id":
  11926. case "class": {
  11927. if (!node.value) {
  11928. throw new Error("Invalid class or id selector syntax");
  11929. }
  11930. if (context.global) {
  11931. break;
  11932. }
  11933. const isImportedValue = localAliasMap.has(node.value);
  11934. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  11935. if (!isImportedValue || isImportedWithExplicitScope) {
  11936. const innerNode = node.clone();
  11937. innerNode.spaces = { before: "", after: "" };
  11938. node = selectorParser$1.pseudo({
  11939. value: ":local",
  11940. nodes: [innerNode],
  11941. spaces: node.spaces,
  11942. });
  11943. context.hasLocals = true;
  11944. }
  11945. break;
  11946. }
  11947. }
  11948. context.lastWasSpacing = false;
  11949. context.ignoreNextSpacing = false;
  11950. context.enforceNoSpacing = false;
  11951. return node;
  11952. };
  11953. const rootContext = {
  11954. global: mode === "global",
  11955. hasPureGlobals: false,
  11956. };
  11957. rootContext.selector = selectorParser$1((root) => {
  11958. transform(root, rootContext);
  11959. }).processSync(rule, { updateSelector: false, lossless: true });
  11960. return rootContext;
  11961. }
  11962. function localizeDeclNode(node, context) {
  11963. switch (node.type) {
  11964. case "word":
  11965. if (context.localizeNextItem) {
  11966. if (!context.localAliasMap.has(node.value)) {
  11967. node.value = ":local(" + node.value + ")";
  11968. context.localizeNextItem = false;
  11969. }
  11970. }
  11971. break;
  11972. case "function":
  11973. if (
  11974. context.options &&
  11975. context.options.rewriteUrl &&
  11976. node.value.toLowerCase() === "url"
  11977. ) {
  11978. node.nodes.map((nestedNode) => {
  11979. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  11980. return;
  11981. }
  11982. let newUrl = context.options.rewriteUrl(
  11983. context.global,
  11984. nestedNode.value
  11985. );
  11986. switch (nestedNode.type) {
  11987. case "string":
  11988. if (nestedNode.quote === "'") {
  11989. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  11990. }
  11991. if (nestedNode.quote === '"') {
  11992. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  11993. }
  11994. break;
  11995. case "word":
  11996. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  11997. break;
  11998. }
  11999. nestedNode.value = newUrl;
  12000. });
  12001. }
  12002. break;
  12003. }
  12004. return node;
  12005. }
  12006. function isWordAFunctionArgument(wordNode, functionNode) {
  12007. return functionNode
  12008. ? functionNode.nodes.some(
  12009. (functionNodeChild) =>
  12010. functionNodeChild.sourceIndex === wordNode.sourceIndex
  12011. )
  12012. : false;
  12013. }
  12014. function localizeDeclarationValues(localize, declaration, context) {
  12015. const valueNodes = valueParser(declaration.value);
  12016. valueNodes.walk((node, index, nodes) => {
  12017. const subContext = {
  12018. options: context.options,
  12019. global: context.global,
  12020. localizeNextItem: localize && !context.global,
  12021. localAliasMap: context.localAliasMap,
  12022. };
  12023. nodes[index] = localizeDeclNode(node, subContext);
  12024. });
  12025. declaration.value = valueNodes.toString();
  12026. }
  12027. function localizeDeclaration(declaration, context) {
  12028. const isAnimation = /animation$/i.test(declaration.prop);
  12029. if (isAnimation) {
  12030. const validIdent = /^-?[_a-z][_a-z0-9-]*$/i;
  12031. /*
  12032. The spec defines some keywords that you can use to describe properties such as the timing
  12033. function. These are still valid animation names, so as long as there is a property that accepts
  12034. a keyword, it is given priority. Only when all the properties that can take a keyword are
  12035. exhausted can the animation name be set to the keyword. I.e.
  12036. animation: infinite infinite;
  12037. The animation will repeat an infinite number of times from the first argument, and will have an
  12038. animation name of infinite from the second.
  12039. */
  12040. const animationKeywords = {
  12041. $alternate: 1,
  12042. "$alternate-reverse": 1,
  12043. $backwards: 1,
  12044. $both: 1,
  12045. $ease: 1,
  12046. "$ease-in": 1,
  12047. "$ease-in-out": 1,
  12048. "$ease-out": 1,
  12049. $forwards: 1,
  12050. $infinite: 1,
  12051. $linear: 1,
  12052. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  12053. $normal: 1,
  12054. $paused: 1,
  12055. $reverse: 1,
  12056. $running: 1,
  12057. "$step-end": 1,
  12058. "$step-start": 1,
  12059. $initial: Infinity,
  12060. $inherit: Infinity,
  12061. $unset: Infinity,
  12062. };
  12063. let parsedAnimationKeywords = {};
  12064. let stepsFunctionNode = null;
  12065. const valueNodes = valueParser(declaration.value).walk((node) => {
  12066. /* If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh. */
  12067. if (node.type === "div") {
  12068. parsedAnimationKeywords = {};
  12069. }
  12070. if (node.type === "function" && node.value.toLowerCase() === "steps") {
  12071. stepsFunctionNode = node;
  12072. }
  12073. const value =
  12074. node.type === "word" &&
  12075. !isWordAFunctionArgument(node, stepsFunctionNode)
  12076. ? node.value.toLowerCase()
  12077. : null;
  12078. let shouldParseAnimationName = false;
  12079. if (value && validIdent.test(value)) {
  12080. if ("$" + value in animationKeywords) {
  12081. parsedAnimationKeywords["$" + value] =
  12082. "$" + value in parsedAnimationKeywords
  12083. ? parsedAnimationKeywords["$" + value] + 1
  12084. : 0;
  12085. shouldParseAnimationName =
  12086. parsedAnimationKeywords["$" + value] >=
  12087. animationKeywords["$" + value];
  12088. } else {
  12089. shouldParseAnimationName = true;
  12090. }
  12091. }
  12092. const subContext = {
  12093. options: context.options,
  12094. global: context.global,
  12095. localizeNextItem: shouldParseAnimationName && !context.global,
  12096. localAliasMap: context.localAliasMap,
  12097. };
  12098. return localizeDeclNode(node, subContext);
  12099. });
  12100. declaration.value = valueNodes.toString();
  12101. return;
  12102. }
  12103. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  12104. if (isAnimationName) {
  12105. return localizeDeclarationValues(true, declaration, context);
  12106. }
  12107. const hasUrl = /url\(/i.test(declaration.value);
  12108. if (hasUrl) {
  12109. return localizeDeclarationValues(false, declaration, context);
  12110. }
  12111. }
  12112. src$4.exports = (options = {}) => {
  12113. if (
  12114. options &&
  12115. options.mode &&
  12116. options.mode !== "global" &&
  12117. options.mode !== "local" &&
  12118. options.mode !== "pure"
  12119. ) {
  12120. throw new Error(
  12121. 'options.mode must be either "global", "local" or "pure" (default "local")'
  12122. );
  12123. }
  12124. const pureMode = options && options.mode === "pure";
  12125. const globalMode = options && options.mode === "global";
  12126. return {
  12127. postcssPlugin: "postcss-modules-local-by-default",
  12128. prepare() {
  12129. const localAliasMap = new Map();
  12130. return {
  12131. Once(root) {
  12132. const { icssImports } = extractICSS(root, false);
  12133. Object.keys(icssImports).forEach((key) => {
  12134. Object.keys(icssImports[key]).forEach((prop) => {
  12135. localAliasMap.set(prop, icssImports[key][prop]);
  12136. });
  12137. });
  12138. root.walkAtRules((atRule) => {
  12139. if (/keyframes$/i.test(atRule.name)) {
  12140. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  12141. atRule.params
  12142. );
  12143. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  12144. atRule.params
  12145. );
  12146. let globalKeyframes = globalMode;
  12147. if (globalMatch) {
  12148. if (pureMode) {
  12149. throw atRule.error(
  12150. "@keyframes :global(...) is not allowed in pure mode"
  12151. );
  12152. }
  12153. atRule.params = globalMatch[1];
  12154. globalKeyframes = true;
  12155. } else if (localMatch) {
  12156. atRule.params = localMatch[0];
  12157. globalKeyframes = false;
  12158. } else if (!globalMode) {
  12159. if (atRule.params && !localAliasMap.has(atRule.params)) {
  12160. atRule.params = ":local(" + atRule.params + ")";
  12161. }
  12162. }
  12163. atRule.walkDecls((declaration) => {
  12164. localizeDeclaration(declaration, {
  12165. localAliasMap,
  12166. options: options,
  12167. global: globalKeyframes,
  12168. });
  12169. });
  12170. } else if (atRule.nodes) {
  12171. atRule.nodes.forEach((declaration) => {
  12172. if (declaration.type === "decl") {
  12173. localizeDeclaration(declaration, {
  12174. localAliasMap,
  12175. options: options,
  12176. global: globalMode,
  12177. });
  12178. }
  12179. });
  12180. }
  12181. });
  12182. root.walkRules((rule) => {
  12183. if (
  12184. rule.parent &&
  12185. rule.parent.type === "atrule" &&
  12186. /keyframes$/i.test(rule.parent.name)
  12187. ) {
  12188. // ignore keyframe rules
  12189. return;
  12190. }
  12191. const context = localizeNode(rule, options.mode, localAliasMap);
  12192. context.options = options;
  12193. context.localAliasMap = localAliasMap;
  12194. if (pureMode && context.hasPureGlobals) {
  12195. throw rule.error(
  12196. 'Selector "' +
  12197. rule.selector +
  12198. '" is not pure ' +
  12199. "(pure selectors must contain at least one local class or id)"
  12200. );
  12201. }
  12202. rule.selector = context.selector;
  12203. // Less-syntax mixins parse as rules with no nodes
  12204. if (rule.nodes) {
  12205. rule.nodes.forEach((declaration) =>
  12206. localizeDeclaration(declaration, context)
  12207. );
  12208. }
  12209. });
  12210. },
  12211. };
  12212. },
  12213. };
  12214. };
  12215. srcExports$2.postcss = true;
  12216. var srcExports$1 = {};
  12217. var src$2 = {
  12218. get exports(){ return srcExports$1; },
  12219. set exports(v){ srcExports$1 = v; },
  12220. };
  12221. const PERMANENT_MARKER = 2;
  12222. const TEMPORARY_MARKER = 1;
  12223. function createError(node, graph) {
  12224. const er = new Error("Nondeterministic import's order");
  12225. const related = graph[node];
  12226. const relatedNode = related.find(
  12227. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  12228. );
  12229. er.nodes = [node, relatedNode];
  12230. return er;
  12231. }
  12232. function walkGraph(node, graph, state, result, strict) {
  12233. if (state[node] === PERMANENT_MARKER) {
  12234. return;
  12235. }
  12236. if (state[node] === TEMPORARY_MARKER) {
  12237. if (strict) {
  12238. return createError(node, graph);
  12239. }
  12240. return;
  12241. }
  12242. state[node] = TEMPORARY_MARKER;
  12243. const children = graph[node];
  12244. const length = children.length;
  12245. for (let i = 0; i < length; ++i) {
  12246. const error = walkGraph(children[i], graph, state, result, strict);
  12247. if (error instanceof Error) {
  12248. return error;
  12249. }
  12250. }
  12251. state[node] = PERMANENT_MARKER;
  12252. result.push(node);
  12253. }
  12254. function topologicalSort$1(graph, strict) {
  12255. const result = [];
  12256. const state = {};
  12257. const nodes = Object.keys(graph);
  12258. const length = nodes.length;
  12259. for (let i = 0; i < length; ++i) {
  12260. const er = walkGraph(nodes[i], graph, state, result, strict);
  12261. if (er instanceof Error) {
  12262. return er;
  12263. }
  12264. }
  12265. return result;
  12266. }
  12267. var topologicalSort_1 = topologicalSort$1;
  12268. const topologicalSort = topologicalSort_1;
  12269. const matchImports$1 = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  12270. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  12271. const VISITED_MARKER = 1;
  12272. /**
  12273. * :import('G') {}
  12274. *
  12275. * Rule
  12276. * composes: ... from 'A'
  12277. * composes: ... from 'B'
  12278. * Rule
  12279. * composes: ... from 'A'
  12280. * composes: ... from 'A'
  12281. * composes: ... from 'C'
  12282. *
  12283. * Results in:
  12284. *
  12285. * graph: {
  12286. * G: [],
  12287. * A: [],
  12288. * B: ['A'],
  12289. * C: ['A'],
  12290. * }
  12291. */
  12292. function addImportToGraph(importId, parentId, graph, visited) {
  12293. const siblingsId = parentId + "_" + "siblings";
  12294. const visitedId = parentId + "_" + importId;
  12295. if (visited[visitedId] !== VISITED_MARKER) {
  12296. if (!Array.isArray(visited[siblingsId])) {
  12297. visited[siblingsId] = [];
  12298. }
  12299. const siblings = visited[siblingsId];
  12300. if (Array.isArray(graph[importId])) {
  12301. graph[importId] = graph[importId].concat(siblings);
  12302. } else {
  12303. graph[importId] = siblings.slice();
  12304. }
  12305. visited[visitedId] = VISITED_MARKER;
  12306. siblings.push(importId);
  12307. }
  12308. }
  12309. src$2.exports = (options = {}) => {
  12310. let importIndex = 0;
  12311. const createImportedName =
  12312. typeof options.createImportedName !== "function"
  12313. ? (importName /*, path*/) =>
  12314. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  12315. : options.createImportedName;
  12316. const failOnWrongOrder = options.failOnWrongOrder;
  12317. return {
  12318. postcssPlugin: "postcss-modules-extract-imports",
  12319. prepare() {
  12320. const graph = {};
  12321. const visited = {};
  12322. const existingImports = {};
  12323. const importDecls = {};
  12324. const imports = {};
  12325. return {
  12326. Once(root, postcss) {
  12327. // Check the existing imports order and save refs
  12328. root.walkRules((rule) => {
  12329. const matches = icssImport.exec(rule.selector);
  12330. if (matches) {
  12331. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  12332. const importPath = doubleQuotePath || singleQuotePath;
  12333. addImportToGraph(importPath, "root", graph, visited);
  12334. existingImports[importPath] = rule;
  12335. }
  12336. });
  12337. root.walkDecls(/^composes$/, (declaration) => {
  12338. const matches = declaration.value.match(matchImports$1);
  12339. if (!matches) {
  12340. return;
  12341. }
  12342. let tmpSymbols;
  12343. let [
  12344. ,
  12345. /*match*/ symbols,
  12346. doubleQuotePath,
  12347. singleQuotePath,
  12348. global,
  12349. ] = matches;
  12350. if (global) {
  12351. // Composing globals simply means changing these classes to wrap them in global(name)
  12352. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  12353. } else {
  12354. const importPath = doubleQuotePath || singleQuotePath;
  12355. let parent = declaration.parent;
  12356. let parentIndexes = "";
  12357. while (parent.type !== "root") {
  12358. parentIndexes =
  12359. parent.parent.index(parent) + "_" + parentIndexes;
  12360. parent = parent.parent;
  12361. }
  12362. const { selector } = declaration.parent;
  12363. const parentRule = `_${parentIndexes}${selector}`;
  12364. addImportToGraph(importPath, parentRule, graph, visited);
  12365. importDecls[importPath] = declaration;
  12366. imports[importPath] = imports[importPath] || {};
  12367. tmpSymbols = symbols.split(/\s+/).map((s) => {
  12368. if (!imports[importPath][s]) {
  12369. imports[importPath][s] = createImportedName(s, importPath);
  12370. }
  12371. return imports[importPath][s];
  12372. });
  12373. }
  12374. declaration.value = tmpSymbols.join(" ");
  12375. });
  12376. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  12377. if (importsOrder instanceof Error) {
  12378. const importPath = importsOrder.nodes.find((importPath) =>
  12379. // eslint-disable-next-line no-prototype-builtins
  12380. importDecls.hasOwnProperty(importPath)
  12381. );
  12382. const decl = importDecls[importPath];
  12383. throw decl.error(
  12384. "Failed to resolve order of composed modules " +
  12385. importsOrder.nodes
  12386. .map((importPath) => "`" + importPath + "`")
  12387. .join(", ") +
  12388. ".",
  12389. {
  12390. plugin: "postcss-modules-extract-imports",
  12391. word: "composes",
  12392. }
  12393. );
  12394. }
  12395. let lastImportRule;
  12396. importsOrder.forEach((path) => {
  12397. const importedSymbols = imports[path];
  12398. let rule = existingImports[path];
  12399. if (!rule && importedSymbols) {
  12400. rule = postcss.rule({
  12401. selector: `:import("${path}")`,
  12402. raws: { after: "\n" },
  12403. });
  12404. if (lastImportRule) {
  12405. root.insertAfter(lastImportRule, rule);
  12406. } else {
  12407. root.prepend(rule);
  12408. }
  12409. }
  12410. lastImportRule = rule;
  12411. if (!importedSymbols) {
  12412. return;
  12413. }
  12414. Object.keys(importedSymbols).forEach((importedSymbol) => {
  12415. rule.append(
  12416. postcss.decl({
  12417. value: importedSymbol,
  12418. prop: importedSymbols[importedSymbol],
  12419. raws: { before: "\n " },
  12420. })
  12421. );
  12422. });
  12423. });
  12424. },
  12425. };
  12426. },
  12427. };
  12428. };
  12429. srcExports$1.postcss = true;
  12430. const selectorParser = distExports;
  12431. const hasOwnProperty = Object.prototype.hasOwnProperty;
  12432. function getSingleLocalNamesForComposes(root) {
  12433. return root.nodes.map((node) => {
  12434. if (node.type !== "selector" || node.nodes.length !== 1) {
  12435. throw new Error(
  12436. `composition is only allowed when selector is single :local class name not in "${root}"`
  12437. );
  12438. }
  12439. node = node.nodes[0];
  12440. if (
  12441. node.type !== "pseudo" ||
  12442. node.value !== ":local" ||
  12443. node.nodes.length !== 1
  12444. ) {
  12445. throw new Error(
  12446. 'composition is only allowed when selector is single :local class name not in "' +
  12447. root +
  12448. '", "' +
  12449. node +
  12450. '" is weird'
  12451. );
  12452. }
  12453. node = node.first;
  12454. if (node.type !== "selector" || node.length !== 1) {
  12455. throw new Error(
  12456. 'composition is only allowed when selector is single :local class name not in "' +
  12457. root +
  12458. '", "' +
  12459. node +
  12460. '" is weird'
  12461. );
  12462. }
  12463. node = node.first;
  12464. if (node.type !== "class") {
  12465. // 'id' is not possible, because you can't compose ids
  12466. throw new Error(
  12467. 'composition is only allowed when selector is single :local class name not in "' +
  12468. root +
  12469. '", "' +
  12470. node +
  12471. '" is weird'
  12472. );
  12473. }
  12474. return node.value;
  12475. });
  12476. }
  12477. const whitespace = "[\\x20\\t\\r\\n\\f]";
  12478. const unescapeRegExp = new RegExp(
  12479. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  12480. "ig"
  12481. );
  12482. function unescape$1(str) {
  12483. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  12484. const high = "0x" + escaped - 0x10000;
  12485. // NaN means non-codepoint
  12486. // Workaround erroneous numeric interpretation of +"0x"
  12487. return high !== high || escapedWhitespace
  12488. ? escaped
  12489. : high < 0
  12490. ? // BMP codepoint
  12491. String.fromCharCode(high + 0x10000)
  12492. : // Supplemental Plane codepoint (surrogate pair)
  12493. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  12494. });
  12495. }
  12496. const plugin = (options = {}) => {
  12497. const generateScopedName =
  12498. (options && options.generateScopedName) || plugin.generateScopedName;
  12499. const generateExportEntry =
  12500. (options && options.generateExportEntry) || plugin.generateExportEntry;
  12501. const exportGlobals = options && options.exportGlobals;
  12502. return {
  12503. postcssPlugin: "postcss-modules-scope",
  12504. Once(root, { rule }) {
  12505. const exports = Object.create(null);
  12506. function exportScopedName(name, rawName) {
  12507. const scopedName = generateScopedName(
  12508. rawName ? rawName : name,
  12509. root.source.input.from,
  12510. root.source.input.css
  12511. );
  12512. const exportEntry = generateExportEntry(
  12513. rawName ? rawName : name,
  12514. scopedName,
  12515. root.source.input.from,
  12516. root.source.input.css
  12517. );
  12518. const { key, value } = exportEntry;
  12519. exports[key] = exports[key] || [];
  12520. if (exports[key].indexOf(value) < 0) {
  12521. exports[key].push(value);
  12522. }
  12523. return scopedName;
  12524. }
  12525. function localizeNode(node) {
  12526. switch (node.type) {
  12527. case "selector":
  12528. node.nodes = node.map(localizeNode);
  12529. return node;
  12530. case "class":
  12531. return selectorParser.className({
  12532. value: exportScopedName(
  12533. node.value,
  12534. node.raws && node.raws.value ? node.raws.value : null
  12535. ),
  12536. });
  12537. case "id": {
  12538. return selectorParser.id({
  12539. value: exportScopedName(
  12540. node.value,
  12541. node.raws && node.raws.value ? node.raws.value : null
  12542. ),
  12543. });
  12544. }
  12545. }
  12546. throw new Error(
  12547. `${node.type} ("${node}") is not allowed in a :local block`
  12548. );
  12549. }
  12550. function traverseNode(node) {
  12551. switch (node.type) {
  12552. case "pseudo":
  12553. if (node.value === ":local") {
  12554. if (node.nodes.length !== 1) {
  12555. throw new Error('Unexpected comma (",") in :local block');
  12556. }
  12557. const selector = localizeNode(node.first, node.spaces);
  12558. // move the spaces that were around the psuedo selector to the first
  12559. // non-container node
  12560. selector.first.spaces = node.spaces;
  12561. const nextNode = node.next();
  12562. if (
  12563. nextNode &&
  12564. nextNode.type === "combinator" &&
  12565. nextNode.value === " " &&
  12566. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  12567. ) {
  12568. selector.last.spaces.after = " ";
  12569. }
  12570. node.replaceWith(selector);
  12571. return;
  12572. }
  12573. /* falls through */
  12574. case "root":
  12575. case "selector": {
  12576. node.each(traverseNode);
  12577. break;
  12578. }
  12579. case "id":
  12580. case "class":
  12581. if (exportGlobals) {
  12582. exports[node.value] = [node.value];
  12583. }
  12584. break;
  12585. }
  12586. return node;
  12587. }
  12588. // Find any :import and remember imported names
  12589. const importedNames = {};
  12590. root.walkRules(/^:import\(.+\)$/, (rule) => {
  12591. rule.walkDecls((decl) => {
  12592. importedNames[decl.prop] = true;
  12593. });
  12594. });
  12595. // Find any :local selectors
  12596. root.walkRules((rule) => {
  12597. let parsedSelector = selectorParser().astSync(rule);
  12598. rule.selector = traverseNode(parsedSelector.clone()).toString();
  12599. rule.walkDecls(/composes|compose-with/i, (decl) => {
  12600. const localNames = getSingleLocalNamesForComposes(parsedSelector);
  12601. const classes = decl.value.split(/\s+/);
  12602. classes.forEach((className) => {
  12603. const global = /^global\(([^)]+)\)$/.exec(className);
  12604. if (global) {
  12605. localNames.forEach((exportedName) => {
  12606. exports[exportedName].push(global[1]);
  12607. });
  12608. } else if (hasOwnProperty.call(importedNames, className)) {
  12609. localNames.forEach((exportedName) => {
  12610. exports[exportedName].push(className);
  12611. });
  12612. } else if (hasOwnProperty.call(exports, className)) {
  12613. localNames.forEach((exportedName) => {
  12614. exports[className].forEach((item) => {
  12615. exports[exportedName].push(item);
  12616. });
  12617. });
  12618. } else {
  12619. throw decl.error(
  12620. `referenced class name "${className}" in ${decl.prop} not found`
  12621. );
  12622. }
  12623. });
  12624. decl.remove();
  12625. });
  12626. // Find any :local values
  12627. rule.walkDecls((decl) => {
  12628. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  12629. return;
  12630. }
  12631. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  12632. tokens = tokens.map((token, idx) => {
  12633. if (idx === 0 || tokens[idx - 1] === ",") {
  12634. let result = token;
  12635. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  12636. if (localMatch) {
  12637. const input = localMatch.input;
  12638. const matchPattern = localMatch[0];
  12639. const matchVal = localMatch[1];
  12640. const newVal = exportScopedName(matchVal);
  12641. result = input.replace(matchPattern, newVal);
  12642. } else {
  12643. return token;
  12644. }
  12645. return result;
  12646. } else {
  12647. return token;
  12648. }
  12649. });
  12650. decl.value = tokens.join("");
  12651. });
  12652. });
  12653. // Find any :local keyframes
  12654. root.walkAtRules(/keyframes$/i, (atRule) => {
  12655. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  12656. if (!localMatch) {
  12657. return;
  12658. }
  12659. atRule.params = exportScopedName(localMatch[1]);
  12660. });
  12661. // If we found any :locals, insert an :export rule
  12662. const exportedNames = Object.keys(exports);
  12663. if (exportedNames.length > 0) {
  12664. const exportRule = rule({ selector: ":export" });
  12665. exportedNames.forEach((exportedName) =>
  12666. exportRule.append({
  12667. prop: exportedName,
  12668. value: exports[exportedName].join(" "),
  12669. raws: { before: "\n " },
  12670. })
  12671. );
  12672. root.append(exportRule);
  12673. }
  12674. },
  12675. };
  12676. };
  12677. plugin.postcss = true;
  12678. plugin.generateScopedName = function (name, path) {
  12679. const sanitisedPath = path
  12680. .replace(/\.[^./\\]+$/, "")
  12681. .replace(/[\W_]+/g, "_")
  12682. .replace(/^_|_$/g, "");
  12683. return `_${sanitisedPath}__${name}`.trim();
  12684. };
  12685. plugin.generateExportEntry = function (name, scopedName) {
  12686. return {
  12687. key: unescape$1(name),
  12688. value: unescape$1(scopedName),
  12689. };
  12690. };
  12691. var src$1 = plugin;
  12692. var srcExports = {};
  12693. var src = {
  12694. get exports(){ return srcExports; },
  12695. set exports(v){ srcExports = v; },
  12696. };
  12697. const ICSSUtils = src$3;
  12698. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  12699. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  12700. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  12701. src.exports = (options) => {
  12702. let importIndex = 0;
  12703. const createImportedName =
  12704. (options && options.createImportedName) ||
  12705. ((importName /*, path*/) =>
  12706. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  12707. return {
  12708. postcssPlugin: "postcss-modules-values",
  12709. prepare(result) {
  12710. const importAliases = [];
  12711. const definitions = {};
  12712. return {
  12713. Once(root, postcss) {
  12714. root.walkAtRules(/value/i, (atRule) => {
  12715. const matches = atRule.params.match(matchImports);
  12716. if (matches) {
  12717. let [, /*match*/ aliases, path] = matches;
  12718. // We can use constants for path names
  12719. if (definitions[path]) {
  12720. path = definitions[path];
  12721. }
  12722. const imports = aliases
  12723. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  12724. .split(/\s*,\s*/)
  12725. .map((alias) => {
  12726. const tokens = matchImport.exec(alias);
  12727. if (tokens) {
  12728. const [, /*match*/ theirName, myName = theirName] = tokens;
  12729. const importedName = createImportedName(myName);
  12730. definitions[myName] = importedName;
  12731. return { theirName, importedName };
  12732. } else {
  12733. throw new Error(`@import statement "${alias}" is invalid!`);
  12734. }
  12735. });
  12736. importAliases.push({ path, imports });
  12737. atRule.remove();
  12738. return;
  12739. }
  12740. if (atRule.params.indexOf("@value") !== -1) {
  12741. result.warn("Invalid value definition: " + atRule.params);
  12742. }
  12743. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  12744. matchValueDefinition
  12745. );
  12746. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  12747. if (normalizedValue.length === 0) {
  12748. result.warn("Invalid value definition: " + atRule.params);
  12749. atRule.remove();
  12750. return;
  12751. }
  12752. let isOnlySpace = /^\s+$/.test(normalizedValue);
  12753. if (!isOnlySpace) {
  12754. value = value.trim();
  12755. }
  12756. // Add to the definitions, knowing that values can refer to each other
  12757. definitions[key] = ICSSUtils.replaceValueSymbols(
  12758. value,
  12759. definitions
  12760. );
  12761. atRule.remove();
  12762. });
  12763. /* If we have no definitions, don't continue */
  12764. if (!Object.keys(definitions).length) {
  12765. return;
  12766. }
  12767. /* Perform replacements */
  12768. ICSSUtils.replaceSymbols(root, definitions);
  12769. /* 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 */
  12770. const exportDeclarations = Object.keys(definitions).map((key) =>
  12771. postcss.decl({
  12772. value: definitions[key],
  12773. prop: key,
  12774. raws: { before: "\n " },
  12775. })
  12776. );
  12777. /* Add export rules if any */
  12778. if (exportDeclarations.length > 0) {
  12779. const exportRule = postcss.rule({
  12780. selector: ":export",
  12781. raws: { after: "\n" },
  12782. });
  12783. exportRule.append(exportDeclarations);
  12784. root.prepend(exportRule);
  12785. }
  12786. /* Add import rules */
  12787. importAliases.reverse().forEach(({ path, imports }) => {
  12788. const importRule = postcss.rule({
  12789. selector: `:import(${path})`,
  12790. raws: { after: "\n" },
  12791. });
  12792. imports.forEach(({ theirName, importedName }) => {
  12793. importRule.append({
  12794. value: theirName,
  12795. prop: importedName,
  12796. raws: { before: "\n " },
  12797. });
  12798. });
  12799. root.prepend(importRule);
  12800. });
  12801. },
  12802. };
  12803. },
  12804. };
  12805. };
  12806. srcExports.postcss = true;
  12807. Object.defineProperty(behaviours$1, "__esModule", {
  12808. value: true
  12809. });
  12810. behaviours$1.behaviours = undefined;
  12811. behaviours$1.getDefaultPlugins = getDefaultPlugins;
  12812. behaviours$1.isValidBehaviour = isValidBehaviour;
  12813. var _postcssModulesLocalByDefault = srcExports$2;
  12814. var _postcssModulesLocalByDefault2 = _interopRequireDefault$1(_postcssModulesLocalByDefault);
  12815. var _postcssModulesExtractImports = srcExports$1;
  12816. var _postcssModulesExtractImports2 = _interopRequireDefault$1(_postcssModulesExtractImports);
  12817. var _postcssModulesScope = src$1;
  12818. var _postcssModulesScope2 = _interopRequireDefault$1(_postcssModulesScope);
  12819. var _postcssModulesValues = srcExports;
  12820. var _postcssModulesValues2 = _interopRequireDefault$1(_postcssModulesValues);
  12821. function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12822. const behaviours = behaviours$1.behaviours = {
  12823. LOCAL: "local",
  12824. GLOBAL: "global"
  12825. };
  12826. function getDefaultPlugins({
  12827. behaviour,
  12828. generateScopedName,
  12829. exportGlobals
  12830. }) {
  12831. const scope = (0, _postcssModulesScope2.default)({ generateScopedName, exportGlobals });
  12832. const plugins = {
  12833. [behaviours.LOCAL]: [_postcssModulesValues2.default, (0, _postcssModulesLocalByDefault2.default)({ mode: 'local' }), _postcssModulesExtractImports2.default, scope],
  12834. [behaviours.GLOBAL]: [_postcssModulesValues2.default, (0, _postcssModulesLocalByDefault2.default)({ mode: 'global' }), _postcssModulesExtractImports2.default, scope]
  12835. };
  12836. return plugins[behaviour];
  12837. }
  12838. function isValidBehaviour(behaviour) {
  12839. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  12840. }
  12841. var _postcss = require$$0$1;
  12842. var _postcss2 = _interopRequireDefault(_postcss);
  12843. var _lodash = lodash_camelcase;
  12844. var _lodash2 = _interopRequireDefault(_lodash);
  12845. var _genericNames = genericNames;
  12846. var _genericNames2 = _interopRequireDefault(_genericNames);
  12847. var _unquote = unquote$1;
  12848. var _unquote2 = _interopRequireDefault(_unquote);
  12849. var _parser = parser;
  12850. var _parser2 = _interopRequireDefault(_parser);
  12851. var _loader = loader;
  12852. var _loader2 = _interopRequireDefault(_loader);
  12853. var _generateScopedName = generateScopedName$1;
  12854. var _generateScopedName2 = _interopRequireDefault(_generateScopedName);
  12855. var _saveJSON = saveJSON$1;
  12856. var _saveJSON2 = _interopRequireDefault(_saveJSON);
  12857. var _behaviours = behaviours$1;
  12858. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12859. function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
  12860. const PLUGIN_NAME = "postcss-modules";
  12861. function getDefaultScopeBehaviour(opts) {
  12862. if (opts.scopeBehaviour && (0, _behaviours.isValidBehaviour)(opts.scopeBehaviour)) {
  12863. return opts.scopeBehaviour;
  12864. }
  12865. return _behaviours.behaviours.LOCAL;
  12866. }
  12867. function getScopedNameGenerator(opts) {
  12868. const scopedNameGenerator = opts.generateScopedName || _generateScopedName2.default;
  12869. if (typeof scopedNameGenerator === "function") return scopedNameGenerator;
  12870. return (0, _genericNames2.default)(scopedNameGenerator, {
  12871. context: process.cwd(),
  12872. hashPrefix: opts.hashPrefix
  12873. });
  12874. }
  12875. function getLoader(opts, plugins) {
  12876. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  12877. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins) : new _loader2.default(root, plugins);
  12878. }
  12879. function isGlobalModule(globalModules, inputFile) {
  12880. return globalModules.some(regex => inputFile.match(regex));
  12881. }
  12882. function getDefaultPluginsList(opts, inputFile) {
  12883. const globalModulesList = opts.globalModulePaths || null;
  12884. const exportGlobals = opts.exportGlobals || false;
  12885. const defaultBehaviour = getDefaultScopeBehaviour(opts);
  12886. const generateScopedName = getScopedNameGenerator(opts);
  12887. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  12888. return (0, _behaviours.getDefaultPlugins)({
  12889. behaviour: _behaviours.behaviours.GLOBAL,
  12890. generateScopedName,
  12891. exportGlobals
  12892. });
  12893. }
  12894. return (0, _behaviours.getDefaultPlugins)({
  12895. behaviour: defaultBehaviour,
  12896. generateScopedName,
  12897. exportGlobals
  12898. });
  12899. }
  12900. function isOurPlugin(plugin) {
  12901. return plugin.postcssPlugin === PLUGIN_NAME;
  12902. }
  12903. function dashesCamelCase(string) {
  12904. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  12905. }
  12906. build.exports = (opts = {}) => {
  12907. return {
  12908. postcssPlugin: PLUGIN_NAME,
  12909. OnceExit(css, { result }) {
  12910. return _asyncToGenerator(function* () {
  12911. const getJSON = opts.getJSON || _saveJSON2.default;
  12912. const inputFile = css.source.input.file;
  12913. const pluginList = getDefaultPluginsList(opts, inputFile);
  12914. const resultPluginIndex = result.processor.plugins.findIndex(function (plugin) {
  12915. return isOurPlugin(plugin);
  12916. });
  12917. if (resultPluginIndex === -1) {
  12918. throw new Error('Plugin missing from options.');
  12919. }
  12920. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  12921. const loaderPlugins = [...earlierPlugins, ...pluginList];
  12922. const loader = getLoader(opts, loaderPlugins);
  12923. const fetcher = function fetcher(file, relativeTo, depTrace) {
  12924. const unquoteFile = (0, _unquote2.default)(file);
  12925. const resolvedResult = typeof opts.resolve === 'function' && opts.resolve(unquoteFile);
  12926. const resolvedFile = resolvedResult instanceof Promise ? resolvedResult : Promise.resolve(resolvedResult);
  12927. return resolvedFile.then(function (f) {
  12928. return loader.fetch.call(loader, `"${f || unquoteFile}"`, relativeTo, depTrace);
  12929. });
  12930. };
  12931. const parser = new _parser2.default(fetcher);
  12932. yield (0, _postcss2.default)([...pluginList, parser.plugin()]).process(css, {
  12933. from: inputFile
  12934. });
  12935. const out = loader.finalSource;
  12936. if (out) css.prepend(out);
  12937. if (opts.localsConvention) {
  12938. const isFunc = typeof opts.localsConvention === "function";
  12939. parser.exportTokens = Object.entries(parser.exportTokens).reduce(function (tokens, [className, value]) {
  12940. if (isFunc) {
  12941. tokens[opts.localsConvention(className, value, inputFile)] = value;
  12942. return tokens;
  12943. }
  12944. switch (opts.localsConvention) {
  12945. case "camelCase":
  12946. tokens[className] = value;
  12947. tokens[(0, _lodash2.default)(className)] = value;
  12948. break;
  12949. case "camelCaseOnly":
  12950. tokens[(0, _lodash2.default)(className)] = value;
  12951. break;
  12952. case "dashes":
  12953. tokens[className] = value;
  12954. tokens[dashesCamelCase(className)] = value;
  12955. break;
  12956. case "dashesOnly":
  12957. tokens[dashesCamelCase(className)] = value;
  12958. break;
  12959. }
  12960. return tokens;
  12961. }, {});
  12962. }
  12963. result.messages.push({
  12964. type: "export",
  12965. plugin: "postcss-modules",
  12966. exportTokens: parser.exportTokens
  12967. });
  12968. // getJSON may return a promise
  12969. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  12970. })();
  12971. }
  12972. };
  12973. };
  12974. buildExports.postcss = true;
  12975. function compileStyle(options) {
  12976. return doCompileStyle({
  12977. ...options,
  12978. isAsync: false
  12979. });
  12980. }
  12981. function compileStyleAsync(options) {
  12982. return doCompileStyle({
  12983. ...options,
  12984. isAsync: true
  12985. });
  12986. }
  12987. function doCompileStyle(options) {
  12988. const {
  12989. filename,
  12990. id,
  12991. scoped = false,
  12992. trim = true,
  12993. isProd = false,
  12994. modules = false,
  12995. modulesOptions = {},
  12996. preprocessLang,
  12997. postcssOptions,
  12998. postcssPlugins
  12999. } = options;
  13000. const preprocessor = preprocessLang && processors[preprocessLang];
  13001. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  13002. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  13003. const source = preProcessedSource ? preProcessedSource.code : options.source;
  13004. const shortId = id.replace(/^data-v-/, "");
  13005. const longId = `data-v-${shortId}`;
  13006. const plugins = (postcssPlugins || []).slice();
  13007. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  13008. if (trim) {
  13009. plugins.push(trimPlugin$1());
  13010. }
  13011. if (scoped) {
  13012. plugins.push(scopedPlugin$1(longId));
  13013. }
  13014. let cssModules;
  13015. if (modules) {
  13016. if (!options.isAsync) {
  13017. throw new Error(
  13018. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  13019. );
  13020. }
  13021. plugins.push(
  13022. buildExports({
  13023. ...modulesOptions,
  13024. getJSON: (_cssFileName, json) => {
  13025. cssModules = json;
  13026. }
  13027. })
  13028. );
  13029. }
  13030. const postCSSOptions = {
  13031. ...postcssOptions,
  13032. to: filename,
  13033. from: filename
  13034. };
  13035. if (map) {
  13036. postCSSOptions.map = {
  13037. inline: false,
  13038. annotation: false,
  13039. prev: map
  13040. };
  13041. }
  13042. let result;
  13043. let code;
  13044. let outMap;
  13045. const dependencies = new Set(
  13046. preProcessedSource ? preProcessedSource.dependencies : []
  13047. );
  13048. dependencies.delete(filename);
  13049. const errors = [];
  13050. if (preProcessedSource && preProcessedSource.errors.length) {
  13051. errors.push(...preProcessedSource.errors);
  13052. }
  13053. const recordPlainCssDependencies = (messages) => {
  13054. messages.forEach((msg) => {
  13055. if (msg.type === "dependency") {
  13056. dependencies.add(msg.file);
  13057. }
  13058. });
  13059. return dependencies;
  13060. };
  13061. try {
  13062. result = require$$0$1(plugins).process(source, postCSSOptions);
  13063. if (options.isAsync) {
  13064. return result.then((result2) => ({
  13065. code: result2.css || "",
  13066. map: result2.map && result2.map.toJSON(),
  13067. errors,
  13068. modules: cssModules,
  13069. rawResult: result2,
  13070. dependencies: recordPlainCssDependencies(result2.messages)
  13071. })).catch((error) => ({
  13072. code: "",
  13073. map: void 0,
  13074. errors: [...errors, error],
  13075. rawResult: void 0,
  13076. dependencies
  13077. }));
  13078. }
  13079. recordPlainCssDependencies(result.messages);
  13080. code = result.css;
  13081. outMap = result.map;
  13082. } catch (e) {
  13083. errors.push(e);
  13084. }
  13085. return {
  13086. code: code || ``,
  13087. map: outMap && outMap.toJSON(),
  13088. errors,
  13089. rawResult: result,
  13090. dependencies
  13091. };
  13092. }
  13093. function preprocess(options, preprocessor) {
  13094. return preprocessor(
  13095. options.source,
  13096. options.inMap || options.map,
  13097. {
  13098. filename: options.filename,
  13099. ...options.preprocessOptions
  13100. },
  13101. options.preprocessCustomRequire
  13102. );
  13103. }
  13104. function analyzeScriptBindings(ast) {
  13105. for (const node of ast) {
  13106. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  13107. return analyzeBindingsFromOptions(node.declaration);
  13108. }
  13109. }
  13110. return {};
  13111. }
  13112. function analyzeBindingsFromOptions(node) {
  13113. const bindings = {};
  13114. Object.defineProperty(bindings, "__isScriptSetup", {
  13115. enumerable: false,
  13116. value: false
  13117. });
  13118. for (const property of node.properties) {
  13119. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  13120. if (property.key.name === "props") {
  13121. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  13122. bindings[key] = "props";
  13123. }
  13124. } else if (property.key.name === "inject") {
  13125. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  13126. bindings[key] = "options";
  13127. }
  13128. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  13129. for (const key of getObjectExpressionKeys(property.value)) {
  13130. bindings[key] = "options";
  13131. }
  13132. }
  13133. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  13134. for (const bodyItem of property.body.body) {
  13135. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  13136. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  13137. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  13138. }
  13139. }
  13140. }
  13141. }
  13142. }
  13143. return bindings;
  13144. }
  13145. function getObjectExpressionKeys(node) {
  13146. const keys = [];
  13147. for (const prop of node.properties) {
  13148. if (prop.type === "SpreadElement")
  13149. continue;
  13150. const key = resolveObjectKey(prop.key, prop.computed);
  13151. if (key)
  13152. keys.push(String(key));
  13153. }
  13154. return keys;
  13155. }
  13156. function getArrayExpressionKeys(node) {
  13157. const keys = [];
  13158. for (const element of node.elements) {
  13159. if (element && element.type === "StringLiteral") {
  13160. keys.push(element.value);
  13161. }
  13162. }
  13163. return keys;
  13164. }
  13165. function getObjectOrArrayExpressionKeys(value) {
  13166. if (value.type === "ArrayExpression") {
  13167. return getArrayExpressionKeys(value);
  13168. }
  13169. if (value.type === "ObjectExpression") {
  13170. return getObjectExpressionKeys(value);
  13171. }
  13172. return [];
  13173. }
  13174. function rewriteDefault(input, as, parserPlugins) {
  13175. const ast = parser$2.parse(input, {
  13176. sourceType: "module",
  13177. plugins: parserPlugins
  13178. }).program.body;
  13179. const s = new MagicString(input);
  13180. rewriteDefaultAST(ast, s, as);
  13181. return s.toString();
  13182. }
  13183. function rewriteDefaultAST(ast, s, as) {
  13184. if (!hasDefaultExport(ast)) {
  13185. s.append(`
  13186. const ${as} = {}`);
  13187. return;
  13188. }
  13189. ast.forEach((node) => {
  13190. if (node.type === "ExportDefaultDeclaration") {
  13191. if (node.declaration.type === "ClassDeclaration") {
  13192. let start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  13193. s.overwrite(start, node.declaration.id.start, ` class `);
  13194. s.append(`
  13195. const ${as} = ${node.declaration.id.name}`);
  13196. } else {
  13197. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  13198. }
  13199. } else if (node.type === "ExportNamedDeclaration") {
  13200. for (const specifier of node.specifiers) {
  13201. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  13202. if (node.source) {
  13203. if (specifier.local.name === "default") {
  13204. s.prepend(
  13205. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  13206. `
  13207. );
  13208. const end2 = specifierEnd(s, specifier.local.end, node.end);
  13209. s.remove(specifier.start, end2);
  13210. s.append(`
  13211. const ${as} = __VUE_DEFAULT__`);
  13212. continue;
  13213. } else {
  13214. s.prepend(
  13215. `import { ${s.slice(
  13216. specifier.local.start,
  13217. specifier.local.end
  13218. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  13219. `
  13220. );
  13221. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  13222. s.remove(specifier.start, end2);
  13223. s.append(`
  13224. const ${as} = __VUE_DEFAULT__`);
  13225. continue;
  13226. }
  13227. }
  13228. const end = specifierEnd(s, specifier.end, node.end);
  13229. s.remove(specifier.start, end);
  13230. s.append(`
  13231. const ${as} = ${specifier.local.name}`);
  13232. }
  13233. }
  13234. }
  13235. });
  13236. }
  13237. function hasDefaultExport(ast) {
  13238. for (const stmt of ast) {
  13239. if (stmt.type === "ExportDefaultDeclaration") {
  13240. return true;
  13241. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  13242. (spec) => spec.exported.name === "default"
  13243. )) {
  13244. return true;
  13245. }
  13246. }
  13247. return false;
  13248. }
  13249. function specifierEnd(s, end, nodeEnd) {
  13250. let hasCommas = false;
  13251. let oldEnd = end;
  13252. while (end < nodeEnd) {
  13253. if (/\s/.test(s.slice(end, end + 1))) {
  13254. end++;
  13255. } else if (s.slice(end, end + 1) === ",") {
  13256. end++;
  13257. hasCommas = true;
  13258. break;
  13259. } else if (s.slice(end, end + 1) === "}") {
  13260. break;
  13261. }
  13262. }
  13263. return hasCommas ? end : oldEnd;
  13264. }
  13265. const normalScriptDefaultVar = `__default__`;
  13266. function processNormalScript(ctx, scopeId) {
  13267. const script = ctx.descriptor.script;
  13268. if (script.lang && !ctx.isJS && !ctx.isTS) {
  13269. return script;
  13270. }
  13271. try {
  13272. let content = script.content;
  13273. let map = script.map;
  13274. const scriptAst = ctx.scriptAst;
  13275. const bindings = analyzeScriptBindings(scriptAst.body);
  13276. const { source, filename, cssVars } = ctx.descriptor;
  13277. const { sourceMap, genDefaultAs, isProd } = ctx.options;
  13278. if (ctx.options.reactivityTransform && reactivityTransform.shouldTransform(content)) {
  13279. const s = new MagicString(source);
  13280. const startOffset = script.loc.start.offset;
  13281. const endOffset = script.loc.end.offset;
  13282. const { importedHelpers } = reactivityTransform.transformAST(scriptAst, s, startOffset);
  13283. if (importedHelpers.length) {
  13284. s.prepend(
  13285. `import { ${importedHelpers.map((h) => `${h} as _${h}`).join(", ")} } from 'vue'
  13286. `
  13287. );
  13288. }
  13289. s.remove(0, startOffset);
  13290. s.remove(endOffset, source.length);
  13291. content = s.toString();
  13292. if (sourceMap !== false) {
  13293. map = s.generateMap({
  13294. source: filename,
  13295. hires: true,
  13296. includeContent: true
  13297. });
  13298. }
  13299. }
  13300. if (cssVars.length || genDefaultAs) {
  13301. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  13302. const s = new MagicString(content);
  13303. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  13304. content = s.toString();
  13305. if (cssVars.length) {
  13306. content += genNormalScriptCssVarsCode(
  13307. cssVars,
  13308. bindings,
  13309. scopeId,
  13310. !!isProd,
  13311. defaultVar
  13312. );
  13313. }
  13314. if (!genDefaultAs) {
  13315. content += `
  13316. export default ${defaultVar}`;
  13317. }
  13318. }
  13319. return {
  13320. ...script,
  13321. content,
  13322. map,
  13323. bindings,
  13324. scriptAst: scriptAst.body
  13325. };
  13326. } catch (e) {
  13327. return script;
  13328. }
  13329. }
  13330. var _a, _b;
  13331. class ScriptCompileContext {
  13332. constructor(descriptor, options) {
  13333. this.descriptor = descriptor;
  13334. this.options = options;
  13335. this.source = this.descriptor.source;
  13336. this.filename = this.descriptor.filename;
  13337. this.s = new MagicString(this.source);
  13338. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  13339. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  13340. this.userImports = /* @__PURE__ */ Object.create(null);
  13341. // macros presence check
  13342. this.hasDefinePropsCall = false;
  13343. this.hasDefineEmitCall = false;
  13344. this.hasDefineExposeCall = false;
  13345. this.hasDefaultExportName = false;
  13346. this.hasDefaultExportRender = false;
  13347. this.hasDefineOptionsCall = false;
  13348. this.hasDefineSlotsCall = false;
  13349. this.hasDefineModelCall = false;
  13350. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  13351. // defineModel
  13352. this.modelDecls = {};
  13353. // codegen
  13354. this.bindingMetadata = {};
  13355. this.helperImports = /* @__PURE__ */ new Set();
  13356. const { script, scriptSetup } = descriptor;
  13357. const scriptLang = script && script.lang;
  13358. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  13359. this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx";
  13360. this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx";
  13361. const plugins = resolveParserPlugins(
  13362. scriptLang || scriptSetupLang,
  13363. options.babelParserPlugins
  13364. );
  13365. function parse(input, offset) {
  13366. try {
  13367. return parser$2.parse(input, {
  13368. plugins,
  13369. sourceType: "module"
  13370. }).program;
  13371. } catch (e) {
  13372. e.message = `[vue/compiler-sfc] ${e.message}
  13373. ${descriptor.filename}
  13374. ${shared.generateCodeFrame(
  13375. descriptor.source,
  13376. e.pos + offset,
  13377. e.pos + offset + 1
  13378. )}`;
  13379. throw e;
  13380. }
  13381. }
  13382. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  13383. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  13384. }
  13385. helper(key) {
  13386. this.helperImports.add(key);
  13387. return `_${key}`;
  13388. }
  13389. getString(node, scriptSetup = true) {
  13390. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  13391. return block.content.slice(node.start, node.end);
  13392. }
  13393. error(msg, node, scope) {
  13394. const offset = scope ? scope.offset : this.startOffset;
  13395. throw new Error(
  13396. `[@vue/compiler-sfc] ${msg}
  13397. ${(scope || this.descriptor).filename}
  13398. ${shared.generateCodeFrame(
  13399. (scope || this.descriptor).source,
  13400. node.start + offset,
  13401. node.end + offset
  13402. )}`
  13403. );
  13404. }
  13405. }
  13406. function resolveParserPlugins(lang, userPlugins, dts = false) {
  13407. const plugins = [];
  13408. if (lang === "jsx" || lang === "tsx") {
  13409. plugins.push("jsx");
  13410. } else if (userPlugins) {
  13411. userPlugins = userPlugins.filter((p) => p !== "jsx");
  13412. }
  13413. if (lang === "ts" || lang === "tsx") {
  13414. plugins.push(["typescript", { dts }]);
  13415. if (!plugins.includes("decorators")) {
  13416. plugins.push("decorators-legacy");
  13417. }
  13418. }
  13419. if (userPlugins) {
  13420. plugins.push(...userPlugins);
  13421. }
  13422. return plugins;
  13423. }
  13424. var balancedMatch = balanced$1;
  13425. function balanced$1(a, b, str) {
  13426. if (a instanceof RegExp) a = maybeMatch(a, str);
  13427. if (b instanceof RegExp) b = maybeMatch(b, str);
  13428. var r = range(a, b, str);
  13429. return r && {
  13430. start: r[0],
  13431. end: r[1],
  13432. pre: str.slice(0, r[0]),
  13433. body: str.slice(r[0] + a.length, r[1]),
  13434. post: str.slice(r[1] + b.length)
  13435. };
  13436. }
  13437. function maybeMatch(reg, str) {
  13438. var m = str.match(reg);
  13439. return m ? m[0] : null;
  13440. }
  13441. balanced$1.range = range;
  13442. function range(a, b, str) {
  13443. var begs, beg, left, right, result;
  13444. var ai = str.indexOf(a);
  13445. var bi = str.indexOf(b, ai + 1);
  13446. var i = ai;
  13447. if (ai >= 0 && bi > 0) {
  13448. if(a===b) {
  13449. return [ai, bi];
  13450. }
  13451. begs = [];
  13452. left = str.length;
  13453. while (i >= 0 && !result) {
  13454. if (i == ai) {
  13455. begs.push(i);
  13456. ai = str.indexOf(a, i + 1);
  13457. } else if (begs.length == 1) {
  13458. result = [ begs.pop(), bi ];
  13459. } else {
  13460. beg = begs.pop();
  13461. if (beg < left) {
  13462. left = beg;
  13463. right = bi;
  13464. }
  13465. bi = str.indexOf(b, i + 1);
  13466. }
  13467. i = ai < bi && ai >= 0 ? ai : bi;
  13468. }
  13469. if (begs.length) {
  13470. result = [ left, right ];
  13471. }
  13472. }
  13473. return result;
  13474. }
  13475. var balanced = balancedMatch;
  13476. var braceExpansion = expandTop;
  13477. var escSlash = '\0SLASH'+Math.random()+'\0';
  13478. var escOpen = '\0OPEN'+Math.random()+'\0';
  13479. var escClose = '\0CLOSE'+Math.random()+'\0';
  13480. var escComma = '\0COMMA'+Math.random()+'\0';
  13481. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  13482. function numeric(str) {
  13483. return parseInt(str, 10) == str
  13484. ? parseInt(str, 10)
  13485. : str.charCodeAt(0);
  13486. }
  13487. function escapeBraces(str) {
  13488. return str.split('\\\\').join(escSlash)
  13489. .split('\\{').join(escOpen)
  13490. .split('\\}').join(escClose)
  13491. .split('\\,').join(escComma)
  13492. .split('\\.').join(escPeriod);
  13493. }
  13494. function unescapeBraces(str) {
  13495. return str.split(escSlash).join('\\')
  13496. .split(escOpen).join('{')
  13497. .split(escClose).join('}')
  13498. .split(escComma).join(',')
  13499. .split(escPeriod).join('.');
  13500. }
  13501. // Basically just str.split(","), but handling cases
  13502. // where we have nested braced sections, which should be
  13503. // treated as individual members, like {a,{b,c},d}
  13504. function parseCommaParts(str) {
  13505. if (!str)
  13506. return [''];
  13507. var parts = [];
  13508. var m = balanced('{', '}', str);
  13509. if (!m)
  13510. return str.split(',');
  13511. var pre = m.pre;
  13512. var body = m.body;
  13513. var post = m.post;
  13514. var p = pre.split(',');
  13515. p[p.length-1] += '{' + body + '}';
  13516. var postParts = parseCommaParts(post);
  13517. if (post.length) {
  13518. p[p.length-1] += postParts.shift();
  13519. p.push.apply(p, postParts);
  13520. }
  13521. parts.push.apply(parts, p);
  13522. return parts;
  13523. }
  13524. function expandTop(str) {
  13525. if (!str)
  13526. return [];
  13527. // I don't know why Bash 4.3 does this, but it does.
  13528. // Anything starting with {} will have the first two bytes preserved
  13529. // but *only* at the top level, so {},a}b will not expand to anything,
  13530. // but a{},b}c will be expanded to [a}c,abc].
  13531. // One could argue that this is a bug in Bash, but since the goal of
  13532. // this module is to match Bash's rules, we escape a leading {}
  13533. if (str.substr(0, 2) === '{}') {
  13534. str = '\\{\\}' + str.substr(2);
  13535. }
  13536. return expand(escapeBraces(str), true).map(unescapeBraces);
  13537. }
  13538. function embrace(str) {
  13539. return '{' + str + '}';
  13540. }
  13541. function isPadded(el) {
  13542. return /^-?0\d/.test(el);
  13543. }
  13544. function lte(i, y) {
  13545. return i <= y;
  13546. }
  13547. function gte(i, y) {
  13548. return i >= y;
  13549. }
  13550. function expand(str, isTop) {
  13551. var expansions = [];
  13552. var m = balanced('{', '}', str);
  13553. if (!m) return [str];
  13554. // no need to expand pre, since it is guaranteed to be free of brace-sets
  13555. var pre = m.pre;
  13556. var post = m.post.length
  13557. ? expand(m.post, false)
  13558. : [''];
  13559. if (/\$$/.test(m.pre)) {
  13560. for (var k = 0; k < post.length; k++) {
  13561. var expansion = pre+ '{' + m.body + '}' + post[k];
  13562. expansions.push(expansion);
  13563. }
  13564. } else {
  13565. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  13566. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  13567. var isSequence = isNumericSequence || isAlphaSequence;
  13568. var isOptions = m.body.indexOf(',') >= 0;
  13569. if (!isSequence && !isOptions) {
  13570. // {a},b}
  13571. if (m.post.match(/,.*\}/)) {
  13572. str = m.pre + '{' + m.body + escClose + m.post;
  13573. return expand(str);
  13574. }
  13575. return [str];
  13576. }
  13577. var n;
  13578. if (isSequence) {
  13579. n = m.body.split(/\.\./);
  13580. } else {
  13581. n = parseCommaParts(m.body);
  13582. if (n.length === 1) {
  13583. // x{{a,b}}y ==> x{a}y x{b}y
  13584. n = expand(n[0], false).map(embrace);
  13585. if (n.length === 1) {
  13586. return post.map(function(p) {
  13587. return m.pre + n[0] + p;
  13588. });
  13589. }
  13590. }
  13591. }
  13592. // at this point, n is the parts, and we know it's not a comma set
  13593. // with a single entry.
  13594. var N;
  13595. if (isSequence) {
  13596. var x = numeric(n[0]);
  13597. var y = numeric(n[1]);
  13598. var width = Math.max(n[0].length, n[1].length);
  13599. var incr = n.length == 3
  13600. ? Math.abs(numeric(n[2]))
  13601. : 1;
  13602. var test = lte;
  13603. var reverse = y < x;
  13604. if (reverse) {
  13605. incr *= -1;
  13606. test = gte;
  13607. }
  13608. var pad = n.some(isPadded);
  13609. N = [];
  13610. for (var i = x; test(i, y); i += incr) {
  13611. var c;
  13612. if (isAlphaSequence) {
  13613. c = String.fromCharCode(i);
  13614. if (c === '\\')
  13615. c = '';
  13616. } else {
  13617. c = String(i);
  13618. if (pad) {
  13619. var need = width - c.length;
  13620. if (need > 0) {
  13621. var z = new Array(need + 1).join('0');
  13622. if (i < 0)
  13623. c = '-' + z + c.slice(1);
  13624. else
  13625. c = z + c;
  13626. }
  13627. }
  13628. }
  13629. N.push(c);
  13630. }
  13631. } else {
  13632. N = [];
  13633. for (var j = 0; j < n.length; j++) {
  13634. N.push.apply(N, expand(n[j], false));
  13635. }
  13636. }
  13637. for (var j = 0; j < N.length; j++) {
  13638. for (var k = 0; k < post.length; k++) {
  13639. var expansion = pre + N[j] + post[k];
  13640. if (!isTop || isSequence || expansion)
  13641. expansions.push(expansion);
  13642. }
  13643. }
  13644. }
  13645. return expansions;
  13646. }
  13647. var expand$1 = braceExpansion;
  13648. const MAX_PATTERN_LENGTH = 1024 * 64;
  13649. const assertValidPattern = (pattern) => {
  13650. if (typeof pattern !== 'string') {
  13651. throw new TypeError('invalid pattern');
  13652. }
  13653. if (pattern.length > MAX_PATTERN_LENGTH) {
  13654. throw new TypeError('pattern is too long');
  13655. }
  13656. };
  13657. // translate the various posix character classes into unicode properties
  13658. // this works across all unicode locales
  13659. // { <posix class>: [<translation>, /u flag required, negated]
  13660. const posixClasses = {
  13661. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  13662. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  13663. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  13664. '[:blank:]': ['\\p{Zs}\\t', true],
  13665. '[:cntrl:]': ['\\p{Cc}', true],
  13666. '[:digit:]': ['\\p{Nd}', true],
  13667. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  13668. '[:lower:]': ['\\p{Ll}', true],
  13669. '[:print:]': ['\\p{C}', true],
  13670. '[:punct:]': ['\\p{P}', true],
  13671. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  13672. '[:upper:]': ['\\p{Lu}', true],
  13673. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  13674. '[:xdigit:]': ['A-Fa-f0-9', false],
  13675. };
  13676. // only need to escape a few things inside of brace expressions
  13677. // escapes: [ \ ] -
  13678. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  13679. // escape all regexp magic characters
  13680. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  13681. // everything has already been escaped, we just have to join
  13682. const rangesToString = (ranges) => ranges.join('');
  13683. // takes a glob string at a posix brace expression, and returns
  13684. // an equivalent regular expression source, and boolean indicating
  13685. // whether the /u flag needs to be applied, and the number of chars
  13686. // consumed to parse the character class.
  13687. // This also removes out of order ranges, and returns ($.) if the
  13688. // entire class just no good.
  13689. const parseClass = (glob, position) => {
  13690. const pos = position;
  13691. /* c8 ignore start */
  13692. if (glob.charAt(pos) !== '[') {
  13693. throw new Error('not in a brace expression');
  13694. }
  13695. /* c8 ignore stop */
  13696. const ranges = [];
  13697. const negs = [];
  13698. let i = pos + 1;
  13699. let sawStart = false;
  13700. let uflag = false;
  13701. let escaping = false;
  13702. let negate = false;
  13703. let endPos = pos;
  13704. let rangeStart = '';
  13705. WHILE: while (i < glob.length) {
  13706. const c = glob.charAt(i);
  13707. if ((c === '!' || c === '^') && i === pos + 1) {
  13708. negate = true;
  13709. i++;
  13710. continue;
  13711. }
  13712. if (c === ']' && sawStart && !escaping) {
  13713. endPos = i + 1;
  13714. break;
  13715. }
  13716. sawStart = true;
  13717. if (c === '\\') {
  13718. if (!escaping) {
  13719. escaping = true;
  13720. i++;
  13721. continue;
  13722. }
  13723. // escaped \ char, fall through and treat like normal char
  13724. }
  13725. if (c === '[' && !escaping) {
  13726. // either a posix class, a collation equivalent, or just a [
  13727. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  13728. if (glob.startsWith(cls, i)) {
  13729. // invalid, [a-[] is fine, but not [a-[:alpha]]
  13730. if (rangeStart) {
  13731. return ['$.', false, glob.length - pos, true];
  13732. }
  13733. i += cls.length;
  13734. if (neg)
  13735. negs.push(unip);
  13736. else
  13737. ranges.push(unip);
  13738. uflag = uflag || u;
  13739. continue WHILE;
  13740. }
  13741. }
  13742. }
  13743. // now it's just a normal character, effectively
  13744. escaping = false;
  13745. if (rangeStart) {
  13746. // throw this range away if it's not valid, but others
  13747. // can still match.
  13748. if (c > rangeStart) {
  13749. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  13750. }
  13751. else if (c === rangeStart) {
  13752. ranges.push(braceEscape(c));
  13753. }
  13754. rangeStart = '';
  13755. i++;
  13756. continue;
  13757. }
  13758. // now might be the start of a range.
  13759. // can be either c-d or c-] or c<more...>] or c] at this point
  13760. if (glob.startsWith('-]', i + 1)) {
  13761. ranges.push(braceEscape(c + '-'));
  13762. i += 2;
  13763. continue;
  13764. }
  13765. if (glob.startsWith('-', i + 1)) {
  13766. rangeStart = c;
  13767. i += 2;
  13768. continue;
  13769. }
  13770. // not the start of a range, just a single character
  13771. ranges.push(braceEscape(c));
  13772. i++;
  13773. }
  13774. if (endPos < i) {
  13775. // didn't see the end of the class, not a valid class,
  13776. // but might still be valid as a literal match.
  13777. return ['', false, 0, false];
  13778. }
  13779. // if we got no ranges and no negates, then we have a range that
  13780. // cannot possibly match anything, and that poisons the whole glob
  13781. if (!ranges.length && !negs.length) {
  13782. return ['$.', false, glob.length - pos, true];
  13783. }
  13784. // if we got one positive range, and it's a single character, then that's
  13785. // not actually a magic pattern, it's just that one literal character.
  13786. // we should not treat that as "magic", we should just return the literal
  13787. // character. [_] is a perfectly valid way to escape glob magic chars.
  13788. if (negs.length === 0 &&
  13789. ranges.length === 1 &&
  13790. /^\\?.$/.test(ranges[0]) &&
  13791. !negate) {
  13792. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  13793. return [regexpEscape(r), false, endPos - pos, false];
  13794. }
  13795. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  13796. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  13797. const comb = ranges.length && negs.length
  13798. ? '(' + sranges + '|' + snegs + ')'
  13799. : ranges.length
  13800. ? sranges
  13801. : snegs;
  13802. return [comb, uflag, endPos - pos, true];
  13803. };
  13804. /**
  13805. * Un-escape a string that has been escaped with {@link escape}.
  13806. *
  13807. * If the {@link windowsPathsNoEscape} option is used, then square-brace
  13808. * escapes are removed, but not backslash escapes. For example, it will turn
  13809. * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
  13810. * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
  13811. *
  13812. * When `windowsPathsNoEscape` is not set, then both brace escapes and
  13813. * backslash escapes are removed.
  13814. *
  13815. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  13816. * or unescaped.
  13817. */
  13818. const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
  13819. return windowsPathsNoEscape
  13820. ? s.replace(/\[([^\/\\])\]/g, '$1')
  13821. : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
  13822. };
  13823. // parse a single path portion
  13824. const types = new Set(['!', '?', '+', '*', '@']);
  13825. const isExtglobType = (c) => types.has(c);
  13826. // Patterns that get prepended to bind to the start of either the
  13827. // entire string, or just a single path portion, to prevent dots
  13828. // and/or traversal patterns, when needed.
  13829. // Exts don't need the ^ or / bit, because the root binds that already.
  13830. const startNoTraversal = '(?!\\.\\.?(?:$|/))';
  13831. const startNoDot = '(?!\\.)';
  13832. // characters that indicate a start of pattern needs the "no dots" bit,
  13833. // because a dot *might* be matched. ( is not in the list, because in
  13834. // the case of a child extglob, it will handle the prevention itself.
  13835. const addPatternStart = new Set(['[', '.']);
  13836. // cases where traversal is A-OK, no dot prevention needed
  13837. const justDots = new Set(['..', '.']);
  13838. const reSpecials = new Set('().*{}+?[]^$\\!');
  13839. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  13840. // any single thing other than /
  13841. const qmark$1 = '[^/]';
  13842. // * => any number of characters
  13843. const star$1 = qmark$1 + '*?';
  13844. // use + when we need to ensure that *something* matches, because the * is
  13845. // the only thing in the path portion.
  13846. const starNoEmpty = qmark$1 + '+?';
  13847. // remove the \ chars that we added if we end up doing a nonmagic compare
  13848. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  13849. class AST {
  13850. type;
  13851. #root;
  13852. #hasMagic;
  13853. #uflag = false;
  13854. #parts = [];
  13855. #parent;
  13856. #parentIndex;
  13857. #negs;
  13858. #filledNegs = false;
  13859. #options;
  13860. #toString;
  13861. // set to true if it's an extglob with no children
  13862. // (which really means one child of '')
  13863. #emptyExt = false;
  13864. constructor(type, parent, options = {}) {
  13865. this.type = type;
  13866. // extglobs are inherently magical
  13867. if (type)
  13868. this.#hasMagic = true;
  13869. this.#parent = parent;
  13870. this.#root = this.#parent ? this.#parent.#root : this;
  13871. this.#options = this.#root === this ? options : this.#root.#options;
  13872. this.#negs = this.#root === this ? [] : this.#root.#negs;
  13873. if (type === '!' && !this.#root.#filledNegs)
  13874. this.#negs.push(this);
  13875. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  13876. }
  13877. get hasMagic() {
  13878. /* c8 ignore start */
  13879. if (this.#hasMagic !== undefined)
  13880. return this.#hasMagic;
  13881. /* c8 ignore stop */
  13882. for (const p of this.#parts) {
  13883. if (typeof p === 'string')
  13884. continue;
  13885. if (p.type || p.hasMagic)
  13886. return (this.#hasMagic = true);
  13887. }
  13888. // note: will be undefined until we generate the regexp src and find out
  13889. return this.#hasMagic;
  13890. }
  13891. // reconstructs the pattern
  13892. toString() {
  13893. if (this.#toString !== undefined)
  13894. return this.#toString;
  13895. if (!this.type) {
  13896. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  13897. }
  13898. else {
  13899. return (this.#toString =
  13900. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  13901. }
  13902. }
  13903. #fillNegs() {
  13904. /* c8 ignore start */
  13905. if (this !== this.#root)
  13906. throw new Error('should only call on root');
  13907. if (this.#filledNegs)
  13908. return this;
  13909. /* c8 ignore stop */
  13910. // call toString() once to fill this out
  13911. this.toString();
  13912. this.#filledNegs = true;
  13913. let n;
  13914. while ((n = this.#negs.pop())) {
  13915. if (n.type !== '!')
  13916. continue;
  13917. // walk up the tree, appending everthing that comes AFTER parentIndex
  13918. let p = n;
  13919. let pp = p.#parent;
  13920. while (pp) {
  13921. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  13922. for (const part of n.#parts) {
  13923. /* c8 ignore start */
  13924. if (typeof part === 'string') {
  13925. throw new Error('string part in extglob AST??');
  13926. }
  13927. /* c8 ignore stop */
  13928. part.copyIn(pp.#parts[i]);
  13929. }
  13930. }
  13931. p = pp;
  13932. pp = p.#parent;
  13933. }
  13934. }
  13935. return this;
  13936. }
  13937. push(...parts) {
  13938. for (const p of parts) {
  13939. if (p === '')
  13940. continue;
  13941. /* c8 ignore start */
  13942. if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
  13943. throw new Error('invalid part: ' + p);
  13944. }
  13945. /* c8 ignore stop */
  13946. this.#parts.push(p);
  13947. }
  13948. }
  13949. toJSON() {
  13950. const ret = this.type === null
  13951. ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
  13952. : [this.type, ...this.#parts.map(p => p.toJSON())];
  13953. if (this.isStart() && !this.type)
  13954. ret.unshift([]);
  13955. if (this.isEnd() &&
  13956. (this === this.#root ||
  13957. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  13958. ret.push({});
  13959. }
  13960. return ret;
  13961. }
  13962. isStart() {
  13963. if (this.#root === this)
  13964. return true;
  13965. // if (this.type) return !!this.#parent?.isStart()
  13966. if (!this.#parent?.isStart())
  13967. return false;
  13968. if (this.#parentIndex === 0)
  13969. return true;
  13970. // if everything AHEAD of this is a negation, then it's still the "start"
  13971. const p = this.#parent;
  13972. for (let i = 0; i < this.#parentIndex; i++) {
  13973. const pp = p.#parts[i];
  13974. if (!(pp instanceof AST && pp.type === '!')) {
  13975. return false;
  13976. }
  13977. }
  13978. return true;
  13979. }
  13980. isEnd() {
  13981. if (this.#root === this)
  13982. return true;
  13983. if (this.#parent?.type === '!')
  13984. return true;
  13985. if (!this.#parent?.isEnd())
  13986. return false;
  13987. if (!this.type)
  13988. return this.#parent?.isEnd();
  13989. // if not root, it'll always have a parent
  13990. /* c8 ignore start */
  13991. const pl = this.#parent ? this.#parent.#parts.length : 0;
  13992. /* c8 ignore stop */
  13993. return this.#parentIndex === pl - 1;
  13994. }
  13995. copyIn(part) {
  13996. if (typeof part === 'string')
  13997. this.push(part);
  13998. else
  13999. this.push(part.clone(this));
  14000. }
  14001. clone(parent) {
  14002. const c = new AST(this.type, parent);
  14003. for (const p of this.#parts) {
  14004. c.copyIn(p);
  14005. }
  14006. return c;
  14007. }
  14008. static #parseAST(str, ast, pos, opt) {
  14009. let escaping = false;
  14010. let inBrace = false;
  14011. let braceStart = -1;
  14012. let braceNeg = false;
  14013. if (ast.type === null) {
  14014. // outside of a extglob, append until we find a start
  14015. let i = pos;
  14016. let acc = '';
  14017. while (i < str.length) {
  14018. const c = str.charAt(i++);
  14019. // still accumulate escapes at this point, but we do ignore
  14020. // starts that are escaped
  14021. if (escaping || c === '\\') {
  14022. escaping = !escaping;
  14023. acc += c;
  14024. continue;
  14025. }
  14026. if (inBrace) {
  14027. if (i === braceStart + 1) {
  14028. if (c === '^' || c === '!') {
  14029. braceNeg = true;
  14030. }
  14031. }
  14032. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  14033. inBrace = false;
  14034. }
  14035. acc += c;
  14036. continue;
  14037. }
  14038. else if (c === '[') {
  14039. inBrace = true;
  14040. braceStart = i;
  14041. braceNeg = false;
  14042. acc += c;
  14043. continue;
  14044. }
  14045. if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
  14046. ast.push(acc);
  14047. acc = '';
  14048. const ext = new AST(c, ast);
  14049. i = AST.#parseAST(str, ext, i, opt);
  14050. ast.push(ext);
  14051. continue;
  14052. }
  14053. acc += c;
  14054. }
  14055. ast.push(acc);
  14056. return i;
  14057. }
  14058. // some kind of extglob, pos is at the (
  14059. // find the next | or )
  14060. let i = pos + 1;
  14061. let part = new AST(null, ast);
  14062. const parts = [];
  14063. let acc = '';
  14064. while (i < str.length) {
  14065. const c = str.charAt(i++);
  14066. // still accumulate escapes at this point, but we do ignore
  14067. // starts that are escaped
  14068. if (escaping || c === '\\') {
  14069. escaping = !escaping;
  14070. acc += c;
  14071. continue;
  14072. }
  14073. if (inBrace) {
  14074. if (i === braceStart + 1) {
  14075. if (c === '^' || c === '!') {
  14076. braceNeg = true;
  14077. }
  14078. }
  14079. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  14080. inBrace = false;
  14081. }
  14082. acc += c;
  14083. continue;
  14084. }
  14085. else if (c === '[') {
  14086. inBrace = true;
  14087. braceStart = i;
  14088. braceNeg = false;
  14089. acc += c;
  14090. continue;
  14091. }
  14092. if (isExtglobType(c) && str.charAt(i) === '(') {
  14093. part.push(acc);
  14094. acc = '';
  14095. const ext = new AST(c, part);
  14096. part.push(ext);
  14097. i = AST.#parseAST(str, ext, i, opt);
  14098. continue;
  14099. }
  14100. if (c === '|') {
  14101. part.push(acc);
  14102. acc = '';
  14103. parts.push(part);
  14104. part = new AST(null, ast);
  14105. continue;
  14106. }
  14107. if (c === ')') {
  14108. if (acc === '' && ast.#parts.length === 0) {
  14109. ast.#emptyExt = true;
  14110. }
  14111. part.push(acc);
  14112. acc = '';
  14113. ast.push(...parts, part);
  14114. return i;
  14115. }
  14116. acc += c;
  14117. }
  14118. // unfinished extglob
  14119. // if we got here, it was a malformed extglob! not an extglob, but
  14120. // maybe something else in there.
  14121. ast.type = null;
  14122. ast.#hasMagic = undefined;
  14123. ast.#parts = [str.substring(pos - 1)];
  14124. return i;
  14125. }
  14126. static fromGlob(pattern, options = {}) {
  14127. const ast = new AST(null, undefined, options);
  14128. AST.#parseAST(pattern, ast, 0, options);
  14129. return ast;
  14130. }
  14131. // returns the regular expression if there's magic, or the unescaped
  14132. // string if not.
  14133. toMMPattern() {
  14134. // should only be called on root
  14135. /* c8 ignore start */
  14136. if (this !== this.#root)
  14137. return this.#root.toMMPattern();
  14138. /* c8 ignore stop */
  14139. const glob = this.toString();
  14140. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  14141. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  14142. // still need a regular expression if we have to case-insensitively
  14143. // match capital/lowercase characters.
  14144. const anyMagic = hasMagic ||
  14145. this.#hasMagic ||
  14146. (this.#options.nocase &&
  14147. !this.#options.nocaseMagicOnly &&
  14148. glob.toUpperCase() !== glob.toLowerCase());
  14149. if (!anyMagic) {
  14150. return body;
  14151. }
  14152. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  14153. return Object.assign(new RegExp(`^${re}$`, flags), {
  14154. _src: re,
  14155. _glob: glob,
  14156. });
  14157. }
  14158. // returns the string match, the regexp source, whether there's magic
  14159. // in the regexp (so a regular expression is required) and whether or
  14160. // not the uflag is needed for the regular expression (for posix classes)
  14161. // TODO: instead of injecting the start/end at this point, just return
  14162. // the BODY of the regexp, along with the start/end portions suitable
  14163. // for binding the start/end in either a joined full-path makeRe context
  14164. // (where we bind to (^|/), or a standalone matchPart context (where
  14165. // we bind to ^, and not /). Otherwise slashes get duped!
  14166. //
  14167. // In part-matching mode, the start is:
  14168. // - if not isStart: nothing
  14169. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  14170. // - if dots allowed or not possible: ^
  14171. // - if dots possible and not allowed: ^(?!\.)
  14172. // end is:
  14173. // - if not isEnd(): nothing
  14174. // - else: $
  14175. //
  14176. // In full-path matching mode, we put the slash at the START of the
  14177. // pattern, so start is:
  14178. // - if first pattern: same as part-matching mode
  14179. // - if not isStart(): nothing
  14180. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  14181. // - if dots allowed or not possible: /
  14182. // - if dots possible and not allowed: /(?!\.)
  14183. // end is:
  14184. // - if last pattern, same as part-matching mode
  14185. // - else nothing
  14186. //
  14187. // Always put the (?:$|/) on negated tails, though, because that has to be
  14188. // there to bind the end of the negated pattern portion, and it's easier to
  14189. // just stick it in now rather than try to inject it later in the middle of
  14190. // the pattern.
  14191. //
  14192. // We can just always return the same end, and leave it up to the caller
  14193. // to know whether it's going to be used joined or in parts.
  14194. // And, if the start is adjusted slightly, can do the same there:
  14195. // - if not isStart: nothing
  14196. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  14197. // - if dots allowed or not possible: (?:/|^)
  14198. // - if dots possible and not allowed: (?:/|^)(?!\.)
  14199. //
  14200. // But it's better to have a simpler binding without a conditional, for
  14201. // performance, so probably better to return both start options.
  14202. //
  14203. // Then the caller just ignores the end if it's not the first pattern,
  14204. // and the start always gets applied.
  14205. //
  14206. // But that's always going to be $ if it's the ending pattern, or nothing,
  14207. // so the caller can just attach $ at the end of the pattern when building.
  14208. //
  14209. // So the todo is:
  14210. // - better detect what kind of start is needed
  14211. // - return both flavors of starting pattern
  14212. // - attach $ at the end of the pattern when creating the actual RegExp
  14213. //
  14214. // Ah, but wait, no, that all only applies to the root when the first pattern
  14215. // is not an extglob. If the first pattern IS an extglob, then we need all
  14216. // that dot prevention biz to live in the extglob portions, because eg
  14217. // +(*|.x*) can match .xy but not .yx.
  14218. //
  14219. // So, return the two flavors if it's #root and the first child is not an
  14220. // AST, otherwise leave it to the child AST to handle it, and there,
  14221. // use the (?:^|/) style of start binding.
  14222. //
  14223. // Even simplified further:
  14224. // - Since the start for a join is eg /(?!\.) and the start for a part
  14225. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  14226. // or start or whatever) and prepend ^ or / at the Regexp construction.
  14227. toRegExpSource() {
  14228. if (this.#root === this)
  14229. this.#fillNegs();
  14230. if (!this.type) {
  14231. const noEmpty = this.isStart() && this.isEnd();
  14232. const src = this.#parts
  14233. .map(p => {
  14234. const [re, _, hasMagic, uflag] = typeof p === 'string'
  14235. ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
  14236. : p.toRegExpSource();
  14237. this.#hasMagic = this.#hasMagic || hasMagic;
  14238. this.#uflag = this.#uflag || uflag;
  14239. return re;
  14240. })
  14241. .join('');
  14242. let start = '';
  14243. if (this.isStart()) {
  14244. if (typeof this.#parts[0] === 'string') {
  14245. // this is the string that will match the start of the pattern,
  14246. // so we need to protect against dots and such.
  14247. // '.' and '..' cannot match unless the pattern is that exactly,
  14248. // even if it starts with . or dot:true is set.
  14249. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  14250. if (!dotTravAllowed) {
  14251. const aps = addPatternStart;
  14252. // check if we have a possibility of matching . or ..,
  14253. // and prevent that.
  14254. const needNoTrav =
  14255. // dots are allowed, and the pattern starts with [ or .
  14256. (this.#options.dot && aps.has(src.charAt(0))) ||
  14257. // the pattern starts with \., and then [ or .
  14258. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  14259. // the pattern starts with \.\., and then [ or .
  14260. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  14261. // no need to prevent dots if it can't match a dot, or if a
  14262. // sub-pattern will be preventing it anyway.
  14263. const needNoDot = !this.#options.dot && aps.has(src.charAt(0));
  14264. start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
  14265. }
  14266. }
  14267. }
  14268. // append the "end of path portion" pattern to negation tails
  14269. let end = '';
  14270. if (this.isEnd() &&
  14271. this.#root.#filledNegs &&
  14272. this.#parent?.type === '!') {
  14273. end = '(?:$|\\/)';
  14274. }
  14275. const final = start + src + end;
  14276. return [
  14277. final,
  14278. unescape(src),
  14279. (this.#hasMagic = !!this.#hasMagic),
  14280. this.#uflag,
  14281. ];
  14282. }
  14283. // some kind of extglob
  14284. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  14285. const body = this.#parts
  14286. .map(p => {
  14287. // extglob ASTs should only contain parent ASTs
  14288. /* c8 ignore start */
  14289. if (typeof p === 'string') {
  14290. throw new Error('string type in extglob ast??');
  14291. }
  14292. /* c8 ignore stop */
  14293. // can ignore hasMagic, because extglobs are already always magic
  14294. const [re, _, _hasMagic, uflag] = p.toRegExpSource();
  14295. this.#uflag = this.#uflag || uflag;
  14296. return re;
  14297. })
  14298. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  14299. .join('|');
  14300. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  14301. // invalid extglob, has to at least be *something* present, if it's
  14302. // the entire path portion.
  14303. const s = this.toString();
  14304. this.#parts = [s];
  14305. this.type = null;
  14306. this.#hasMagic = undefined;
  14307. return [s, unescape(this.toString()), false, false];
  14308. }
  14309. // an empty !() is exactly equivalent to a starNoEmpty
  14310. let final = '';
  14311. if (this.type === '!' && this.#emptyExt) {
  14312. final =
  14313. (this.isStart() && !this.#options.dot ? startNoDot : '') + starNoEmpty;
  14314. }
  14315. else {
  14316. const close = this.type === '!'
  14317. ? // !() must match something,but !(x) can match ''
  14318. '))' +
  14319. (this.isStart() && !this.#options.dot ? startNoDot : '') +
  14320. star$1 +
  14321. ')'
  14322. : this.type === '@'
  14323. ? ')'
  14324. : `)${this.type}`;
  14325. final = start + body + close;
  14326. }
  14327. return [
  14328. final,
  14329. unescape(body),
  14330. (this.#hasMagic = !!this.#hasMagic),
  14331. this.#uflag,
  14332. ];
  14333. }
  14334. static #parseGlob(glob, hasMagic, noEmpty = false) {
  14335. let escaping = false;
  14336. let re = '';
  14337. let uflag = false;
  14338. for (let i = 0; i < glob.length; i++) {
  14339. const c = glob.charAt(i);
  14340. if (escaping) {
  14341. escaping = false;
  14342. re += (reSpecials.has(c) ? '\\' : '') + c;
  14343. continue;
  14344. }
  14345. if (c === '\\') {
  14346. if (i === glob.length - 1) {
  14347. re += '\\\\';
  14348. }
  14349. else {
  14350. escaping = true;
  14351. }
  14352. continue;
  14353. }
  14354. if (c === '[') {
  14355. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  14356. if (consumed) {
  14357. re += src;
  14358. uflag = uflag || needUflag;
  14359. i += consumed - 1;
  14360. hasMagic = hasMagic || magic;
  14361. continue;
  14362. }
  14363. }
  14364. if (c === '*') {
  14365. if (noEmpty && glob === '*')
  14366. re += starNoEmpty;
  14367. else
  14368. re += star$1;
  14369. hasMagic = true;
  14370. continue;
  14371. }
  14372. if (c === '?') {
  14373. re += qmark$1;
  14374. hasMagic = true;
  14375. continue;
  14376. }
  14377. re += regExpEscape$1(c);
  14378. }
  14379. return [re, unescape(glob), !!hasMagic, uflag];
  14380. }
  14381. }
  14382. /**
  14383. * Escape all magic characters in a glob pattern.
  14384. *
  14385. * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
  14386. * option is used, then characters are escaped by wrapping in `[]`, because
  14387. * a magic character wrapped in a character class can only be satisfied by
  14388. * that exact character. In this mode, `\` is _not_ escaped, because it is
  14389. * not interpreted as a magic character, but instead as a path separator.
  14390. */
  14391. const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
  14392. // don't need to escape +@! because we escape the parens
  14393. // that make those magic, and escaping ! as [!] isn't valid,
  14394. // because [!]] is a valid glob class meaning not ']'.
  14395. return windowsPathsNoEscape
  14396. ? s.replace(/[?*()[\]]/g, '[$&]')
  14397. : s.replace(/[?*()[\]\\]/g, '\\$&');
  14398. };
  14399. const minimatch = (p, pattern, options = {}) => {
  14400. assertValidPattern(pattern);
  14401. // shortcut: comments match nothing.
  14402. if (!options.nocomment && pattern.charAt(0) === '#') {
  14403. return false;
  14404. }
  14405. return new Minimatch(pattern, options).match(p);
  14406. };
  14407. // Optimized checking for the most common glob patterns.
  14408. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  14409. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  14410. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  14411. const starDotExtTestNocase = (ext) => {
  14412. ext = ext.toLowerCase();
  14413. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  14414. };
  14415. const starDotExtTestNocaseDot = (ext) => {
  14416. ext = ext.toLowerCase();
  14417. return (f) => f.toLowerCase().endsWith(ext);
  14418. };
  14419. const starDotStarRE = /^\*+\.\*+$/;
  14420. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  14421. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  14422. const dotStarRE = /^\.\*+$/;
  14423. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  14424. const starRE = /^\*+$/;
  14425. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  14426. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  14427. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  14428. const qmarksTestNocase = ([$0, ext = '']) => {
  14429. const noext = qmarksTestNoExt([$0]);
  14430. if (!ext)
  14431. return noext;
  14432. ext = ext.toLowerCase();
  14433. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  14434. };
  14435. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  14436. const noext = qmarksTestNoExtDot([$0]);
  14437. if (!ext)
  14438. return noext;
  14439. ext = ext.toLowerCase();
  14440. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  14441. };
  14442. const qmarksTestDot = ([$0, ext = '']) => {
  14443. const noext = qmarksTestNoExtDot([$0]);
  14444. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  14445. };
  14446. const qmarksTest = ([$0, ext = '']) => {
  14447. const noext = qmarksTestNoExt([$0]);
  14448. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  14449. };
  14450. const qmarksTestNoExt = ([$0]) => {
  14451. const len = $0.length;
  14452. return (f) => f.length === len && !f.startsWith('.');
  14453. };
  14454. const qmarksTestNoExtDot = ([$0]) => {
  14455. const len = $0.length;
  14456. return (f) => f.length === len && f !== '.' && f !== '..';
  14457. };
  14458. /* c8 ignore start */
  14459. const defaultPlatform = (typeof process === 'object' && process
  14460. ? (typeof process.env === 'object' &&
  14461. process.env &&
  14462. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  14463. process.platform
  14464. : 'posix');
  14465. const path = {
  14466. win32: { sep: '\\' },
  14467. posix: { sep: '/' },
  14468. };
  14469. /* c8 ignore stop */
  14470. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  14471. minimatch.sep = sep;
  14472. const GLOBSTAR = Symbol('globstar **');
  14473. minimatch.GLOBSTAR = GLOBSTAR;
  14474. // any single thing other than /
  14475. // don't need to escape / when using new RegExp()
  14476. const qmark = '[^/]';
  14477. // * => any number of characters
  14478. const star = qmark + '*?';
  14479. // ** when dots are allowed. Anything goes, except .. and .
  14480. // not (^ or / followed by one or two dots followed by $ or /),
  14481. // followed by anything, any number of times.
  14482. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  14483. // not a ^ or / followed by a dot,
  14484. // followed by anything, any number of times.
  14485. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  14486. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  14487. minimatch.filter = filter;
  14488. const ext = (a, b = {}) => Object.assign({}, a, b);
  14489. const defaults = (def) => {
  14490. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  14491. return minimatch;
  14492. }
  14493. const orig = minimatch;
  14494. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  14495. return Object.assign(m, {
  14496. Minimatch: class Minimatch extends orig.Minimatch {
  14497. constructor(pattern, options = {}) {
  14498. super(pattern, ext(def, options));
  14499. }
  14500. static defaults(options) {
  14501. return orig.defaults(ext(def, options)).Minimatch;
  14502. }
  14503. },
  14504. AST: class AST extends orig.AST {
  14505. /* c8 ignore start */
  14506. constructor(type, parent, options = {}) {
  14507. super(type, parent, ext(def, options));
  14508. }
  14509. /* c8 ignore stop */
  14510. static fromGlob(pattern, options = {}) {
  14511. return orig.AST.fromGlob(pattern, ext(def, options));
  14512. }
  14513. },
  14514. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  14515. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  14516. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  14517. defaults: (options) => orig.defaults(ext(def, options)),
  14518. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  14519. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  14520. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  14521. sep: orig.sep,
  14522. GLOBSTAR: GLOBSTAR,
  14523. });
  14524. };
  14525. minimatch.defaults = defaults;
  14526. // Brace expansion:
  14527. // a{b,c}d -> abd acd
  14528. // a{b,}c -> abc ac
  14529. // a{0..3}d -> a0d a1d a2d a3d
  14530. // a{b,c{d,e}f}g -> abg acdfg acefg
  14531. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  14532. //
  14533. // Invalid sets are not expanded.
  14534. // a{2..}b -> a{2..}b
  14535. // a{b}c -> a{b}c
  14536. const braceExpand = (pattern, options = {}) => {
  14537. assertValidPattern(pattern);
  14538. // Thanks to Yeting Li <https://github.com/yetingli> for
  14539. // improving this regexp to avoid a ReDOS vulnerability.
  14540. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  14541. // shortcut. no need to expand.
  14542. return [pattern];
  14543. }
  14544. return expand$1(pattern);
  14545. };
  14546. minimatch.braceExpand = braceExpand;
  14547. // parse a component of the expanded set.
  14548. // At this point, no pattern may contain "/" in it
  14549. // so we're going to return a 2d array, where each entry is the full
  14550. // pattern, split on '/', and then turned into a regular expression.
  14551. // A regexp is made at the end which joins each array with an
  14552. // escaped /, and another full one which joins each regexp with |.
  14553. //
  14554. // Following the lead of Bash 4.1, note that "**" only has special meaning
  14555. // when it is the *only* thing in a path portion. Otherwise, any series
  14556. // of * is equivalent to a single *. Globstar behavior is enabled by
  14557. // default, and can be disabled by setting options.noglobstar.
  14558. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  14559. minimatch.makeRe = makeRe;
  14560. const match = (list, pattern, options = {}) => {
  14561. const mm = new Minimatch(pattern, options);
  14562. list = list.filter(f => mm.match(f));
  14563. if (mm.options.nonull && !list.length) {
  14564. list.push(pattern);
  14565. }
  14566. return list;
  14567. };
  14568. minimatch.match = match;
  14569. // replace stuff like \* with *
  14570. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  14571. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  14572. class Minimatch {
  14573. options;
  14574. set;
  14575. pattern;
  14576. windowsPathsNoEscape;
  14577. nonegate;
  14578. negate;
  14579. comment;
  14580. empty;
  14581. preserveMultipleSlashes;
  14582. partial;
  14583. globSet;
  14584. globParts;
  14585. nocase;
  14586. isWindows;
  14587. platform;
  14588. windowsNoMagicRoot;
  14589. regexp;
  14590. constructor(pattern, options = {}) {
  14591. assertValidPattern(pattern);
  14592. options = options || {};
  14593. this.options = options;
  14594. this.pattern = pattern;
  14595. this.platform = options.platform || defaultPlatform;
  14596. this.isWindows = this.platform === 'win32';
  14597. this.windowsPathsNoEscape =
  14598. !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  14599. if (this.windowsPathsNoEscape) {
  14600. this.pattern = this.pattern.replace(/\\/g, '/');
  14601. }
  14602. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  14603. this.regexp = null;
  14604. this.negate = false;
  14605. this.nonegate = !!options.nonegate;
  14606. this.comment = false;
  14607. this.empty = false;
  14608. this.partial = !!options.partial;
  14609. this.nocase = !!this.options.nocase;
  14610. this.windowsNoMagicRoot =
  14611. options.windowsNoMagicRoot !== undefined
  14612. ? options.windowsNoMagicRoot
  14613. : !!(this.isWindows && this.nocase);
  14614. this.globSet = [];
  14615. this.globParts = [];
  14616. this.set = [];
  14617. // make the set of regexps etc.
  14618. this.make();
  14619. }
  14620. hasMagic() {
  14621. if (this.options.magicalBraces && this.set.length > 1) {
  14622. return true;
  14623. }
  14624. for (const pattern of this.set) {
  14625. for (const part of pattern) {
  14626. if (typeof part !== 'string')
  14627. return true;
  14628. }
  14629. }
  14630. return false;
  14631. }
  14632. debug(..._) { }
  14633. make() {
  14634. const pattern = this.pattern;
  14635. const options = this.options;
  14636. // empty patterns and comments match nothing.
  14637. if (!options.nocomment && pattern.charAt(0) === '#') {
  14638. this.comment = true;
  14639. return;
  14640. }
  14641. if (!pattern) {
  14642. this.empty = true;
  14643. return;
  14644. }
  14645. // step 1: figure out negation, etc.
  14646. this.parseNegate();
  14647. // step 2: expand braces
  14648. this.globSet = [...new Set(this.braceExpand())];
  14649. if (options.debug) {
  14650. this.debug = (...args) => console.error(...args);
  14651. }
  14652. this.debug(this.pattern, this.globSet);
  14653. // step 3: now we have a set, so turn each one into a series of
  14654. // path-portion matching patterns.
  14655. // These will be regexps, except in the case of "**", which is
  14656. // set to the GLOBSTAR object for globstar behavior,
  14657. // and will not contain any / characters
  14658. //
  14659. // First, we preprocess to make the glob pattern sets a bit simpler
  14660. // and deduped. There are some perf-killing patterns that can cause
  14661. // problems with a glob walk, but we can simplify them down a bit.
  14662. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  14663. this.globParts = this.preprocess(rawGlobParts);
  14664. this.debug(this.pattern, this.globParts);
  14665. // glob --> regexps
  14666. let set = this.globParts.map((s, _, __) => {
  14667. if (this.isWindows && this.windowsNoMagicRoot) {
  14668. // check if it's a drive or unc path.
  14669. const isUNC = s[0] === '' &&
  14670. s[1] === '' &&
  14671. (s[2] === '?' || !globMagic.test(s[2])) &&
  14672. !globMagic.test(s[3]);
  14673. const isDrive = /^[a-z]:/i.test(s[0]);
  14674. if (isUNC) {
  14675. return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
  14676. }
  14677. else if (isDrive) {
  14678. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  14679. }
  14680. }
  14681. return s.map(ss => this.parse(ss));
  14682. });
  14683. this.debug(this.pattern, set);
  14684. // filter out everything that didn't compile properly.
  14685. this.set = set.filter(s => s.indexOf(false) === -1);
  14686. // do not treat the ? in UNC paths as magic
  14687. if (this.isWindows) {
  14688. for (let i = 0; i < this.set.length; i++) {
  14689. const p = this.set[i];
  14690. if (p[0] === '' &&
  14691. p[1] === '' &&
  14692. this.globParts[i][2] === '?' &&
  14693. typeof p[3] === 'string' &&
  14694. /^[a-z]:$/i.test(p[3])) {
  14695. p[2] = '?';
  14696. }
  14697. }
  14698. }
  14699. this.debug(this.pattern, this.set);
  14700. }
  14701. // various transforms to equivalent pattern sets that are
  14702. // faster to process in a filesystem walk. The goal is to
  14703. // eliminate what we can, and push all ** patterns as far
  14704. // to the right as possible, even if it increases the number
  14705. // of patterns that we have to process.
  14706. preprocess(globParts) {
  14707. // if we're not in globstar mode, then turn all ** into *
  14708. if (this.options.noglobstar) {
  14709. for (let i = 0; i < globParts.length; i++) {
  14710. for (let j = 0; j < globParts[i].length; j++) {
  14711. if (globParts[i][j] === '**') {
  14712. globParts[i][j] = '*';
  14713. }
  14714. }
  14715. }
  14716. }
  14717. const { optimizationLevel = 1 } = this.options;
  14718. if (optimizationLevel >= 2) {
  14719. // aggressive optimization for the purpose of fs walking
  14720. globParts = this.firstPhasePreProcess(globParts);
  14721. globParts = this.secondPhasePreProcess(globParts);
  14722. }
  14723. else if (optimizationLevel >= 1) {
  14724. // just basic optimizations to remove some .. parts
  14725. globParts = this.levelOneOptimize(globParts);
  14726. }
  14727. else {
  14728. globParts = this.adjascentGlobstarOptimize(globParts);
  14729. }
  14730. return globParts;
  14731. }
  14732. // just get rid of adjascent ** portions
  14733. adjascentGlobstarOptimize(globParts) {
  14734. return globParts.map(parts => {
  14735. let gs = -1;
  14736. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  14737. let i = gs;
  14738. while (parts[i + 1] === '**') {
  14739. i++;
  14740. }
  14741. if (i !== gs) {
  14742. parts.splice(gs, i - gs);
  14743. }
  14744. }
  14745. return parts;
  14746. });
  14747. }
  14748. // get rid of adjascent ** and resolve .. portions
  14749. levelOneOptimize(globParts) {
  14750. return globParts.map(parts => {
  14751. parts = parts.reduce((set, part) => {
  14752. const prev = set[set.length - 1];
  14753. if (part === '**' && prev === '**') {
  14754. return set;
  14755. }
  14756. if (part === '..') {
  14757. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  14758. set.pop();
  14759. return set;
  14760. }
  14761. }
  14762. set.push(part);
  14763. return set;
  14764. }, []);
  14765. return parts.length === 0 ? [''] : parts;
  14766. });
  14767. }
  14768. levelTwoFileOptimize(parts) {
  14769. if (!Array.isArray(parts)) {
  14770. parts = this.slashSplit(parts);
  14771. }
  14772. let didSomething = false;
  14773. do {
  14774. didSomething = false;
  14775. // <pre>/<e>/<rest> -> <pre>/<rest>
  14776. if (!this.preserveMultipleSlashes) {
  14777. for (let i = 1; i < parts.length - 1; i++) {
  14778. const p = parts[i];
  14779. // don't squeeze out UNC patterns
  14780. if (i === 1 && p === '' && parts[0] === '')
  14781. continue;
  14782. if (p === '.' || p === '') {
  14783. didSomething = true;
  14784. parts.splice(i, 1);
  14785. i--;
  14786. }
  14787. }
  14788. if (parts[0] === '.' &&
  14789. parts.length === 2 &&
  14790. (parts[1] === '.' || parts[1] === '')) {
  14791. didSomething = true;
  14792. parts.pop();
  14793. }
  14794. }
  14795. // <pre>/<p>/../<rest> -> <pre>/<rest>
  14796. let dd = 0;
  14797. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  14798. const p = parts[dd - 1];
  14799. if (p && p !== '.' && p !== '..' && p !== '**') {
  14800. didSomething = true;
  14801. parts.splice(dd - 1, 2);
  14802. dd -= 2;
  14803. }
  14804. }
  14805. } while (didSomething);
  14806. return parts.length === 0 ? [''] : parts;
  14807. }
  14808. // First phase: single-pattern processing
  14809. // <pre> is 1 or more portions
  14810. // <rest> is 1 or more portions
  14811. // <p> is any portion other than ., .., '', or **
  14812. // <e> is . or ''
  14813. //
  14814. // **/.. is *brutal* for filesystem walking performance, because
  14815. // it effectively resets the recursive walk each time it occurs,
  14816. // and ** cannot be reduced out by a .. pattern part like a regexp
  14817. // or most strings (other than .., ., and '') can be.
  14818. //
  14819. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  14820. // <pre>/<e>/<rest> -> <pre>/<rest>
  14821. // <pre>/<p>/../<rest> -> <pre>/<rest>
  14822. // **/**/<rest> -> **/<rest>
  14823. //
  14824. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  14825. // this WOULD be allowed if ** did follow symlinks, or * didn't
  14826. firstPhasePreProcess(globParts) {
  14827. let didSomething = false;
  14828. do {
  14829. didSomething = false;
  14830. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  14831. for (let parts of globParts) {
  14832. let gs = -1;
  14833. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  14834. let gss = gs;
  14835. while (parts[gss + 1] === '**') {
  14836. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  14837. gss++;
  14838. }
  14839. // eg, if gs is 2 and gss is 4, that means we have 3 **
  14840. // parts, and can remove 2 of them.
  14841. if (gss > gs) {
  14842. parts.splice(gs + 1, gss - gs);
  14843. }
  14844. let next = parts[gs + 1];
  14845. const p = parts[gs + 2];
  14846. const p2 = parts[gs + 3];
  14847. if (next !== '..')
  14848. continue;
  14849. if (!p ||
  14850. p === '.' ||
  14851. p === '..' ||
  14852. !p2 ||
  14853. p2 === '.' ||
  14854. p2 === '..') {
  14855. continue;
  14856. }
  14857. didSomething = true;
  14858. // edit parts in place, and push the new one
  14859. parts.splice(gs, 1);
  14860. const other = parts.slice(0);
  14861. other[gs] = '**';
  14862. globParts.push(other);
  14863. gs--;
  14864. }
  14865. // <pre>/<e>/<rest> -> <pre>/<rest>
  14866. if (!this.preserveMultipleSlashes) {
  14867. for (let i = 1; i < parts.length - 1; i++) {
  14868. const p = parts[i];
  14869. // don't squeeze out UNC patterns
  14870. if (i === 1 && p === '' && parts[0] === '')
  14871. continue;
  14872. if (p === '.' || p === '') {
  14873. didSomething = true;
  14874. parts.splice(i, 1);
  14875. i--;
  14876. }
  14877. }
  14878. if (parts[0] === '.' &&
  14879. parts.length === 2 &&
  14880. (parts[1] === '.' || parts[1] === '')) {
  14881. didSomething = true;
  14882. parts.pop();
  14883. }
  14884. }
  14885. // <pre>/<p>/../<rest> -> <pre>/<rest>
  14886. let dd = 0;
  14887. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  14888. const p = parts[dd - 1];
  14889. if (p && p !== '.' && p !== '..' && p !== '**') {
  14890. didSomething = true;
  14891. const needDot = dd === 1 && parts[dd + 1] === '**';
  14892. const splin = needDot ? ['.'] : [];
  14893. parts.splice(dd - 1, 2, ...splin);
  14894. if (parts.length === 0)
  14895. parts.push('');
  14896. dd -= 2;
  14897. }
  14898. }
  14899. }
  14900. } while (didSomething);
  14901. return globParts;
  14902. }
  14903. // second phase: multi-pattern dedupes
  14904. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  14905. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  14906. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  14907. //
  14908. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  14909. // ^-- not valid because ** doens't follow symlinks
  14910. secondPhasePreProcess(globParts) {
  14911. for (let i = 0; i < globParts.length - 1; i++) {
  14912. for (let j = i + 1; j < globParts.length; j++) {
  14913. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  14914. if (!matched)
  14915. continue;
  14916. globParts[i] = matched;
  14917. globParts[j] = [];
  14918. }
  14919. }
  14920. return globParts.filter(gs => gs.length);
  14921. }
  14922. partsMatch(a, b, emptyGSMatch = false) {
  14923. let ai = 0;
  14924. let bi = 0;
  14925. let result = [];
  14926. let which = '';
  14927. while (ai < a.length && bi < b.length) {
  14928. if (a[ai] === b[bi]) {
  14929. result.push(which === 'b' ? b[bi] : a[ai]);
  14930. ai++;
  14931. bi++;
  14932. }
  14933. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  14934. result.push(a[ai]);
  14935. ai++;
  14936. }
  14937. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  14938. result.push(b[bi]);
  14939. bi++;
  14940. }
  14941. else if (a[ai] === '*' &&
  14942. b[bi] &&
  14943. (this.options.dot || !b[bi].startsWith('.')) &&
  14944. b[bi] !== '**') {
  14945. if (which === 'b')
  14946. return false;
  14947. which = 'a';
  14948. result.push(a[ai]);
  14949. ai++;
  14950. bi++;
  14951. }
  14952. else if (b[bi] === '*' &&
  14953. a[ai] &&
  14954. (this.options.dot || !a[ai].startsWith('.')) &&
  14955. a[ai] !== '**') {
  14956. if (which === 'a')
  14957. return false;
  14958. which = 'b';
  14959. result.push(b[bi]);
  14960. ai++;
  14961. bi++;
  14962. }
  14963. else {
  14964. return false;
  14965. }
  14966. }
  14967. // if we fall out of the loop, it means they two are identical
  14968. // as long as their lengths match
  14969. return a.length === b.length && result;
  14970. }
  14971. parseNegate() {
  14972. if (this.nonegate)
  14973. return;
  14974. const pattern = this.pattern;
  14975. let negate = false;
  14976. let negateOffset = 0;
  14977. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  14978. negate = !negate;
  14979. negateOffset++;
  14980. }
  14981. if (negateOffset)
  14982. this.pattern = pattern.slice(negateOffset);
  14983. this.negate = negate;
  14984. }
  14985. // set partial to true to test if, for example,
  14986. // "/a/b" matches the start of "/*/b/*/d"
  14987. // Partial means, if you run out of file before you run
  14988. // out of pattern, then that's fine, as long as all
  14989. // the parts match.
  14990. matchOne(file, pattern, partial = false) {
  14991. const options = this.options;
  14992. // a UNC pattern like //?/c:/* can match a path like c:/x
  14993. // and vice versa
  14994. if (this.isWindows) {
  14995. const fileUNC = file[0] === '' &&
  14996. file[1] === '' &&
  14997. file[2] === '?' &&
  14998. typeof file[3] === 'string' &&
  14999. /^[a-z]:$/i.test(file[3]);
  15000. const patternUNC = pattern[0] === '' &&
  15001. pattern[1] === '' &&
  15002. pattern[2] === '?' &&
  15003. typeof pattern[3] === 'string' &&
  15004. /^[a-z]:$/i.test(pattern[3]);
  15005. if (fileUNC && patternUNC) {
  15006. const fd = file[3];
  15007. const pd = pattern[3];
  15008. if (fd.toLowerCase() === pd.toLowerCase()) {
  15009. file[3] = pd;
  15010. }
  15011. }
  15012. else if (patternUNC && typeof file[0] === 'string') {
  15013. const pd = pattern[3];
  15014. const fd = file[0];
  15015. if (pd.toLowerCase() === fd.toLowerCase()) {
  15016. pattern[3] = fd;
  15017. pattern = pattern.slice(3);
  15018. }
  15019. }
  15020. else if (fileUNC && typeof pattern[0] === 'string') {
  15021. const fd = file[3];
  15022. if (fd.toLowerCase() === pattern[0].toLowerCase()) {
  15023. pattern[0] = fd;
  15024. file = file.slice(3);
  15025. }
  15026. }
  15027. }
  15028. // resolve and reduce . and .. portions in the file as well.
  15029. // dont' need to do the second phase, because it's only one string[]
  15030. const { optimizationLevel = 1 } = this.options;
  15031. if (optimizationLevel >= 2) {
  15032. file = this.levelTwoFileOptimize(file);
  15033. }
  15034. this.debug('matchOne', this, { file, pattern });
  15035. this.debug('matchOne', file.length, pattern.length);
  15036. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  15037. this.debug('matchOne loop');
  15038. var p = pattern[pi];
  15039. var f = file[fi];
  15040. this.debug(pattern, p, f);
  15041. // should be impossible.
  15042. // some invalid regexp stuff in the set.
  15043. /* c8 ignore start */
  15044. if (p === false) {
  15045. return false;
  15046. }
  15047. /* c8 ignore stop */
  15048. if (p === GLOBSTAR) {
  15049. this.debug('GLOBSTAR', [pattern, p, f]);
  15050. // "**"
  15051. // a/**/b/**/c would match the following:
  15052. // a/b/x/y/z/c
  15053. // a/x/y/z/b/c
  15054. // a/b/x/b/x/c
  15055. // a/b/c
  15056. // To do this, take the rest of the pattern after
  15057. // the **, and see if it would match the file remainder.
  15058. // If so, return success.
  15059. // If not, the ** "swallows" a segment, and try again.
  15060. // This is recursively awful.
  15061. //
  15062. // a/**/b/**/c matching a/b/x/y/z/c
  15063. // - a matches a
  15064. // - doublestar
  15065. // - matchOne(b/x/y/z/c, b/**/c)
  15066. // - b matches b
  15067. // - doublestar
  15068. // - matchOne(x/y/z/c, c) -> no
  15069. // - matchOne(y/z/c, c) -> no
  15070. // - matchOne(z/c, c) -> no
  15071. // - matchOne(c, c) yes, hit
  15072. var fr = fi;
  15073. var pr = pi + 1;
  15074. if (pr === pl) {
  15075. this.debug('** at the end');
  15076. // a ** at the end will just swallow the rest.
  15077. // We have found a match.
  15078. // however, it will not swallow /.x, unless
  15079. // options.dot is set.
  15080. // . and .. are *never* matched by **, for explosively
  15081. // exponential reasons.
  15082. for (; fi < fl; fi++) {
  15083. if (file[fi] === '.' ||
  15084. file[fi] === '..' ||
  15085. (!options.dot && file[fi].charAt(0) === '.'))
  15086. return false;
  15087. }
  15088. return true;
  15089. }
  15090. // ok, let's see if we can swallow whatever we can.
  15091. while (fr < fl) {
  15092. var swallowee = file[fr];
  15093. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  15094. // XXX remove this slice. Just pass the start index.
  15095. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  15096. this.debug('globstar found match!', fr, fl, swallowee);
  15097. // found a match.
  15098. return true;
  15099. }
  15100. else {
  15101. // can't swallow "." or ".." ever.
  15102. // can only swallow ".foo" when explicitly asked.
  15103. if (swallowee === '.' ||
  15104. swallowee === '..' ||
  15105. (!options.dot && swallowee.charAt(0) === '.')) {
  15106. this.debug('dot detected!', file, fr, pattern, pr);
  15107. break;
  15108. }
  15109. // ** swallows a segment, and continue.
  15110. this.debug('globstar swallow a segment, and continue');
  15111. fr++;
  15112. }
  15113. }
  15114. // no match was found.
  15115. // However, in partial mode, we can't say this is necessarily over.
  15116. /* c8 ignore start */
  15117. if (partial) {
  15118. // ran out of file
  15119. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  15120. if (fr === fl) {
  15121. return true;
  15122. }
  15123. }
  15124. /* c8 ignore stop */
  15125. return false;
  15126. }
  15127. // something other than **
  15128. // non-magic patterns just have to match exactly
  15129. // patterns with magic have been turned into regexps.
  15130. let hit;
  15131. if (typeof p === 'string') {
  15132. hit = f === p;
  15133. this.debug('string match', p, f, hit);
  15134. }
  15135. else {
  15136. hit = p.test(f);
  15137. this.debug('pattern match', p, f, hit);
  15138. }
  15139. if (!hit)
  15140. return false;
  15141. }
  15142. // Note: ending in / means that we'll get a final ""
  15143. // at the end of the pattern. This can only match a
  15144. // corresponding "" at the end of the file.
  15145. // If the file ends in /, then it can only match a
  15146. // a pattern that ends in /, unless the pattern just
  15147. // doesn't have any more for it. But, a/b/ should *not*
  15148. // match "a/b/*", even though "" matches against the
  15149. // [^/]*? pattern, except in partial mode, where it might
  15150. // simply not be reached yet.
  15151. // However, a/b/ should still satisfy a/*
  15152. // now either we fell off the end of the pattern, or we're done.
  15153. if (fi === fl && pi === pl) {
  15154. // ran out of pattern and filename at the same time.
  15155. // an exact hit!
  15156. return true;
  15157. }
  15158. else if (fi === fl) {
  15159. // ran out of file, but still had pattern left.
  15160. // this is ok if we're doing the match as part of
  15161. // a glob fs traversal.
  15162. return partial;
  15163. }
  15164. else if (pi === pl) {
  15165. // ran out of pattern, still have file left.
  15166. // this is only acceptable if we're on the very last
  15167. // empty segment of a file with a trailing slash.
  15168. // a/* should match a/b/
  15169. return fi === fl - 1 && file[fi] === '';
  15170. /* c8 ignore start */
  15171. }
  15172. else {
  15173. // should be unreachable.
  15174. throw new Error('wtf?');
  15175. }
  15176. /* c8 ignore stop */
  15177. }
  15178. braceExpand() {
  15179. return braceExpand(this.pattern, this.options);
  15180. }
  15181. parse(pattern) {
  15182. assertValidPattern(pattern);
  15183. const options = this.options;
  15184. // shortcuts
  15185. if (pattern === '**')
  15186. return GLOBSTAR;
  15187. if (pattern === '')
  15188. return '';
  15189. // far and away, the most common glob pattern parts are
  15190. // *, *.*, and *.<ext> Add a fast check method for those.
  15191. let m;
  15192. let fastTest = null;
  15193. if ((m = pattern.match(starRE))) {
  15194. fastTest = options.dot ? starTestDot : starTest;
  15195. }
  15196. else if ((m = pattern.match(starDotExtRE))) {
  15197. fastTest = (options.nocase
  15198. ? options.dot
  15199. ? starDotExtTestNocaseDot
  15200. : starDotExtTestNocase
  15201. : options.dot
  15202. ? starDotExtTestDot
  15203. : starDotExtTest)(m[1]);
  15204. }
  15205. else if ((m = pattern.match(qmarksRE))) {
  15206. fastTest = (options.nocase
  15207. ? options.dot
  15208. ? qmarksTestNocaseDot
  15209. : qmarksTestNocase
  15210. : options.dot
  15211. ? qmarksTestDot
  15212. : qmarksTest)(m);
  15213. }
  15214. else if ((m = pattern.match(starDotStarRE))) {
  15215. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  15216. }
  15217. else if ((m = pattern.match(dotStarRE))) {
  15218. fastTest = dotStarTest;
  15219. }
  15220. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  15221. return fastTest ? Object.assign(re, { test: fastTest }) : re;
  15222. }
  15223. makeRe() {
  15224. if (this.regexp || this.regexp === false)
  15225. return this.regexp;
  15226. // at this point, this.set is a 2d array of partial
  15227. // pattern strings, or "**".
  15228. //
  15229. // It's better to use .match(). This function shouldn't
  15230. // be used, really, but it's pretty convenient sometimes,
  15231. // when you just want to work with a regex.
  15232. const set = this.set;
  15233. if (!set.length) {
  15234. this.regexp = false;
  15235. return this.regexp;
  15236. }
  15237. const options = this.options;
  15238. const twoStar = options.noglobstar
  15239. ? star
  15240. : options.dot
  15241. ? twoStarDot
  15242. : twoStarNoDot;
  15243. const flags = new Set(options.nocase ? ['i'] : []);
  15244. // regexpify non-globstar patterns
  15245. // if ** is only item, then we just do one twoStar
  15246. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  15247. // if ** is last, append (\/twoStar|) to previous
  15248. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  15249. // then filter out GLOBSTAR symbols
  15250. let re = set
  15251. .map(pattern => {
  15252. const pp = pattern.map(p => {
  15253. if (p instanceof RegExp) {
  15254. for (const f of p.flags.split(''))
  15255. flags.add(f);
  15256. }
  15257. return typeof p === 'string'
  15258. ? regExpEscape(p)
  15259. : p === GLOBSTAR
  15260. ? GLOBSTAR
  15261. : p._src;
  15262. });
  15263. pp.forEach((p, i) => {
  15264. const next = pp[i + 1];
  15265. const prev = pp[i - 1];
  15266. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  15267. return;
  15268. }
  15269. if (prev === undefined) {
  15270. if (next !== undefined && next !== GLOBSTAR) {
  15271. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  15272. }
  15273. else {
  15274. pp[i] = twoStar;
  15275. }
  15276. }
  15277. else if (next === undefined) {
  15278. pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
  15279. }
  15280. else if (next !== GLOBSTAR) {
  15281. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  15282. pp[i + 1] = GLOBSTAR;
  15283. }
  15284. });
  15285. return pp.filter(p => p !== GLOBSTAR).join('/');
  15286. })
  15287. .join('|');
  15288. // need to wrap in parens if we had more than one thing with |,
  15289. // otherwise only the first will be anchored to ^ and the last to $
  15290. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  15291. // must match entire pattern
  15292. // ending in a * or ** will make it less strict.
  15293. re = '^' + open + re + close + '$';
  15294. // can match anything, as long as it's not this.
  15295. if (this.negate)
  15296. re = '^(?!' + re + ').+$';
  15297. try {
  15298. this.regexp = new RegExp(re, [...flags].join(''));
  15299. /* c8 ignore start */
  15300. }
  15301. catch (ex) {
  15302. // should be impossible
  15303. this.regexp = false;
  15304. }
  15305. /* c8 ignore stop */
  15306. return this.regexp;
  15307. }
  15308. slashSplit(p) {
  15309. // if p starts with // on windows, we preserve that
  15310. // so that UNC paths aren't broken. Otherwise, any number of
  15311. // / characters are coalesced into one, unless
  15312. // preserveMultipleSlashes is set to true.
  15313. if (this.preserveMultipleSlashes) {
  15314. return p.split('/');
  15315. }
  15316. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  15317. // add an extra '' for the one we lose
  15318. return ['', ...p.split(/\/+/)];
  15319. }
  15320. else {
  15321. return p.split(/\/+/);
  15322. }
  15323. }
  15324. match(f, partial = this.partial) {
  15325. this.debug('match', f, this.pattern);
  15326. // short-circuit in the case of busted things.
  15327. // comments, etc.
  15328. if (this.comment) {
  15329. return false;
  15330. }
  15331. if (this.empty) {
  15332. return f === '';
  15333. }
  15334. if (f === '/' && partial) {
  15335. return true;
  15336. }
  15337. const options = this.options;
  15338. // windows: need to use /, not \
  15339. if (this.isWindows) {
  15340. f = f.split('\\').join('/');
  15341. }
  15342. // treat the test path as a set of pathparts.
  15343. const ff = this.slashSplit(f);
  15344. this.debug(this.pattern, 'split', ff);
  15345. // just ONE of the pattern sets in this.set needs to match
  15346. // in order for it to be valid. If negating, then just one
  15347. // match means that we have failed.
  15348. // Either way, return on the first hit.
  15349. const set = this.set;
  15350. this.debug(this.pattern, 'set', set);
  15351. // Find the basename of the path by looking for the last non-empty segment
  15352. let filename = ff[ff.length - 1];
  15353. if (!filename) {
  15354. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  15355. filename = ff[i];
  15356. }
  15357. }
  15358. for (let i = 0; i < set.length; i++) {
  15359. const pattern = set[i];
  15360. let file = ff;
  15361. if (options.matchBase && pattern.length === 1) {
  15362. file = [filename];
  15363. }
  15364. const hit = this.matchOne(file, pattern, partial);
  15365. if (hit) {
  15366. if (options.flipNegate) {
  15367. return true;
  15368. }
  15369. return !this.negate;
  15370. }
  15371. }
  15372. // didn't get any hits. this is success if it's a negative
  15373. // pattern, failure otherwise.
  15374. if (options.flipNegate) {
  15375. return false;
  15376. }
  15377. return this.negate;
  15378. }
  15379. static defaults(def) {
  15380. return minimatch.defaults(def).Minimatch;
  15381. }
  15382. }
  15383. /* c8 ignore stop */
  15384. minimatch.AST = AST;
  15385. minimatch.Minimatch = Minimatch;
  15386. minimatch.escape = escape;
  15387. minimatch.unescape = unescape;
  15388. class TypeScope {
  15389. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  15390. this.filename = filename;
  15391. this.source = source;
  15392. this.offset = offset;
  15393. this.imports = imports;
  15394. this.types = types;
  15395. this.declares = declares;
  15396. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  15397. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  15398. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  15399. }
  15400. }
  15401. function resolveTypeElements(ctx, node, scope) {
  15402. if (node._resolvedElements) {
  15403. return node._resolvedElements;
  15404. }
  15405. return node._resolvedElements = innerResolveTypeElements(
  15406. ctx,
  15407. node,
  15408. node._ownerScope || scope || ctxToScope(ctx)
  15409. );
  15410. }
  15411. function innerResolveTypeElements(ctx, node, scope) {
  15412. var _a, _b;
  15413. switch (node.type) {
  15414. case "TSTypeLiteral":
  15415. return typeElementsToMap(ctx, node.members, scope);
  15416. case "TSInterfaceDeclaration":
  15417. return resolveInterfaceMembers(ctx, node, scope);
  15418. case "TSTypeAliasDeclaration":
  15419. case "TSParenthesizedType":
  15420. return resolveTypeElements(ctx, node.typeAnnotation, scope);
  15421. case "TSFunctionType": {
  15422. return { props: {}, calls: [node] };
  15423. }
  15424. case "TSUnionType":
  15425. case "TSIntersectionType":
  15426. return mergeElements(
  15427. node.types.map((t) => resolveTypeElements(ctx, t, scope)),
  15428. node.type
  15429. );
  15430. case "TSMappedType":
  15431. return resolveMappedType(ctx, node, scope);
  15432. case "TSIndexedAccessType": {
  15433. const types = resolveIndexType(ctx, node, scope);
  15434. return mergeElements(
  15435. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  15436. "TSUnionType"
  15437. );
  15438. }
  15439. case "TSExpressionWithTypeArguments":
  15440. case "TSTypeReference": {
  15441. const typeName = getReferenceName(node);
  15442. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  15443. return resolveExtractPropTypes(
  15444. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  15445. scope
  15446. );
  15447. }
  15448. const resolved = resolveTypeReference(ctx, node, scope);
  15449. if (resolved) {
  15450. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  15451. } else {
  15452. if (typeof typeName === "string") {
  15453. if (
  15454. // @ts-ignore
  15455. SupportedBuiltinsSet.has(typeName)
  15456. ) {
  15457. return resolveBuiltin(ctx, node, typeName, scope);
  15458. } else if (typeName === "ReturnType" && node.typeParameters) {
  15459. const ret = resolveReturnType(
  15460. ctx,
  15461. node.typeParameters.params[0],
  15462. scope
  15463. );
  15464. if (ret) {
  15465. return resolveTypeElements(ctx, ret, scope);
  15466. }
  15467. }
  15468. }
  15469. return ctx.error(
  15470. `Unresolvable type reference or unsupported built-in utility type`,
  15471. node,
  15472. scope
  15473. );
  15474. }
  15475. }
  15476. case "TSImportType": {
  15477. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  15478. return resolveExtractPropTypes(
  15479. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  15480. scope
  15481. );
  15482. }
  15483. const sourceScope = importSourceToScope(
  15484. ctx,
  15485. node.argument,
  15486. scope,
  15487. node.argument.value
  15488. );
  15489. const resolved = resolveTypeReference(ctx, node, sourceScope);
  15490. if (resolved) {
  15491. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  15492. }
  15493. }
  15494. case "TSTypeQuery": {
  15495. const resolved = resolveTypeReference(ctx, node, scope);
  15496. if (resolved) {
  15497. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  15498. }
  15499. }
  15500. }
  15501. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  15502. }
  15503. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx)) {
  15504. const res = { props: {} };
  15505. for (const e of elements) {
  15506. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  15507. e._ownerScope = scope;
  15508. const name = getId(e.key);
  15509. if (name && !e.computed) {
  15510. res.props[name] = e;
  15511. } else if (e.key.type === "TemplateLiteral") {
  15512. for (const key of resolveTemplateKeys(ctx, e.key, scope)) {
  15513. res.props[key] = e;
  15514. }
  15515. } else {
  15516. ctx.error(
  15517. `Unsupported computed key in type referenced by a macro`,
  15518. e.key,
  15519. scope
  15520. );
  15521. }
  15522. } else if (e.type === "TSCallSignatureDeclaration") {
  15523. (res.calls || (res.calls = [])).push(e);
  15524. }
  15525. }
  15526. return res;
  15527. }
  15528. function mergeElements(maps, type) {
  15529. if (maps.length === 1)
  15530. return maps[0];
  15531. const res = { props: {} };
  15532. const { props: baseProps } = res;
  15533. for (const { props, calls } of maps) {
  15534. for (const key in props) {
  15535. if (!shared.hasOwn(baseProps, key)) {
  15536. baseProps[key] = props[key];
  15537. } else {
  15538. baseProps[key] = createProperty(
  15539. baseProps[key].key,
  15540. {
  15541. type,
  15542. // @ts-ignore
  15543. types: [baseProps[key], props[key]]
  15544. },
  15545. baseProps[key]._ownerScope,
  15546. baseProps[key].optional || props[key].optional
  15547. );
  15548. }
  15549. }
  15550. if (calls) {
  15551. (res.calls || (res.calls = [])).push(...calls);
  15552. }
  15553. }
  15554. return res;
  15555. }
  15556. function createProperty(key, typeAnnotation, scope, optional) {
  15557. return {
  15558. type: "TSPropertySignature",
  15559. key,
  15560. kind: "get",
  15561. optional,
  15562. typeAnnotation: {
  15563. type: "TSTypeAnnotation",
  15564. typeAnnotation
  15565. },
  15566. _ownerScope: scope
  15567. };
  15568. }
  15569. function resolveInterfaceMembers(ctx, node, scope) {
  15570. const base = typeElementsToMap(ctx, node.body.body, node._ownerScope);
  15571. if (node.extends) {
  15572. for (const ext of node.extends) {
  15573. if (ext.leadingComments && ext.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  15574. continue;
  15575. }
  15576. try {
  15577. const { props } = resolveTypeElements(ctx, ext, scope);
  15578. for (const key in props) {
  15579. if (!shared.hasOwn(base.props, key)) {
  15580. base.props[key] = props[key];
  15581. }
  15582. }
  15583. } catch (e) {
  15584. ctx.error(
  15585. `Failed to resolve extends base type.
  15586. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  15587. interface Props extends /* @vue-ignore */ Base {}
  15588. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  15589. ext
  15590. );
  15591. }
  15592. }
  15593. }
  15594. return base;
  15595. }
  15596. function resolveMappedType(ctx, node, scope) {
  15597. const res = { props: {} };
  15598. const keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  15599. for (const key of keys) {
  15600. res.props[key] = createProperty(
  15601. {
  15602. type: "Identifier",
  15603. name: key
  15604. },
  15605. node.typeAnnotation,
  15606. scope,
  15607. !!node.optional
  15608. );
  15609. }
  15610. return res;
  15611. }
  15612. function resolveIndexType(ctx, node, scope) {
  15613. var _a, _b;
  15614. if (node.indexType.type === "TSNumberKeyword") {
  15615. return resolveArrayElementType(ctx, node.objectType, scope);
  15616. }
  15617. const { indexType, objectType } = node;
  15618. const types = [];
  15619. let keys;
  15620. let resolved;
  15621. if (indexType.type === "TSStringKeyword") {
  15622. resolved = resolveTypeElements(ctx, objectType, scope);
  15623. keys = Object.keys(resolved.props);
  15624. } else {
  15625. keys = resolveStringType(ctx, indexType, scope);
  15626. resolved = resolveTypeElements(ctx, objectType, scope);
  15627. }
  15628. for (const key of keys) {
  15629. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  15630. if (targetType) {
  15631. targetType._ownerScope = resolved.props[key]._ownerScope;
  15632. types.push(targetType);
  15633. }
  15634. }
  15635. return types;
  15636. }
  15637. function resolveArrayElementType(ctx, node, scope) {
  15638. if (node.type === "TSArrayType") {
  15639. return [node.elementType];
  15640. }
  15641. if (node.type === "TSTupleType") {
  15642. return node.elementTypes.map(
  15643. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  15644. );
  15645. }
  15646. if (node.type === "TSTypeReference") {
  15647. if (getReferenceName(node) === "Array" && node.typeParameters) {
  15648. return node.typeParameters.params;
  15649. } else {
  15650. const resolved = resolveTypeReference(ctx, node, scope);
  15651. if (resolved) {
  15652. return resolveArrayElementType(ctx, resolved, scope);
  15653. }
  15654. }
  15655. }
  15656. return ctx.error(
  15657. "Failed to resolve element type from target type",
  15658. node,
  15659. scope
  15660. );
  15661. }
  15662. function resolveStringType(ctx, node, scope) {
  15663. switch (node.type) {
  15664. case "StringLiteral":
  15665. return [node.value];
  15666. case "TSLiteralType":
  15667. return resolveStringType(ctx, node.literal, scope);
  15668. case "TSUnionType":
  15669. return node.types.map((t) => resolveStringType(ctx, t, scope)).flat();
  15670. case "TemplateLiteral": {
  15671. return resolveTemplateKeys(ctx, node, scope);
  15672. }
  15673. case "TSTypeReference": {
  15674. const resolved = resolveTypeReference(ctx, node, scope);
  15675. if (resolved) {
  15676. return resolveStringType(ctx, resolved, scope);
  15677. }
  15678. if (node.typeName.type === "Identifier") {
  15679. const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters.params[index], scope);
  15680. switch (node.typeName.name) {
  15681. case "Extract":
  15682. return getParam(1);
  15683. case "Exclude": {
  15684. const excluded = getParam(1);
  15685. return getParam().filter((s) => !excluded.includes(s));
  15686. }
  15687. case "Uppercase":
  15688. return getParam().map((s) => s.toUpperCase());
  15689. case "Lowercase":
  15690. return getParam().map((s) => s.toLowerCase());
  15691. case "Capitalize":
  15692. return getParam().map(shared.capitalize);
  15693. case "Uncapitalize":
  15694. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  15695. default:
  15696. ctx.error(
  15697. "Unsupported type when resolving index type",
  15698. node.typeName,
  15699. scope
  15700. );
  15701. }
  15702. }
  15703. }
  15704. }
  15705. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  15706. }
  15707. function resolveTemplateKeys(ctx, node, scope) {
  15708. if (!node.expressions.length) {
  15709. return [node.quasis[0].value.raw];
  15710. }
  15711. const res = [];
  15712. const e = node.expressions[0];
  15713. const q = node.quasis[0];
  15714. const leading = q ? q.value.raw : ``;
  15715. const resolved = resolveStringType(ctx, e, scope);
  15716. const restResolved = resolveTemplateKeys(
  15717. ctx,
  15718. {
  15719. ...node,
  15720. expressions: node.expressions.slice(1),
  15721. quasis: q ? node.quasis.slice(1) : node.quasis
  15722. },
  15723. scope
  15724. );
  15725. for (const r of resolved) {
  15726. for (const rr of restResolved) {
  15727. res.push(leading + r + rr);
  15728. }
  15729. }
  15730. return res;
  15731. }
  15732. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  15733. "Partial",
  15734. "Required",
  15735. "Readonly",
  15736. "Pick",
  15737. "Omit"
  15738. ]);
  15739. function resolveBuiltin(ctx, node, name, scope) {
  15740. const t = resolveTypeElements(ctx, node.typeParameters.params[0], scope);
  15741. switch (name) {
  15742. case "Partial": {
  15743. const res2 = { props: {}, calls: t.calls };
  15744. Object.keys(t.props).forEach((key) => {
  15745. res2.props[key] = { ...t.props[key], optional: true };
  15746. });
  15747. return res2;
  15748. }
  15749. case "Required": {
  15750. const res2 = { props: {}, calls: t.calls };
  15751. Object.keys(t.props).forEach((key) => {
  15752. res2.props[key] = { ...t.props[key], optional: false };
  15753. });
  15754. return res2;
  15755. }
  15756. case "Readonly":
  15757. return t;
  15758. case "Pick": {
  15759. const picked = resolveStringType(
  15760. ctx,
  15761. node.typeParameters.params[1],
  15762. scope
  15763. );
  15764. const res2 = { props: {}, calls: t.calls };
  15765. for (const key of picked) {
  15766. res2.props[key] = t.props[key];
  15767. }
  15768. return res2;
  15769. }
  15770. case "Omit":
  15771. const omitted = resolveStringType(
  15772. ctx,
  15773. node.typeParameters.params[1],
  15774. scope
  15775. );
  15776. const res = { props: {}, calls: t.calls };
  15777. for (const key in t.props) {
  15778. if (!omitted.includes(key)) {
  15779. res.props[key] = t.props[key];
  15780. }
  15781. }
  15782. return res;
  15783. }
  15784. }
  15785. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  15786. if (node._resolvedReference) {
  15787. return node._resolvedReference;
  15788. }
  15789. return node._resolvedReference = innerResolveTypeReference(
  15790. ctx,
  15791. scope || ctxToScope(ctx),
  15792. name || getReferenceName(node),
  15793. node,
  15794. onlyExported
  15795. );
  15796. }
  15797. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  15798. if (typeof name === "string") {
  15799. if (scope.imports[name]) {
  15800. return resolveTypeFromImport(ctx, node, name, scope);
  15801. } else {
  15802. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  15803. if (lookupSource[name]) {
  15804. return lookupSource[name];
  15805. } else {
  15806. const globalScopes = resolveGlobalScope(ctx);
  15807. if (globalScopes) {
  15808. for (const s of globalScopes) {
  15809. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  15810. if (src[name]) {
  15811. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  15812. return src[name];
  15813. }
  15814. }
  15815. }
  15816. }
  15817. }
  15818. } else {
  15819. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  15820. if (ns) {
  15821. if (ns.type !== "TSModuleDeclaration") {
  15822. ns = ns._ns;
  15823. }
  15824. if (ns) {
  15825. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  15826. return innerResolveTypeReference(
  15827. ctx,
  15828. childScope,
  15829. name.length > 2 ? name.slice(1) : name[name.length - 1],
  15830. node,
  15831. !ns.declare
  15832. );
  15833. }
  15834. }
  15835. }
  15836. }
  15837. function getReferenceName(node) {
  15838. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  15839. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  15840. return ref.name;
  15841. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  15842. return qualifiedNameToPath(ref);
  15843. } else {
  15844. return "default";
  15845. }
  15846. }
  15847. function qualifiedNameToPath(node) {
  15848. if (node.type === "Identifier") {
  15849. return [node.name];
  15850. } else {
  15851. return [...qualifiedNameToPath(node.left), node.right.name];
  15852. }
  15853. }
  15854. function resolveGlobalScope(ctx) {
  15855. if (ctx.options.globalTypeFiles) {
  15856. const fs = resolveFS(ctx);
  15857. if (!fs) {
  15858. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  15859. }
  15860. return ctx.options.globalTypeFiles.map(
  15861. (file) => fileToScope(ctx, normalizePath(file), true)
  15862. );
  15863. }
  15864. }
  15865. let ts;
  15866. function registerTS(_ts) {
  15867. ts = _ts;
  15868. }
  15869. function resolveFS(ctx) {
  15870. if (ctx.fs) {
  15871. return ctx.fs;
  15872. }
  15873. const fs = ctx.options.fs || ts.sys;
  15874. if (!fs) {
  15875. return;
  15876. }
  15877. return ctx.fs = {
  15878. fileExists(file) {
  15879. if (file.endsWith(".vue.ts")) {
  15880. file = file.replace(/\.ts$/, "");
  15881. }
  15882. return fs.fileExists(file);
  15883. },
  15884. readFile(file) {
  15885. if (file.endsWith(".vue.ts")) {
  15886. file = file.replace(/\.ts$/, "");
  15887. }
  15888. return fs.readFile(file);
  15889. }
  15890. };
  15891. }
  15892. function resolveTypeFromImport(ctx, node, name, scope) {
  15893. const { source, imported } = scope.imports[name];
  15894. const sourceScope = importSourceToScope(ctx, node, scope, source);
  15895. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  15896. }
  15897. function importSourceToScope(ctx, node, scope, source) {
  15898. const fs = resolveFS(ctx);
  15899. if (!fs) {
  15900. return ctx.error(
  15901. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  15902. node,
  15903. scope
  15904. );
  15905. }
  15906. let resolved = scope.resolvedImportSources[source];
  15907. if (!resolved) {
  15908. if (source.startsWith(".")) {
  15909. const filename = joinPaths(scope.filename, "..", source);
  15910. resolved = resolveExt(filename, fs);
  15911. } else {
  15912. if (!ts) {
  15913. ctx.error(
  15914. `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.`,
  15915. node,
  15916. scope
  15917. );
  15918. }
  15919. resolved = resolveWithTS(scope.filename, source, fs);
  15920. }
  15921. if (resolved) {
  15922. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  15923. }
  15924. }
  15925. if (resolved) {
  15926. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  15927. return fileToScope(ctx, resolved);
  15928. } else {
  15929. return ctx.error(
  15930. `Failed to resolve import source ${JSON.stringify(source)}.`,
  15931. node,
  15932. scope
  15933. );
  15934. }
  15935. }
  15936. function resolveExt(filename, fs) {
  15937. filename = filename.replace(/\.js$/, "");
  15938. const tryResolve = (filename2) => {
  15939. if (fs.fileExists(filename2))
  15940. return filename2;
  15941. };
  15942. return tryResolve(filename) || tryResolve(filename + `.ts`) || tryResolve(filename + `.d.ts`) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  15943. }
  15944. const tsConfigCache = createCache();
  15945. const tsConfigRefMap = /* @__PURE__ */ new Map();
  15946. function resolveWithTS(containingFile, source, fs) {
  15947. var _a, _b;
  15948. const configPath = ts.findConfigFile(containingFile, fs.fileExists);
  15949. let tsCompilerOptions;
  15950. let tsResolveCache;
  15951. if (configPath) {
  15952. let configs;
  15953. const normalizedConfigPath = normalizePath(configPath);
  15954. const cached = tsConfigCache.get(normalizedConfigPath);
  15955. if (!cached) {
  15956. configs = loadTSConfig(configPath, fs).map((config) => ({ config }));
  15957. tsConfigCache.set(normalizedConfigPath, configs);
  15958. } else {
  15959. configs = cached;
  15960. }
  15961. let matchedConfig;
  15962. if (configs.length === 1) {
  15963. matchedConfig = configs[0];
  15964. } else {
  15965. for (const c of configs) {
  15966. const base = normalizePath(
  15967. c.config.options.pathsBasePath || path$3.dirname(c.config.options.configFilePath)
  15968. );
  15969. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  15970. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  15971. if (!included && (!base || containingFile.startsWith(base)) || included.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  15972. if (excluded && excluded.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  15973. continue;
  15974. }
  15975. matchedConfig = c;
  15976. break;
  15977. }
  15978. }
  15979. if (!matchedConfig) {
  15980. matchedConfig = configs[configs.length - 1];
  15981. }
  15982. }
  15983. tsCompilerOptions = matchedConfig.config.options;
  15984. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts.createModuleResolutionCache(
  15985. process.cwd(),
  15986. createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames),
  15987. tsCompilerOptions
  15988. ));
  15989. } else {
  15990. tsCompilerOptions = {};
  15991. }
  15992. const res = ts.resolveModuleName(
  15993. source,
  15994. containingFile,
  15995. tsCompilerOptions,
  15996. fs,
  15997. tsResolveCache
  15998. );
  15999. if (res.resolvedModule) {
  16000. let filename = res.resolvedModule.resolvedFileName;
  16001. if (filename.endsWith(".vue.ts")) {
  16002. filename = filename.replace(/\.ts$/, "");
  16003. }
  16004. return filename;
  16005. }
  16006. }
  16007. function loadTSConfig(configPath, fs) {
  16008. const parseConfigHost = ts.sys;
  16009. const config = ts.parseJsonConfigFileContent(
  16010. ts.readConfigFile(configPath, fs.readFile).config,
  16011. parseConfigHost,
  16012. path$3.dirname(configPath),
  16013. void 0,
  16014. configPath
  16015. );
  16016. const res = [config];
  16017. if (config.projectReferences) {
  16018. for (const ref of config.projectReferences) {
  16019. tsConfigRefMap.set(ref.path, configPath);
  16020. res.unshift(...loadTSConfig(ref.path, fs));
  16021. }
  16022. }
  16023. return res;
  16024. }
  16025. const fileToScopeCache = createCache();
  16026. function invalidateTypeCache(filename) {
  16027. filename = normalizePath(filename);
  16028. fileToScopeCache.delete(filename);
  16029. tsConfigCache.delete(filename);
  16030. const affectedConfig = tsConfigRefMap.get(filename);
  16031. if (affectedConfig)
  16032. tsConfigCache.delete(affectedConfig);
  16033. }
  16034. function fileToScope(ctx, filename, asGlobal = false) {
  16035. const cached = fileToScopeCache.get(filename);
  16036. if (cached) {
  16037. return cached;
  16038. }
  16039. const fs = resolveFS(ctx);
  16040. const source = fs.readFile(filename) || "";
  16041. const body = parseFile(filename, source, ctx.options.babelParserPlugins);
  16042. const scope = new TypeScope(filename, source, 0, recordImports(body));
  16043. recordTypes(ctx, body, scope, asGlobal);
  16044. fileToScopeCache.set(filename, scope);
  16045. return scope;
  16046. }
  16047. function parseFile(filename, content, parserPlugins) {
  16048. const ext = path$3.extname(filename);
  16049. if (ext === ".ts" || ext === ".tsx") {
  16050. return parser$2.parse(content, {
  16051. plugins: resolveParserPlugins(
  16052. ext.slice(1),
  16053. parserPlugins,
  16054. filename.endsWith(".d.ts")
  16055. ),
  16056. sourceType: "module"
  16057. }).program.body;
  16058. } else if (ext === ".vue") {
  16059. const {
  16060. descriptor: { script, scriptSetup }
  16061. } = parse$2(content);
  16062. if (!script && !scriptSetup) {
  16063. return [];
  16064. }
  16065. const scriptOffset = script ? script.loc.start.offset : Infinity;
  16066. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  16067. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  16068. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  16069. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  16070. if (secondBlock) {
  16071. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  16072. }
  16073. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  16074. return parser$2.parse(scriptContent, {
  16075. plugins: resolveParserPlugins(lang, parserPlugins),
  16076. sourceType: "module"
  16077. }).program.body;
  16078. }
  16079. return [];
  16080. }
  16081. function ctxToScope(ctx) {
  16082. if (ctx.scope) {
  16083. return ctx.scope;
  16084. }
  16085. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  16086. const scope = new TypeScope(
  16087. ctx.filename,
  16088. ctx.source,
  16089. "startOffset" in ctx ? ctx.startOffset : 0,
  16090. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  16091. );
  16092. recordTypes(ctx, body, scope);
  16093. return ctx.scope = scope;
  16094. }
  16095. function moduleDeclToScope(ctx, node, parentScope) {
  16096. if (node._resolvedChildScope) {
  16097. return node._resolvedChildScope;
  16098. }
  16099. const scope = new TypeScope(
  16100. parentScope.filename,
  16101. parentScope.source,
  16102. parentScope.offset,
  16103. Object.create(parentScope.imports),
  16104. Object.create(parentScope.types),
  16105. Object.create(parentScope.declares)
  16106. );
  16107. if (node.body.type === "TSModuleDeclaration") {
  16108. const decl = node.body;
  16109. decl._ownerScope = scope;
  16110. const id = getId(decl.id);
  16111. scope.types[id] = scope.exportedTypes[id] = decl;
  16112. } else {
  16113. recordTypes(ctx, node.body.body, scope);
  16114. }
  16115. return node._resolvedChildScope = scope;
  16116. }
  16117. const importExportRE = /^Import|^Export/;
  16118. function recordTypes(ctx, body, scope, asGlobal = false) {
  16119. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  16120. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  16121. for (const stmt of body) {
  16122. if (asGlobal) {
  16123. if (isAmbient) {
  16124. if (stmt.declare) {
  16125. recordType(stmt, types, declares);
  16126. }
  16127. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  16128. for (const s of stmt.body.body) {
  16129. recordType(s, types, declares);
  16130. }
  16131. }
  16132. } else {
  16133. recordType(stmt, types, declares);
  16134. }
  16135. }
  16136. if (!asGlobal) {
  16137. for (const stmt of body) {
  16138. if (stmt.type === "ExportNamedDeclaration") {
  16139. if (stmt.declaration) {
  16140. recordType(stmt.declaration, types, declares);
  16141. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  16142. } else {
  16143. for (const spec of stmt.specifiers) {
  16144. if (spec.type === "ExportSpecifier") {
  16145. const local = spec.local.name;
  16146. const exported = getId(spec.exported);
  16147. if (stmt.source) {
  16148. imports[local] = {
  16149. source: stmt.source.value,
  16150. imported: local
  16151. };
  16152. exportedTypes[exported] = {
  16153. type: "TSTypeReference",
  16154. typeName: {
  16155. type: "Identifier",
  16156. name: local
  16157. },
  16158. _ownerScope: scope
  16159. };
  16160. } else if (types[local]) {
  16161. exportedTypes[exported] = types[local];
  16162. }
  16163. }
  16164. }
  16165. }
  16166. } else if (stmt.type === "ExportAllDeclaration") {
  16167. const sourceScope = importSourceToScope(
  16168. ctx,
  16169. stmt.source,
  16170. scope,
  16171. stmt.source.value
  16172. );
  16173. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  16174. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  16175. if (stmt.declaration.type !== "Identifier") {
  16176. recordType(stmt.declaration, types, declares, "default");
  16177. recordType(
  16178. stmt.declaration,
  16179. exportedTypes,
  16180. exportedDeclares,
  16181. "default"
  16182. );
  16183. } else if (types[stmt.declaration.name]) {
  16184. exportedTypes["default"] = types[stmt.declaration.name];
  16185. }
  16186. }
  16187. }
  16188. }
  16189. for (const key of Object.keys(types)) {
  16190. const node = types[key];
  16191. node._ownerScope = scope;
  16192. if (node._ns)
  16193. node._ns._ownerScope = scope;
  16194. }
  16195. for (const key of Object.keys(declares)) {
  16196. declares[key]._ownerScope = scope;
  16197. }
  16198. }
  16199. function recordType(node, types, declares, overwriteId) {
  16200. switch (node.type) {
  16201. case "TSInterfaceDeclaration":
  16202. case "TSEnumDeclaration":
  16203. case "TSModuleDeclaration": {
  16204. const id = overwriteId || getId(node.id);
  16205. let existing = types[id];
  16206. if (existing) {
  16207. if (node.type === "TSModuleDeclaration") {
  16208. if (existing.type === "TSModuleDeclaration") {
  16209. mergeNamespaces(existing, node);
  16210. } else {
  16211. attachNamespace(existing, node);
  16212. }
  16213. break;
  16214. }
  16215. if (existing.type === "TSModuleDeclaration") {
  16216. types[id] = node;
  16217. attachNamespace(node, existing);
  16218. break;
  16219. }
  16220. if (existing.type !== node.type) {
  16221. break;
  16222. }
  16223. if (node.type === "TSInterfaceDeclaration") {
  16224. existing.body.body.push(...node.body.body);
  16225. } else {
  16226. existing.members.push(...node.members);
  16227. }
  16228. } else {
  16229. types[id] = node;
  16230. }
  16231. break;
  16232. }
  16233. case "ClassDeclaration":
  16234. types[overwriteId || getId(node.id)] = node;
  16235. break;
  16236. case "TSTypeAliasDeclaration":
  16237. types[node.id.name] = node.typeAnnotation;
  16238. break;
  16239. case "TSDeclareFunction":
  16240. if (node.id)
  16241. declares[node.id.name] = node;
  16242. break;
  16243. case "VariableDeclaration": {
  16244. if (node.declare) {
  16245. for (const decl of node.declarations) {
  16246. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  16247. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  16248. }
  16249. }
  16250. }
  16251. break;
  16252. }
  16253. }
  16254. }
  16255. function mergeNamespaces(to, from) {
  16256. const toBody = to.body;
  16257. const fromBody = from.body;
  16258. if (toBody.type === "TSModuleDeclaration") {
  16259. if (fromBody.type === "TSModuleDeclaration") {
  16260. mergeNamespaces(toBody, fromBody);
  16261. } else {
  16262. fromBody.body.push({
  16263. type: "ExportNamedDeclaration",
  16264. declaration: toBody,
  16265. exportKind: "type",
  16266. specifiers: []
  16267. });
  16268. }
  16269. } else if (fromBody.type === "TSModuleDeclaration") {
  16270. toBody.body.push({
  16271. type: "ExportNamedDeclaration",
  16272. declaration: fromBody,
  16273. exportKind: "type",
  16274. specifiers: []
  16275. });
  16276. } else {
  16277. toBody.body.push(...fromBody.body);
  16278. }
  16279. }
  16280. function attachNamespace(to, ns) {
  16281. if (!to._ns) {
  16282. to._ns = ns;
  16283. } else {
  16284. mergeNamespaces(to._ns, ns);
  16285. }
  16286. }
  16287. function recordImports(body) {
  16288. const imports = /* @__PURE__ */ Object.create(null);
  16289. for (const s of body) {
  16290. recordImport(s, imports);
  16291. }
  16292. return imports;
  16293. }
  16294. function recordImport(node, imports) {
  16295. if (node.type !== "ImportDeclaration") {
  16296. return;
  16297. }
  16298. for (const s of node.specifiers) {
  16299. imports[s.local.name] = {
  16300. imported: getImportedName(s),
  16301. source: node.source.value
  16302. };
  16303. }
  16304. }
  16305. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx)) {
  16306. try {
  16307. switch (node.type) {
  16308. case "TSStringKeyword":
  16309. return ["String"];
  16310. case "TSNumberKeyword":
  16311. return ["Number"];
  16312. case "TSBooleanKeyword":
  16313. return ["Boolean"];
  16314. case "TSObjectKeyword":
  16315. return ["Object"];
  16316. case "TSNullKeyword":
  16317. return ["null"];
  16318. case "TSTypeLiteral":
  16319. case "TSInterfaceDeclaration": {
  16320. const types = /* @__PURE__ */ new Set();
  16321. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  16322. for (const m of members) {
  16323. if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  16324. types.add("Function");
  16325. } else {
  16326. types.add("Object");
  16327. }
  16328. }
  16329. return types.size ? Array.from(types) : ["Object"];
  16330. }
  16331. case "TSPropertySignature":
  16332. if (node.typeAnnotation) {
  16333. return inferRuntimeType(
  16334. ctx,
  16335. node.typeAnnotation.typeAnnotation,
  16336. scope
  16337. );
  16338. }
  16339. case "TSMethodSignature":
  16340. case "TSFunctionType":
  16341. return ["Function"];
  16342. case "TSArrayType":
  16343. case "TSTupleType":
  16344. return ["Array"];
  16345. case "TSLiteralType":
  16346. switch (node.literal.type) {
  16347. case "StringLiteral":
  16348. return ["String"];
  16349. case "BooleanLiteral":
  16350. return ["Boolean"];
  16351. case "NumericLiteral":
  16352. case "BigIntLiteral":
  16353. return ["Number"];
  16354. default:
  16355. return [UNKNOWN_TYPE];
  16356. }
  16357. case "TSTypeReference": {
  16358. const resolved = resolveTypeReference(ctx, node, scope);
  16359. if (resolved) {
  16360. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  16361. }
  16362. if (node.typeName.type === "Identifier") {
  16363. switch (node.typeName.name) {
  16364. case "Array":
  16365. case "Function":
  16366. case "Object":
  16367. case "Set":
  16368. case "Map":
  16369. case "WeakSet":
  16370. case "WeakMap":
  16371. case "Date":
  16372. case "Promise":
  16373. return [node.typeName.name];
  16374. case "Partial":
  16375. case "Required":
  16376. case "Readonly":
  16377. case "Record":
  16378. case "Pick":
  16379. case "Omit":
  16380. case "InstanceType":
  16381. return ["Object"];
  16382. case "Uppercase":
  16383. case "Lowercase":
  16384. case "Capitalize":
  16385. case "Uncapitalize":
  16386. return ["String"];
  16387. case "Parameters":
  16388. case "ConstructorParameters":
  16389. return ["Array"];
  16390. case "NonNullable":
  16391. if (node.typeParameters && node.typeParameters.params[0]) {
  16392. return inferRuntimeType(
  16393. ctx,
  16394. node.typeParameters.params[0],
  16395. scope
  16396. ).filter((t) => t !== "null");
  16397. }
  16398. break;
  16399. case "Extract":
  16400. if (node.typeParameters && node.typeParameters.params[1]) {
  16401. return inferRuntimeType(
  16402. ctx,
  16403. node.typeParameters.params[1],
  16404. scope
  16405. );
  16406. }
  16407. break;
  16408. case "Exclude":
  16409. case "OmitThisParameter":
  16410. if (node.typeParameters && node.typeParameters.params[0]) {
  16411. return inferRuntimeType(
  16412. ctx,
  16413. node.typeParameters.params[0],
  16414. scope
  16415. );
  16416. }
  16417. break;
  16418. }
  16419. }
  16420. break;
  16421. }
  16422. case "TSParenthesizedType":
  16423. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  16424. case "TSUnionType":
  16425. return flattenTypes(ctx, node.types, scope);
  16426. case "TSIntersectionType": {
  16427. return flattenTypes(ctx, node.types, scope).filter(
  16428. (t) => t !== UNKNOWN_TYPE
  16429. );
  16430. }
  16431. case "TSEnumDeclaration":
  16432. return inferEnumType(node);
  16433. case "TSSymbolKeyword":
  16434. return ["Symbol"];
  16435. case "TSIndexedAccessType": {
  16436. const types = resolveIndexType(ctx, node, scope);
  16437. return flattenTypes(ctx, types, scope);
  16438. }
  16439. case "ClassDeclaration":
  16440. return ["Object"];
  16441. case "TSImportType": {
  16442. const sourceScope = importSourceToScope(
  16443. ctx,
  16444. node.argument,
  16445. scope,
  16446. node.argument.value
  16447. );
  16448. const resolved = resolveTypeReference(ctx, node, sourceScope);
  16449. if (resolved) {
  16450. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  16451. }
  16452. break;
  16453. }
  16454. case "TSTypeQuery": {
  16455. const id = node.exprName;
  16456. if (id.type === "Identifier") {
  16457. const matched = scope.declares[id.name];
  16458. if (matched) {
  16459. return inferRuntimeType(ctx, matched, matched._ownerScope);
  16460. }
  16461. }
  16462. break;
  16463. }
  16464. }
  16465. } catch (e) {
  16466. }
  16467. return [UNKNOWN_TYPE];
  16468. }
  16469. function flattenTypes(ctx, types, scope) {
  16470. if (types.length === 1) {
  16471. return inferRuntimeType(ctx, types[0], scope);
  16472. }
  16473. return [
  16474. ...new Set(
  16475. [].concat(
  16476. ...types.map((t) => inferRuntimeType(ctx, t, scope))
  16477. )
  16478. )
  16479. ];
  16480. }
  16481. function inferEnumType(node) {
  16482. const types = /* @__PURE__ */ new Set();
  16483. for (const m of node.members) {
  16484. if (m.initializer) {
  16485. switch (m.initializer.type) {
  16486. case "StringLiteral":
  16487. types.add("String");
  16488. break;
  16489. case "NumericLiteral":
  16490. types.add("Number");
  16491. break;
  16492. }
  16493. }
  16494. }
  16495. return types.size ? [...types] : ["Number"];
  16496. }
  16497. function resolveExtractPropTypes({ props }, scope) {
  16498. const res = { props: {} };
  16499. for (const key in props) {
  16500. const raw = props[key];
  16501. res.props[key] = reverseInferType(
  16502. raw.key,
  16503. raw.typeAnnotation.typeAnnotation,
  16504. scope
  16505. );
  16506. }
  16507. return res;
  16508. }
  16509. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  16510. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  16511. const typeType = findStaticPropertyType(node, "type");
  16512. if (typeType) {
  16513. const requiredType = findStaticPropertyType(node, "required");
  16514. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  16515. return reverseInferType(key, typeType, scope, optional2, false);
  16516. }
  16517. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  16518. if (node.typeName.name.endsWith("Constructor")) {
  16519. return createProperty(
  16520. key,
  16521. ctorToType(node.typeName.name),
  16522. scope,
  16523. optional
  16524. );
  16525. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  16526. return createProperty(key, node.typeParameters.params[0], scope, optional);
  16527. }
  16528. }
  16529. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  16530. for (const t of node.typeParameters.params) {
  16531. const inferred = reverseInferType(key, t, scope, optional);
  16532. if (inferred)
  16533. return inferred;
  16534. }
  16535. }
  16536. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  16537. }
  16538. function ctorToType(ctorType) {
  16539. const ctor = ctorType.slice(0, -11);
  16540. switch (ctor) {
  16541. case "String":
  16542. case "Number":
  16543. case "Boolean":
  16544. return { type: `TS${ctor}Keyword` };
  16545. case "Array":
  16546. case "Function":
  16547. case "Object":
  16548. case "Set":
  16549. case "Map":
  16550. case "WeakSet":
  16551. case "WeakMap":
  16552. case "Date":
  16553. case "Promise":
  16554. return {
  16555. type: "TSTypeReference",
  16556. typeName: { type: "Identifier", name: ctor }
  16557. };
  16558. }
  16559. return { type: `TSNullKeyword` };
  16560. }
  16561. function findStaticPropertyType(node, key) {
  16562. const prop = node.members.find(
  16563. (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation
  16564. );
  16565. return prop && prop.typeAnnotation.typeAnnotation;
  16566. }
  16567. function resolveReturnType(ctx, arg, scope) {
  16568. var _a;
  16569. let resolved = arg;
  16570. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  16571. resolved = resolveTypeReference(ctx, arg, scope);
  16572. }
  16573. if (!resolved)
  16574. return;
  16575. if (resolved.type === "TSFunctionType") {
  16576. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  16577. }
  16578. if (resolved.type === "TSDeclareFunction") {
  16579. return resolved.returnType;
  16580. }
  16581. }
  16582. function resolveUnionType(ctx, node, scope) {
  16583. if (node.type === "TSTypeReference") {
  16584. const resolved = resolveTypeReference(ctx, node, scope);
  16585. if (resolved)
  16586. node = resolved;
  16587. }
  16588. let types;
  16589. if (node.type === "TSUnionType") {
  16590. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  16591. } else {
  16592. types = [node];
  16593. }
  16594. return types;
  16595. }
  16596. const DEFINE_MODEL = "defineModel";
  16597. function processDefineModel(ctx, node, declId) {
  16598. if (!ctx.options.defineModel || !isCallOf(node, DEFINE_MODEL)) {
  16599. return false;
  16600. }
  16601. warnOnce(
  16602. `This project is using defineModel(), which is an experimental feature. It may receive breaking changes or be removed in the future, so use at your own risk.
  16603. To stay updated, follow the RFC at https://github.com/vuejs/rfcs/discussions/503.`
  16604. );
  16605. ctx.hasDefineModelCall = true;
  16606. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  16607. let modelName;
  16608. let options;
  16609. const arg0 = node.arguments[0] && unwrapTSNode(node.arguments[0]);
  16610. if (arg0 && arg0.type === "StringLiteral") {
  16611. modelName = arg0.value;
  16612. options = node.arguments[1];
  16613. } else {
  16614. modelName = "modelValue";
  16615. options = arg0;
  16616. }
  16617. if (ctx.modelDecls[modelName]) {
  16618. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  16619. }
  16620. const optionsString = options && ctx.getString(options);
  16621. ctx.modelDecls[modelName] = {
  16622. type,
  16623. options: optionsString,
  16624. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  16625. };
  16626. ctx.bindingMetadata[modelName] = "props";
  16627. let runtimeOptions = "";
  16628. if (options) {
  16629. if (options.type === "ObjectExpression") {
  16630. const local = options.properties.find(
  16631. (p) => p.type === "ObjectProperty" && (p.key.type === "Identifier" && p.key.name === "local" || p.key.type === "StringLiteral" && p.key.value === "local")
  16632. );
  16633. if (local) {
  16634. runtimeOptions = `{ ${ctx.getString(local)} }`;
  16635. } else {
  16636. for (const p of options.properties) {
  16637. if (p.type === "SpreadElement" || p.computed) {
  16638. runtimeOptions = optionsString;
  16639. break;
  16640. }
  16641. }
  16642. }
  16643. } else {
  16644. runtimeOptions = optionsString;
  16645. }
  16646. }
  16647. ctx.s.overwrite(
  16648. ctx.startOffset + node.start,
  16649. ctx.startOffset + node.end,
  16650. `${ctx.helper("useModel")}(__props, ${JSON.stringify(modelName)}${runtimeOptions ? `, ${runtimeOptions}` : ``})`
  16651. );
  16652. return true;
  16653. }
  16654. function genModelProps(ctx) {
  16655. if (!ctx.hasDefineModelCall)
  16656. return;
  16657. const isProd = !!ctx.options.isProd;
  16658. let modelPropsDecl = "";
  16659. for (const [name, { type, options }] of Object.entries(ctx.modelDecls)) {
  16660. let skipCheck = false;
  16661. let runtimeTypes = type && inferRuntimeType(ctx, type);
  16662. if (runtimeTypes) {
  16663. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  16664. runtimeTypes = runtimeTypes.filter((el) => {
  16665. if (el === UNKNOWN_TYPE)
  16666. return false;
  16667. return isProd ? el === "Boolean" || el === "Function" && options : true;
  16668. });
  16669. skipCheck = !isProd && hasUnknownType && runtimeTypes.length > 0;
  16670. }
  16671. let runtimeType = runtimeTypes && runtimeTypes.length > 0 && toRuntimeTypeString(runtimeTypes) || void 0;
  16672. const codegenOptions = concatStrings([
  16673. runtimeType && `type: ${runtimeType}`,
  16674. skipCheck && "skipCheck: true"
  16675. ]);
  16676. let decl;
  16677. if (runtimeType && options) {
  16678. decl = ctx.isTS ? `{ ${codegenOptions}, ...${options} }` : `Object.assign({ ${codegenOptions} }, ${options})`;
  16679. } else {
  16680. decl = options || (runtimeType ? `{ ${codegenOptions} }` : "{}");
  16681. }
  16682. modelPropsDecl += `
  16683. ${JSON.stringify(name)}: ${decl},`;
  16684. }
  16685. return `{${modelPropsDecl}
  16686. }`;
  16687. }
  16688. const DEFINE_PROPS = "defineProps";
  16689. const WITH_DEFAULTS = "withDefaults";
  16690. function processDefineProps(ctx, node, declId) {
  16691. if (!isCallOf(node, DEFINE_PROPS)) {
  16692. return processWithDefaults(ctx, node, declId);
  16693. }
  16694. if (ctx.hasDefinePropsCall) {
  16695. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  16696. }
  16697. ctx.hasDefinePropsCall = true;
  16698. ctx.propsRuntimeDecl = node.arguments[0];
  16699. if (ctx.propsRuntimeDecl) {
  16700. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  16701. if (!(key in ctx.bindingMetadata)) {
  16702. ctx.bindingMetadata[key] = "props";
  16703. }
  16704. }
  16705. }
  16706. if (node.typeParameters) {
  16707. if (ctx.propsRuntimeDecl) {
  16708. ctx.error(
  16709. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  16710. node
  16711. );
  16712. }
  16713. ctx.propsTypeDecl = node.typeParameters.params[0];
  16714. }
  16715. if (declId) {
  16716. if (declId.type === "ObjectPattern") {
  16717. processPropsDestructure(ctx, declId);
  16718. } else {
  16719. ctx.propsIdentifier = ctx.getString(declId);
  16720. }
  16721. }
  16722. return true;
  16723. }
  16724. function processWithDefaults(ctx, node, declId) {
  16725. if (!isCallOf(node, WITH_DEFAULTS)) {
  16726. return false;
  16727. }
  16728. if (processDefineProps(ctx, node.arguments[0], declId)) {
  16729. if (ctx.propsRuntimeDecl) {
  16730. ctx.error(
  16731. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  16732. node
  16733. );
  16734. }
  16735. if (ctx.propsDestructureDecl) {
  16736. ctx.error(
  16737. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  16738. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`,
  16739. node.callee
  16740. );
  16741. }
  16742. ctx.propsRuntimeDefaults = node.arguments[1];
  16743. if (!ctx.propsRuntimeDefaults) {
  16744. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  16745. }
  16746. } else {
  16747. ctx.error(
  16748. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  16749. node.arguments[0] || node
  16750. );
  16751. }
  16752. return true;
  16753. }
  16754. function genRuntimeProps(ctx) {
  16755. let propsDecls;
  16756. if (ctx.propsRuntimeDecl) {
  16757. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  16758. if (ctx.propsDestructureDecl) {
  16759. const defaults = [];
  16760. for (const key in ctx.propsDestructuredBindings) {
  16761. const d = genDestructuredDefaultValue(ctx, key);
  16762. const finalKey = getEscapedKey(key);
  16763. if (d)
  16764. defaults.push(
  16765. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  16766. );
  16767. }
  16768. if (defaults.length) {
  16769. propsDecls = `${ctx.helper(
  16770. `mergeDefaults`
  16771. )}(${propsDecls}, {
  16772. ${defaults.join(",\n ")}
  16773. })`;
  16774. }
  16775. }
  16776. } else if (ctx.propsTypeDecl) {
  16777. propsDecls = genRuntimePropsFromTypes(ctx);
  16778. }
  16779. const modelsDecls = genModelProps(ctx);
  16780. if (propsDecls && modelsDecls) {
  16781. return `${ctx.helper("mergeModels")}(${propsDecls}, ${modelsDecls})`;
  16782. } else {
  16783. return modelsDecls || propsDecls;
  16784. }
  16785. }
  16786. function genRuntimePropsFromTypes(ctx) {
  16787. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  16788. if (!props.length) {
  16789. return;
  16790. }
  16791. const propStrings = [];
  16792. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  16793. for (const prop of props) {
  16794. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  16795. if (!(prop.key in ctx.bindingMetadata)) {
  16796. ctx.bindingMetadata[prop.key] = "props";
  16797. }
  16798. }
  16799. let propsDecls = `{
  16800. ${propStrings.join(",\n ")}
  16801. }`;
  16802. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  16803. propsDecls = `${ctx.helper("mergeDefaults")}(${propsDecls}, ${ctx.getString(
  16804. ctx.propsRuntimeDefaults
  16805. )})`;
  16806. }
  16807. return propsDecls;
  16808. }
  16809. function resolveRuntimePropsFromType(ctx, node) {
  16810. const props = [];
  16811. const elements = resolveTypeElements(ctx, node);
  16812. for (const key in elements.props) {
  16813. const e = elements.props[key];
  16814. let type = inferRuntimeType(ctx, e);
  16815. let skipCheck = false;
  16816. if (type.includes(UNKNOWN_TYPE)) {
  16817. if (type.includes("Boolean") || type.includes("Function")) {
  16818. type = type.filter((t) => t !== UNKNOWN_TYPE);
  16819. skipCheck = true;
  16820. } else {
  16821. type = ["null"];
  16822. }
  16823. }
  16824. props.push({
  16825. key,
  16826. required: !e.optional,
  16827. type: type || [`null`],
  16828. skipCheck
  16829. });
  16830. }
  16831. return props;
  16832. }
  16833. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  16834. let defaultString;
  16835. const destructured = genDestructuredDefaultValue(ctx, key, type);
  16836. if (destructured) {
  16837. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  16838. } else if (hasStaticDefaults) {
  16839. const prop = ctx.propsRuntimeDefaults.properties.find(
  16840. (node) => {
  16841. if (node.type === "SpreadElement")
  16842. return false;
  16843. return resolveObjectKey(node.key, node.computed) === key;
  16844. }
  16845. );
  16846. if (prop) {
  16847. if (prop.type === "ObjectProperty") {
  16848. defaultString = `default: ${ctx.getString(prop.value)}`;
  16849. } else {
  16850. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`;
  16851. }
  16852. }
  16853. }
  16854. const finalKey = getEscapedKey(key);
  16855. if (!ctx.options.isProd) {
  16856. return `${finalKey}: { ${concatStrings([
  16857. `type: ${toRuntimeTypeString(type)}`,
  16858. `required: ${required}`,
  16859. skipCheck && "skipCheck: true",
  16860. defaultString
  16861. ])} }`;
  16862. } else if (type.some(
  16863. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  16864. )) {
  16865. return `${finalKey}: { ${concatStrings([
  16866. `type: ${toRuntimeTypeString(type)}`,
  16867. defaultString
  16868. ])} }`;
  16869. } else {
  16870. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  16871. }
  16872. }
  16873. function hasStaticWithDefaults(ctx) {
  16874. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  16875. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  16876. ));
  16877. }
  16878. function genDestructuredDefaultValue(ctx, key, inferredType) {
  16879. const destructured = ctx.propsDestructuredBindings[key];
  16880. const defaultVal = destructured && destructured.default;
  16881. if (defaultVal) {
  16882. const value = ctx.getString(defaultVal);
  16883. const unwrapped = unwrapTSNode(defaultVal);
  16884. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  16885. const valueType = inferValueType(unwrapped);
  16886. if (valueType && !inferredType.includes(valueType)) {
  16887. ctx.error(
  16888. `Default value of prop "${key}" does not match declared type.`,
  16889. unwrapped
  16890. );
  16891. }
  16892. }
  16893. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  16894. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  16895. return {
  16896. valueString: needFactoryWrap ? `() => (${value})` : value,
  16897. needSkipFactory
  16898. };
  16899. }
  16900. }
  16901. function inferValueType(node) {
  16902. switch (node.type) {
  16903. case "StringLiteral":
  16904. return "String";
  16905. case "NumericLiteral":
  16906. return "Number";
  16907. case "BooleanLiteral":
  16908. return "Boolean";
  16909. case "ObjectExpression":
  16910. return "Object";
  16911. case "ArrayExpression":
  16912. return "Array";
  16913. case "FunctionExpression":
  16914. case "ArrowFunctionExpression":
  16915. return "Function";
  16916. }
  16917. }
  16918. function processPropsDestructure(ctx, declId) {
  16919. if (!ctx.options.propsDestructure && !ctx.options.reactivityTransform) {
  16920. ctx.propsIdentifier = ctx.getString(declId);
  16921. return;
  16922. }
  16923. warnOnce(
  16924. `This project is using reactive props destructure, which is an experimental feature. It may receive breaking changes or be removed in the future, so use at your own risk.
  16925. To stay updated, follow the RFC at https://github.com/vuejs/rfcs/discussions/502.`
  16926. );
  16927. ctx.propsDestructureDecl = declId;
  16928. const registerBinding = (key, local, defaultValue) => {
  16929. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  16930. if (local !== key) {
  16931. ctx.bindingMetadata[local] = "props-aliased";
  16932. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  16933. }
  16934. };
  16935. for (const prop of declId.properties) {
  16936. if (prop.type === "ObjectProperty") {
  16937. const propKey = resolveObjectKey(prop.key, prop.computed);
  16938. if (!propKey) {
  16939. ctx.error(
  16940. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  16941. prop.key
  16942. );
  16943. }
  16944. if (prop.value.type === "AssignmentPattern") {
  16945. const { left, right } = prop.value;
  16946. if (left.type !== "Identifier") {
  16947. ctx.error(
  16948. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  16949. left
  16950. );
  16951. }
  16952. registerBinding(propKey, left.name, right);
  16953. } else if (prop.value.type === "Identifier") {
  16954. registerBinding(propKey, prop.value.name);
  16955. } else {
  16956. ctx.error(
  16957. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  16958. prop.value
  16959. );
  16960. }
  16961. } else {
  16962. ctx.propsDestructureRestId = prop.argument.name;
  16963. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  16964. }
  16965. }
  16966. }
  16967. function transformDestructuredProps(ctx, vueImportAliases) {
  16968. if (!ctx.options.propsDestructure && !ctx.options.reactivityTransform) {
  16969. return;
  16970. }
  16971. const rootScope = {};
  16972. const scopeStack = [rootScope];
  16973. let currentScope = rootScope;
  16974. const excludedIds = /* @__PURE__ */ new WeakSet();
  16975. const parentStack = [];
  16976. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  16977. for (const key in ctx.propsDestructuredBindings) {
  16978. const { local } = ctx.propsDestructuredBindings[key];
  16979. rootScope[local] = true;
  16980. propsLocalToPublicMap[local] = key;
  16981. }
  16982. function pushScope() {
  16983. scopeStack.push(currentScope = Object.create(currentScope));
  16984. }
  16985. function popScope() {
  16986. scopeStack.pop();
  16987. currentScope = scopeStack[scopeStack.length - 1] || null;
  16988. }
  16989. function registerLocalBinding(id) {
  16990. excludedIds.add(id);
  16991. if (currentScope) {
  16992. currentScope[id.name] = false;
  16993. } else {
  16994. ctx.error(
  16995. "registerBinding called without active scope, something is wrong.",
  16996. id
  16997. );
  16998. }
  16999. }
  17000. function walkScope(node, isRoot = false) {
  17001. for (const stmt of node.body) {
  17002. if (stmt.type === "VariableDeclaration") {
  17003. walkVariableDeclaration(stmt, isRoot);
  17004. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  17005. if (stmt.declare || !stmt.id)
  17006. continue;
  17007. registerLocalBinding(stmt.id);
  17008. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  17009. walkVariableDeclaration(stmt.left);
  17010. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  17011. walkVariableDeclaration(stmt.declaration, isRoot);
  17012. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  17013. walkVariableDeclaration(stmt.body, isRoot);
  17014. }
  17015. }
  17016. }
  17017. function walkVariableDeclaration(stmt, isRoot = false) {
  17018. if (stmt.declare) {
  17019. return;
  17020. }
  17021. for (const decl of stmt.declarations) {
  17022. const isDefineProps = isRoot && decl.init && isCallOf(unwrapTSNode(decl.init), "defineProps");
  17023. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  17024. if (isDefineProps) {
  17025. excludedIds.add(id);
  17026. } else {
  17027. registerLocalBinding(id);
  17028. }
  17029. }
  17030. }
  17031. }
  17032. function rewriteId(id, parent, parentStack2) {
  17033. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  17034. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  17035. }
  17036. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  17037. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  17038. ctx.s.appendLeft(
  17039. id.end + ctx.startOffset,
  17040. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  17041. );
  17042. }
  17043. } else {
  17044. ctx.s.overwrite(
  17045. id.start + ctx.startOffset,
  17046. id.end + ctx.startOffset,
  17047. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  17048. );
  17049. }
  17050. }
  17051. function checkUsage(node, method, alias = method) {
  17052. if (isCallOf(node, alias)) {
  17053. const arg = unwrapTSNode(node.arguments[0]);
  17054. if (arg.type === "Identifier" && currentScope[arg.name]) {
  17055. ctx.error(
  17056. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  17057. arg
  17058. );
  17059. }
  17060. }
  17061. }
  17062. const ast = ctx.scriptSetupAst;
  17063. walkScope(ast, true);
  17064. estreeWalker.walk(ast, {
  17065. enter(node, parent) {
  17066. parent && parentStack.push(parent);
  17067. if (parent && parent.type.startsWith("TS") && parent.type !== "TSAsExpression" && parent.type !== "TSNonNullExpression" && parent.type !== "TSTypeAssertion") {
  17068. return this.skip();
  17069. }
  17070. checkUsage(node, "watch", vueImportAliases.watch);
  17071. checkUsage(node, "toRef", vueImportAliases.toRef);
  17072. if (CompilerDOM.isFunctionType(node)) {
  17073. pushScope();
  17074. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  17075. if (node.body.type === "BlockStatement") {
  17076. walkScope(node.body);
  17077. }
  17078. return;
  17079. }
  17080. if (node.type === "CatchClause") {
  17081. pushScope();
  17082. if (node.param && node.param.type === "Identifier") {
  17083. registerLocalBinding(node.param);
  17084. }
  17085. walkScope(node.body);
  17086. return;
  17087. }
  17088. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  17089. pushScope();
  17090. walkScope(node);
  17091. return;
  17092. }
  17093. if (node.type === "Identifier") {
  17094. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  17095. if (currentScope[node.name]) {
  17096. rewriteId(node, parent, parentStack);
  17097. }
  17098. }
  17099. }
  17100. },
  17101. leave(node, parent) {
  17102. parent && parentStack.pop();
  17103. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node)) {
  17104. popScope();
  17105. }
  17106. }
  17107. });
  17108. }
  17109. const DEFINE_EMITS = "defineEmits";
  17110. function processDefineEmits(ctx, node, declId) {
  17111. if (!isCallOf(node, DEFINE_EMITS)) {
  17112. return false;
  17113. }
  17114. if (ctx.hasDefineEmitCall) {
  17115. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  17116. }
  17117. ctx.hasDefineEmitCall = true;
  17118. ctx.emitsRuntimeDecl = node.arguments[0];
  17119. if (node.typeParameters) {
  17120. if (ctx.emitsRuntimeDecl) {
  17121. ctx.error(
  17122. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  17123. node
  17124. );
  17125. }
  17126. ctx.emitsTypeDecl = node.typeParameters.params[0];
  17127. }
  17128. if (declId) {
  17129. ctx.emitIdentifier = declId.type === "Identifier" ? declId.name : ctx.getString(declId);
  17130. }
  17131. return true;
  17132. }
  17133. function genRuntimeEmits(ctx) {
  17134. let emitsDecl = "";
  17135. if (ctx.emitsRuntimeDecl) {
  17136. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  17137. } else if (ctx.emitsTypeDecl) {
  17138. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  17139. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  17140. }
  17141. if (ctx.hasDefineModelCall) {
  17142. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  17143. emitsDecl = emitsDecl ? `${ctx.helper("mergeModels")}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  17144. }
  17145. return emitsDecl;
  17146. }
  17147. function extractRuntimeEmits(ctx) {
  17148. const emits = /* @__PURE__ */ new Set();
  17149. const node = ctx.emitsTypeDecl;
  17150. if (node.type === "TSFunctionType") {
  17151. extractEventNames(ctx, node.parameters[0], emits);
  17152. return emits;
  17153. }
  17154. const { props, calls } = resolveTypeElements(ctx, node);
  17155. let hasProperty = false;
  17156. for (const key in props) {
  17157. emits.add(key);
  17158. hasProperty = true;
  17159. }
  17160. if (calls) {
  17161. if (hasProperty) {
  17162. ctx.error(
  17163. `defineEmits() type cannot mixed call signature and property syntax.`,
  17164. node
  17165. );
  17166. }
  17167. for (const call of calls) {
  17168. extractEventNames(ctx, call.parameters[0], emits);
  17169. }
  17170. }
  17171. return emits;
  17172. }
  17173. function extractEventNames(ctx, eventName, emits) {
  17174. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  17175. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  17176. for (const type of types) {
  17177. if (type.type === "TSLiteralType") {
  17178. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  17179. emits.add(String(type.literal.value));
  17180. }
  17181. }
  17182. }
  17183. }
  17184. }
  17185. const DEFINE_EXPOSE = "defineExpose";
  17186. function processDefineExpose(ctx, node) {
  17187. if (isCallOf(node, DEFINE_EXPOSE)) {
  17188. if (ctx.hasDefineExposeCall) {
  17189. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  17190. }
  17191. ctx.hasDefineExposeCall = true;
  17192. return true;
  17193. }
  17194. return false;
  17195. }
  17196. const DEFINE_SLOTS = "defineSlots";
  17197. function processDefineSlots(ctx, node, declId) {
  17198. if (!isCallOf(node, DEFINE_SLOTS)) {
  17199. return false;
  17200. }
  17201. if (ctx.hasDefineSlotsCall) {
  17202. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  17203. }
  17204. ctx.hasDefineSlotsCall = true;
  17205. if (node.arguments.length > 0) {
  17206. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  17207. }
  17208. if (declId) {
  17209. ctx.s.overwrite(
  17210. ctx.startOffset + node.start,
  17211. ctx.startOffset + node.end,
  17212. `${ctx.helper("useSlots")}()`
  17213. );
  17214. }
  17215. return true;
  17216. }
  17217. const DEFINE_OPTIONS = "defineOptions";
  17218. function processDefineOptions(ctx, node) {
  17219. if (!isCallOf(node, DEFINE_OPTIONS)) {
  17220. return false;
  17221. }
  17222. if (ctx.hasDefineOptionsCall) {
  17223. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  17224. }
  17225. if (node.typeParameters) {
  17226. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  17227. }
  17228. if (!node.arguments[0])
  17229. return true;
  17230. ctx.hasDefineOptionsCall = true;
  17231. ctx.optionsRuntimeDecl = unwrapTSNode(node.arguments[0]);
  17232. let propsOption = void 0;
  17233. let emitsOption = void 0;
  17234. let exposeOption = void 0;
  17235. let slotsOption = void 0;
  17236. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  17237. for (const prop of ctx.optionsRuntimeDecl.properties) {
  17238. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  17239. if (prop.key.name === "props")
  17240. propsOption = prop;
  17241. if (prop.key.name === "emits")
  17242. emitsOption = prop;
  17243. if (prop.key.name === "expose")
  17244. exposeOption = prop;
  17245. if (prop.key.name === "slots")
  17246. slotsOption = prop;
  17247. }
  17248. }
  17249. }
  17250. if (propsOption) {
  17251. ctx.error(
  17252. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  17253. propsOption
  17254. );
  17255. }
  17256. if (emitsOption) {
  17257. ctx.error(
  17258. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  17259. emitsOption
  17260. );
  17261. }
  17262. if (exposeOption) {
  17263. ctx.error(
  17264. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  17265. exposeOption
  17266. );
  17267. }
  17268. if (slotsOption) {
  17269. ctx.error(
  17270. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  17271. slotsOption
  17272. );
  17273. }
  17274. return true;
  17275. }
  17276. function processAwait(ctx, node, needSemi, isStatement) {
  17277. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  17278. const startOffset = ctx.startOffset;
  17279. const argumentStr = ctx.descriptor.source.slice(
  17280. argumentStart + startOffset,
  17281. node.argument.end + startOffset
  17282. );
  17283. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  17284. ctx.s.overwrite(
  17285. node.start + startOffset,
  17286. argumentStart + startOffset,
  17287. `${needSemi ? `;` : ``}(
  17288. ([__temp,__restore] = ${ctx.helper(
  17289. `withAsyncContext`
  17290. )}(${containsNestedAwait ? `async ` : ``}() => `
  17291. );
  17292. ctx.s.appendLeft(
  17293. node.end + startOffset,
  17294. `)),
  17295. ${isStatement ? `` : `__temp = `}await __temp,
  17296. __restore()${isStatement ? `` : `,
  17297. __temp`}
  17298. )`
  17299. );
  17300. }
  17301. function compileScript(sfc, options) {
  17302. var _a;
  17303. if (!options.id) {
  17304. warnOnce(
  17305. `compileScript now requires passing the \`id\` option.
  17306. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  17307. );
  17308. }
  17309. const ctx = new ScriptCompileContext(sfc, options);
  17310. const { script, scriptSetup, source, filename } = sfc;
  17311. const hoistStatic = options.hoistStatic !== false && !script;
  17312. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  17313. const scriptLang = script && script.lang;
  17314. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  17315. const enableReactivityTransform = !!options.reactivityTransform;
  17316. let refBindings;
  17317. if (!scriptSetup) {
  17318. if (!script) {
  17319. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  17320. }
  17321. return processNormalScript(ctx, scopeId);
  17322. }
  17323. if (script && scriptLang !== scriptSetupLang) {
  17324. throw new Error(
  17325. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  17326. );
  17327. }
  17328. if (scriptSetupLang && !ctx.isJS && !ctx.isTS) {
  17329. return scriptSetup;
  17330. }
  17331. const scriptBindings = /* @__PURE__ */ Object.create(null);
  17332. const setupBindings = /* @__PURE__ */ Object.create(null);
  17333. let defaultExport;
  17334. let hasAwait = false;
  17335. let hasInlinedSsrRenderFn = false;
  17336. const startOffset = ctx.startOffset;
  17337. const endOffset = ctx.endOffset;
  17338. const scriptStartOffset = script && script.loc.start.offset;
  17339. const scriptEndOffset = script && script.loc.end.offset;
  17340. function hoistNode(node) {
  17341. const start = node.start + startOffset;
  17342. let end = node.end + startOffset;
  17343. if (node.trailingComments && node.trailingComments.length > 0) {
  17344. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  17345. end = lastCommentNode.end + startOffset;
  17346. }
  17347. while (end <= source.length) {
  17348. if (!/\s/.test(source.charAt(end))) {
  17349. break;
  17350. }
  17351. end++;
  17352. }
  17353. ctx.s.move(start, end, 0);
  17354. }
  17355. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  17356. let isUsedInTemplate = needTemplateUsageCheck;
  17357. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  17358. isUsedInTemplate = isImportUsed(local, sfc);
  17359. }
  17360. ctx.userImports[local] = {
  17361. isType,
  17362. imported,
  17363. local,
  17364. source: source2,
  17365. isFromSetup,
  17366. isUsedInTemplate
  17367. };
  17368. }
  17369. function checkInvalidScopeReference(node, method) {
  17370. if (!node)
  17371. return;
  17372. CompilerDOM.walkIdentifiers(node, (id) => {
  17373. const binding = setupBindings[id.name];
  17374. if (binding && binding !== "literal-const") {
  17375. ctx.error(
  17376. `\`${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.`,
  17377. id
  17378. );
  17379. }
  17380. });
  17381. }
  17382. const scriptAst = ctx.scriptAst;
  17383. const scriptSetupAst = ctx.scriptSetupAst;
  17384. if (scriptAst) {
  17385. for (const node of scriptAst.body) {
  17386. if (node.type === "ImportDeclaration") {
  17387. for (const specifier of node.specifiers) {
  17388. const imported = getImportedName(specifier);
  17389. registerUserImport(
  17390. node.source.value,
  17391. specifier.local.name,
  17392. imported,
  17393. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  17394. false,
  17395. !options.inlineTemplate
  17396. );
  17397. }
  17398. }
  17399. }
  17400. }
  17401. for (const node of scriptSetupAst.body) {
  17402. if (node.type === "ImportDeclaration") {
  17403. hoistNode(node);
  17404. let removed = 0;
  17405. const removeSpecifier = (i) => {
  17406. const removeLeft = i > removed;
  17407. removed++;
  17408. const current = node.specifiers[i];
  17409. const next = node.specifiers[i + 1];
  17410. ctx.s.remove(
  17411. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  17412. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  17413. );
  17414. };
  17415. for (let i = 0; i < node.specifiers.length; i++) {
  17416. const specifier = node.specifiers[i];
  17417. const local = specifier.local.name;
  17418. const imported = getImportedName(specifier);
  17419. const source2 = node.source.value;
  17420. const existing = ctx.userImports[local];
  17421. if (source2 === "vue" && (imported === DEFINE_PROPS || imported === DEFINE_EMITS || imported === DEFINE_EXPOSE)) {
  17422. warnOnce(
  17423. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  17424. );
  17425. removeSpecifier(i);
  17426. } else if (existing) {
  17427. if (existing.source === source2 && existing.imported === imported) {
  17428. removeSpecifier(i);
  17429. } else {
  17430. ctx.error(
  17431. `different imports aliased to same local name.`,
  17432. specifier
  17433. );
  17434. }
  17435. } else {
  17436. registerUserImport(
  17437. source2,
  17438. local,
  17439. imported,
  17440. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  17441. true,
  17442. !options.inlineTemplate
  17443. );
  17444. }
  17445. }
  17446. if (node.specifiers.length && removed === node.specifiers.length) {
  17447. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  17448. }
  17449. }
  17450. }
  17451. const vueImportAliases = {};
  17452. for (const key in ctx.userImports) {
  17453. const { source: source2, imported, local } = ctx.userImports[key];
  17454. if (source2 === "vue")
  17455. vueImportAliases[imported] = local;
  17456. }
  17457. if (script && scriptAst) {
  17458. for (const node of scriptAst.body) {
  17459. if (node.type === "ExportDefaultDeclaration") {
  17460. defaultExport = node;
  17461. let optionProperties;
  17462. if (defaultExport.declaration.type === "ObjectExpression") {
  17463. optionProperties = defaultExport.declaration.properties;
  17464. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  17465. optionProperties = defaultExport.declaration.arguments[0].properties;
  17466. }
  17467. if (optionProperties) {
  17468. for (const p of optionProperties) {
  17469. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  17470. ctx.hasDefaultExportName = true;
  17471. }
  17472. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  17473. ctx.hasDefaultExportRender = true;
  17474. }
  17475. }
  17476. }
  17477. const start = node.start + scriptStartOffset;
  17478. const end = node.declaration.start + scriptStartOffset;
  17479. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  17480. } else if (node.type === "ExportNamedDeclaration") {
  17481. const defaultSpecifier = node.specifiers.find(
  17482. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  17483. );
  17484. if (defaultSpecifier) {
  17485. defaultExport = node;
  17486. if (node.specifiers.length > 1) {
  17487. ctx.s.remove(
  17488. defaultSpecifier.start + scriptStartOffset,
  17489. defaultSpecifier.end + scriptStartOffset
  17490. );
  17491. } else {
  17492. ctx.s.remove(
  17493. node.start + scriptStartOffset,
  17494. node.end + scriptStartOffset
  17495. );
  17496. }
  17497. if (node.source) {
  17498. ctx.s.prepend(
  17499. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  17500. `
  17501. );
  17502. } else {
  17503. ctx.s.appendLeft(
  17504. scriptEndOffset,
  17505. `
  17506. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  17507. `
  17508. );
  17509. }
  17510. }
  17511. if (node.declaration) {
  17512. walkDeclaration(
  17513. "script",
  17514. node.declaration,
  17515. scriptBindings,
  17516. vueImportAliases,
  17517. hoistStatic
  17518. );
  17519. }
  17520. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  17521. walkDeclaration(
  17522. "script",
  17523. node,
  17524. scriptBindings,
  17525. vueImportAliases,
  17526. hoistStatic
  17527. );
  17528. }
  17529. }
  17530. if (enableReactivityTransform && reactivityTransform.shouldTransform(script.content)) {
  17531. const { rootRefs, importedHelpers } = reactivityTransform.transformAST(
  17532. scriptAst,
  17533. ctx.s,
  17534. scriptStartOffset
  17535. );
  17536. refBindings = rootRefs;
  17537. for (const h of importedHelpers) {
  17538. ctx.helperImports.add(h);
  17539. }
  17540. }
  17541. if (scriptStartOffset > startOffset) {
  17542. if (!/\n$/.test(script.content.trim())) {
  17543. ctx.s.appendLeft(scriptEndOffset, `
  17544. `);
  17545. }
  17546. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  17547. }
  17548. }
  17549. for (const node of scriptSetupAst.body) {
  17550. if (node.type === "ExpressionStatement") {
  17551. const expr = unwrapTSNode(node.expression);
  17552. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  17553. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  17554. } else if (processDefineExpose(ctx, expr)) {
  17555. const callee = expr.callee;
  17556. ctx.s.overwrite(
  17557. callee.start + startOffset,
  17558. callee.end + startOffset,
  17559. "__expose"
  17560. );
  17561. } else {
  17562. processDefineModel(ctx, expr);
  17563. }
  17564. }
  17565. if (node.type === "VariableDeclaration" && !node.declare) {
  17566. const total = node.declarations.length;
  17567. let left = total;
  17568. let lastNonRemoved;
  17569. for (let i = 0; i < total; i++) {
  17570. const decl = node.declarations[i];
  17571. const init = decl.init && unwrapTSNode(decl.init);
  17572. if (init) {
  17573. if (processDefineOptions(ctx, init)) {
  17574. ctx.error(
  17575. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  17576. node
  17577. );
  17578. }
  17579. const isDefineProps = processDefineProps(ctx, init, decl.id);
  17580. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  17581. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  17582. if (isDefineProps || isDefineEmits) {
  17583. if (left === 1) {
  17584. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  17585. } else {
  17586. let start = decl.start + startOffset;
  17587. let end = decl.end + startOffset;
  17588. if (i === total - 1) {
  17589. start = node.declarations[lastNonRemoved].end + startOffset;
  17590. } else {
  17591. end = node.declarations[i + 1].start + startOffset;
  17592. }
  17593. ctx.s.remove(start, end);
  17594. left--;
  17595. }
  17596. } else {
  17597. lastNonRemoved = i;
  17598. }
  17599. }
  17600. }
  17601. }
  17602. let isAllLiteral = false;
  17603. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  17604. isAllLiteral = walkDeclaration(
  17605. "scriptSetup",
  17606. node,
  17607. setupBindings,
  17608. vueImportAliases,
  17609. hoistStatic
  17610. );
  17611. }
  17612. if (hoistStatic && isAllLiteral) {
  17613. hoistNode(node);
  17614. }
  17615. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  17616. const scope = [scriptSetupAst.body];
  17617. estreeWalker.walk(node, {
  17618. enter(child, parent) {
  17619. if (CompilerDOM.isFunctionType(child)) {
  17620. this.skip();
  17621. }
  17622. if (child.type === "BlockStatement") {
  17623. scope.push(child.body);
  17624. }
  17625. if (child.type === "AwaitExpression") {
  17626. hasAwait = true;
  17627. const currentScope = scope[scope.length - 1];
  17628. const needsSemi = currentScope.some((n, i) => {
  17629. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  17630. });
  17631. processAwait(
  17632. ctx,
  17633. child,
  17634. needsSemi,
  17635. parent.type === "ExpressionStatement"
  17636. );
  17637. }
  17638. },
  17639. exit(node2) {
  17640. if (node2.type === "BlockStatement")
  17641. scope.pop();
  17642. }
  17643. });
  17644. }
  17645. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  17646. ctx.error(
  17647. `<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.`,
  17648. node
  17649. );
  17650. }
  17651. if (ctx.isTS) {
  17652. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  17653. if (node.type !== "TSEnumDeclaration") {
  17654. hoistNode(node);
  17655. }
  17656. }
  17657. }
  17658. }
  17659. if (ctx.propsDestructureDecl) {
  17660. transformDestructuredProps(ctx, vueImportAliases);
  17661. }
  17662. if (enableReactivityTransform && // normal <script> had ref bindings that maybe used in <script setup>
  17663. (refBindings || reactivityTransform.shouldTransform(scriptSetup.content))) {
  17664. const { rootRefs, importedHelpers } = reactivityTransform.transformAST(
  17665. scriptSetupAst,
  17666. ctx.s,
  17667. startOffset,
  17668. refBindings
  17669. );
  17670. refBindings = refBindings ? [...refBindings, ...rootRefs] : rootRefs;
  17671. for (const h of importedHelpers) {
  17672. ctx.helperImports.add(h);
  17673. }
  17674. }
  17675. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  17676. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  17677. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  17678. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  17679. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  17680. if (script) {
  17681. if (startOffset < scriptStartOffset) {
  17682. ctx.s.remove(0, startOffset);
  17683. ctx.s.remove(endOffset, scriptStartOffset);
  17684. ctx.s.remove(scriptEndOffset, source.length);
  17685. } else {
  17686. ctx.s.remove(0, scriptStartOffset);
  17687. ctx.s.remove(scriptEndOffset, startOffset);
  17688. ctx.s.remove(endOffset, source.length);
  17689. }
  17690. } else {
  17691. ctx.s.remove(0, startOffset);
  17692. ctx.s.remove(endOffset, source.length);
  17693. }
  17694. if (scriptAst) {
  17695. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  17696. }
  17697. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  17698. ctx.userImports
  17699. )) {
  17700. if (isType)
  17701. continue;
  17702. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  17703. }
  17704. for (const key in scriptBindings) {
  17705. ctx.bindingMetadata[key] = scriptBindings[key];
  17706. }
  17707. for (const key in setupBindings) {
  17708. ctx.bindingMetadata[key] = setupBindings[key];
  17709. }
  17710. if (refBindings) {
  17711. for (const key of refBindings) {
  17712. ctx.bindingMetadata[key] = "setup-ref";
  17713. }
  17714. }
  17715. if (sfc.cssVars.length && // no need to do this when targeting SSR
  17716. !(options.inlineTemplate && ((_a = options.templateOptions) == null ? void 0 : _a.ssr))) {
  17717. ctx.helperImports.add(CSS_VARS_HELPER);
  17718. ctx.helperImports.add("unref");
  17719. ctx.s.prependLeft(
  17720. startOffset,
  17721. `
  17722. ${genCssVarsCode(
  17723. sfc.cssVars,
  17724. ctx.bindingMetadata,
  17725. scopeId,
  17726. !!options.isProd
  17727. )}
  17728. `
  17729. );
  17730. }
  17731. let args = `__props`;
  17732. if (ctx.propsTypeDecl) {
  17733. args += `: any`;
  17734. }
  17735. if (ctx.propsIdentifier) {
  17736. ctx.s.prependLeft(
  17737. startOffset,
  17738. `
  17739. const ${ctx.propsIdentifier} = __props;
  17740. `
  17741. );
  17742. }
  17743. if (ctx.propsDestructureRestId) {
  17744. ctx.s.prependLeft(
  17745. startOffset,
  17746. `
  17747. const ${ctx.propsDestructureRestId} = ${ctx.helper(
  17748. `createPropsRestProxy`
  17749. )}(__props, ${JSON.stringify(
  17750. Object.keys(ctx.propsDestructuredBindings)
  17751. )});
  17752. `
  17753. );
  17754. }
  17755. if (hasAwait) {
  17756. const any = ctx.isTS ? `: any` : ``;
  17757. ctx.s.prependLeft(startOffset, `
  17758. let __temp${any}, __restore${any}
  17759. `);
  17760. }
  17761. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  17762. if (ctx.emitIdentifier) {
  17763. destructureElements.push(
  17764. ctx.emitIdentifier === `emit` ? `emit` : `emit: ${ctx.emitIdentifier}`
  17765. );
  17766. }
  17767. if (destructureElements.length) {
  17768. args += `, { ${destructureElements.join(", ")} }`;
  17769. }
  17770. let returned;
  17771. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  17772. const allBindings = {
  17773. ...scriptBindings,
  17774. ...setupBindings
  17775. };
  17776. for (const key in ctx.userImports) {
  17777. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  17778. allBindings[key] = true;
  17779. }
  17780. }
  17781. returned = `{ `;
  17782. for (const key in allBindings) {
  17783. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  17784. returned += `get ${key}() { return ${key} }, `;
  17785. } else if (ctx.bindingMetadata[key] === "setup-let") {
  17786. const setArg = key === "v" ? `_v` : `v`;
  17787. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  17788. } else {
  17789. returned += `${key}, `;
  17790. }
  17791. }
  17792. returned = returned.replace(/, $/, "") + ` }`;
  17793. } else {
  17794. if (sfc.template && !sfc.template.src) {
  17795. if (options.templateOptions && options.templateOptions.ssr) {
  17796. hasInlinedSsrRenderFn = true;
  17797. }
  17798. const { code, ast, preamble, tips, errors } = compileTemplate({
  17799. filename,
  17800. source: sfc.template.content,
  17801. inMap: sfc.template.map,
  17802. ...options.templateOptions,
  17803. id: scopeId,
  17804. scoped: sfc.styles.some((s) => s.scoped),
  17805. isProd: options.isProd,
  17806. ssrCssVars: sfc.cssVars,
  17807. compilerOptions: {
  17808. ...options.templateOptions && options.templateOptions.compilerOptions,
  17809. inline: true,
  17810. isTS: ctx.isTS,
  17811. bindingMetadata: ctx.bindingMetadata
  17812. }
  17813. });
  17814. if (tips.length) {
  17815. tips.forEach(warnOnce);
  17816. }
  17817. const err = errors[0];
  17818. if (typeof err === "string") {
  17819. throw new Error(err);
  17820. } else if (err) {
  17821. if (err.loc) {
  17822. err.message += `
  17823. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  17824. source,
  17825. err.loc.start.offset,
  17826. err.loc.end.offset
  17827. ) + `
  17828. `;
  17829. }
  17830. throw err;
  17831. }
  17832. if (preamble) {
  17833. ctx.s.prepend(preamble);
  17834. }
  17835. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  17836. ctx.helperImports.delete("unref");
  17837. }
  17838. returned = code;
  17839. } else {
  17840. returned = `() => {}`;
  17841. }
  17842. }
  17843. if (!options.inlineTemplate && true) {
  17844. ctx.s.appendRight(
  17845. endOffset,
  17846. `
  17847. const __returned__ = ${returned}
  17848. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  17849. return __returned__
  17850. }
  17851. `
  17852. );
  17853. } else {
  17854. ctx.s.appendRight(endOffset, `
  17855. return ${returned}
  17856. }
  17857. `);
  17858. }
  17859. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  17860. let runtimeOptions = ``;
  17861. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  17862. const match = filename.match(/([^/\\]+)\.\w+$/);
  17863. if (match) {
  17864. runtimeOptions += `
  17865. __name: '${match[1]}',`;
  17866. }
  17867. }
  17868. if (hasInlinedSsrRenderFn) {
  17869. runtimeOptions += `
  17870. __ssrInlineRender: true,`;
  17871. }
  17872. const propsDecl = genRuntimeProps(ctx);
  17873. if (propsDecl)
  17874. runtimeOptions += `
  17875. props: ${propsDecl},`;
  17876. const emitsDecl = genRuntimeEmits(ctx);
  17877. if (emitsDecl)
  17878. runtimeOptions += `
  17879. emits: ${emitsDecl},`;
  17880. let definedOptions = "";
  17881. if (ctx.optionsRuntimeDecl) {
  17882. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  17883. }
  17884. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  17885. `;
  17886. if (ctx.isTS) {
  17887. const def = (defaultExport ? `
  17888. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  17889. ...${definedOptions},` : "");
  17890. ctx.s.prependLeft(
  17891. startOffset,
  17892. `
  17893. ${genDefaultAs} /*#__PURE__*/${ctx.helper(
  17894. `defineComponent`
  17895. )}({${def}${runtimeOptions}
  17896. ${hasAwait ? `async ` : ``}setup(${args}) {
  17897. ${exposeCall}`
  17898. );
  17899. ctx.s.appendRight(endOffset, `})`);
  17900. } else {
  17901. if (defaultExport || definedOptions) {
  17902. ctx.s.prependLeft(
  17903. startOffset,
  17904. `
  17905. ${genDefaultAs} /*#__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  17906. ${hasAwait ? `async ` : ``}setup(${args}) {
  17907. ${exposeCall}`
  17908. );
  17909. ctx.s.appendRight(endOffset, `})`);
  17910. } else {
  17911. ctx.s.prependLeft(
  17912. startOffset,
  17913. `
  17914. ${genDefaultAs} {${runtimeOptions}
  17915. ${hasAwait ? `async ` : ``}setup(${args}) {
  17916. ${exposeCall}`
  17917. );
  17918. ctx.s.appendRight(endOffset, `}`);
  17919. }
  17920. }
  17921. if (ctx.helperImports.size > 0) {
  17922. ctx.s.prepend(
  17923. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from 'vue'
  17924. `
  17925. );
  17926. }
  17927. ctx.s.trim();
  17928. return {
  17929. ...scriptSetup,
  17930. bindings: ctx.bindingMetadata,
  17931. imports: ctx.userImports,
  17932. content: ctx.s.toString(),
  17933. map: options.sourceMap !== false ? ctx.s.generateMap({
  17934. source: filename,
  17935. hires: true,
  17936. includeContent: true
  17937. }) : void 0,
  17938. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  17939. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  17940. deps: ctx.deps ? [...ctx.deps] : void 0
  17941. };
  17942. }
  17943. function registerBinding(bindings, node, type) {
  17944. bindings[node.name] = type;
  17945. }
  17946. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic) {
  17947. let isAllLiteral = false;
  17948. if (node.type === "VariableDeclaration") {
  17949. const isConst = node.kind === "const";
  17950. isAllLiteral = isConst && node.declarations.every(
  17951. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  17952. );
  17953. for (const { id, init: _init } of node.declarations) {
  17954. const init = _init && unwrapTSNode(_init);
  17955. const isDefineCall = !!(isConst && isCallOf(
  17956. init,
  17957. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS
  17958. ));
  17959. if (id.type === "Identifier") {
  17960. let bindingType;
  17961. const userReactiveBinding = userImportAliases["reactive"];
  17962. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  17963. bindingType = "literal-const";
  17964. } else if (isCallOf(init, userReactiveBinding)) {
  17965. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  17966. } else if (
  17967. // if a declaration is a const literal, we can mark it so that
  17968. // the generated render fn code doesn't need to unref() it
  17969. isDefineCall || isConst && canNeverBeRef(init, userReactiveBinding)
  17970. ) {
  17971. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  17972. } else if (isConst) {
  17973. if (isCallOf(
  17974. init,
  17975. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === DEFINE_MODEL
  17976. )) {
  17977. bindingType = "setup-ref";
  17978. } else {
  17979. bindingType = "setup-maybe-ref";
  17980. }
  17981. } else {
  17982. bindingType = "setup-let";
  17983. }
  17984. registerBinding(bindings, id, bindingType);
  17985. } else {
  17986. if (isCallOf(init, DEFINE_PROPS)) {
  17987. continue;
  17988. }
  17989. if (id.type === "ObjectPattern") {
  17990. walkObjectPattern(id, bindings, isConst, isDefineCall);
  17991. } else if (id.type === "ArrayPattern") {
  17992. walkArrayPattern(id, bindings, isConst, isDefineCall);
  17993. }
  17994. }
  17995. }
  17996. } else if (node.type === "TSEnumDeclaration") {
  17997. isAllLiteral = node.members.every(
  17998. (member) => !member.initializer || isStaticNode(member.initializer)
  17999. );
  18000. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  18001. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  18002. bindings[node.id.name] = "setup-const";
  18003. }
  18004. return isAllLiteral;
  18005. }
  18006. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  18007. for (const p of node.properties) {
  18008. if (p.type === "ObjectProperty") {
  18009. if (p.key.type === "Identifier" && p.key === p.value) {
  18010. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  18011. registerBinding(bindings, p.key, type);
  18012. } else {
  18013. walkPattern(p.value, bindings, isConst, isDefineCall);
  18014. }
  18015. } else {
  18016. const type = isConst ? "setup-const" : "setup-let";
  18017. registerBinding(bindings, p.argument, type);
  18018. }
  18019. }
  18020. }
  18021. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  18022. for (const e of node.elements) {
  18023. e && walkPattern(e, bindings, isConst, isDefineCall);
  18024. }
  18025. }
  18026. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  18027. if (node.type === "Identifier") {
  18028. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  18029. registerBinding(bindings, node, type);
  18030. } else if (node.type === "RestElement") {
  18031. const type = isConst ? "setup-const" : "setup-let";
  18032. registerBinding(bindings, node.argument, type);
  18033. } else if (node.type === "ObjectPattern") {
  18034. walkObjectPattern(node, bindings, isConst);
  18035. } else if (node.type === "ArrayPattern") {
  18036. walkArrayPattern(node, bindings, isConst);
  18037. } else if (node.type === "AssignmentPattern") {
  18038. if (node.left.type === "Identifier") {
  18039. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  18040. registerBinding(bindings, node.left, type);
  18041. } else {
  18042. walkPattern(node.left, bindings, isConst);
  18043. }
  18044. }
  18045. }
  18046. function canNeverBeRef(node, userReactiveImport) {
  18047. if (isCallOf(node, userReactiveImport)) {
  18048. return true;
  18049. }
  18050. switch (node.type) {
  18051. case "UnaryExpression":
  18052. case "BinaryExpression":
  18053. case "ArrayExpression":
  18054. case "ObjectExpression":
  18055. case "FunctionExpression":
  18056. case "ArrowFunctionExpression":
  18057. case "UpdateExpression":
  18058. case "ClassExpression":
  18059. case "TaggedTemplateExpression":
  18060. return true;
  18061. case "SequenceExpression":
  18062. return canNeverBeRef(
  18063. node.expressions[node.expressions.length - 1],
  18064. userReactiveImport
  18065. );
  18066. default:
  18067. if (isLiteralNode(node)) {
  18068. return true;
  18069. }
  18070. return false;
  18071. }
  18072. }
  18073. function isStaticNode(node) {
  18074. node = unwrapTSNode(node);
  18075. switch (node.type) {
  18076. case "UnaryExpression":
  18077. return isStaticNode(node.argument);
  18078. case "LogicalExpression":
  18079. case "BinaryExpression":
  18080. return isStaticNode(node.left) && isStaticNode(node.right);
  18081. case "ConditionalExpression": {
  18082. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  18083. }
  18084. case "SequenceExpression":
  18085. case "TemplateLiteral":
  18086. return node.expressions.every((expr) => isStaticNode(expr));
  18087. case "ParenthesizedExpression":
  18088. return isStaticNode(node.expression);
  18089. case "StringLiteral":
  18090. case "NumericLiteral":
  18091. case "BooleanLiteral":
  18092. case "NullLiteral":
  18093. case "BigIntLiteral":
  18094. return true;
  18095. }
  18096. return false;
  18097. }
  18098. const version = "3.3.4";
  18099. const walk = estreeWalker.walk;
  18100. exports.babelParse = parser$2.parse;
  18101. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  18102. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  18103. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  18104. exports.isStaticProperty = compilerCore.isStaticProperty;
  18105. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  18106. exports.shouldTransformRef = reactivityTransform.shouldTransform;
  18107. exports.transformRef = reactivityTransform.transform;
  18108. exports.transformRefAST = reactivityTransform.transformAST;
  18109. exports.MagicString = MagicString;
  18110. exports.compileScript = compileScript;
  18111. exports.compileStyle = compileStyle;
  18112. exports.compileStyleAsync = compileStyleAsync;
  18113. exports.compileTemplate = compileTemplate;
  18114. exports.inferRuntimeType = inferRuntimeType;
  18115. exports.invalidateTypeCache = invalidateTypeCache;
  18116. exports.parse = parse$2;
  18117. exports.parseCache = parseCache;
  18118. exports.registerTS = registerTS;
  18119. exports.resolveTypeElements = resolveTypeElements;
  18120. exports.rewriteDefault = rewriteDefault;
  18121. exports.rewriteDefaultAST = rewriteDefaultAST;
  18122. exports.version = version;
  18123. exports.walk = walk;