less.cjs.js 374 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716
  1. 'use strict';
  2. var path = require('path');
  3. var url = require('url');
  4. var CloneHelper = require('clone');
  5. var environment = {
  6. encodeBase64: function encodeBase64(str) {
  7. // Avoid Buffer constructor on newer versions of Node.js.
  8. var buffer = Buffer.from ? Buffer.from(str) : new Buffer(str);
  9. return buffer.toString('base64');
  10. },
  11. mimeLookup: function mimeLookup(filename) {
  12. return require('mime').lookup(filename);
  13. },
  14. charsetLookup: function charsetLookup(mime) {
  15. return require('mime').charsets.lookup(mime);
  16. },
  17. getSourceMapGenerator: function getSourceMapGenerator() {
  18. return require('source-map').SourceMapGenerator;
  19. }
  20. };
  21. function _classCallCheck(instance, Constructor) {
  22. if (!(instance instanceof Constructor)) {
  23. throw new TypeError("Cannot call a class as a function");
  24. }
  25. }
  26. function _defineProperties(target, props) {
  27. for (var i = 0; i < props.length; i++) {
  28. var descriptor = props[i];
  29. descriptor.enumerable = descriptor.enumerable || false;
  30. descriptor.configurable = true;
  31. if ("value" in descriptor) descriptor.writable = true;
  32. Object.defineProperty(target, descriptor.key, descriptor);
  33. }
  34. }
  35. function _createClass(Constructor, protoProps, staticProps) {
  36. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  37. if (staticProps) _defineProperties(Constructor, staticProps);
  38. return Constructor;
  39. }
  40. function _inherits(subClass, superClass) {
  41. if (typeof superClass !== "function" && superClass !== null) {
  42. throw new TypeError("Super expression must either be null or a function");
  43. }
  44. subClass.prototype = Object.create(superClass && superClass.prototype, {
  45. constructor: {
  46. value: subClass,
  47. writable: true,
  48. configurable: true
  49. }
  50. });
  51. if (superClass) _setPrototypeOf(subClass, superClass);
  52. }
  53. function _getPrototypeOf(o) {
  54. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  55. return o.__proto__ || Object.getPrototypeOf(o);
  56. };
  57. return _getPrototypeOf(o);
  58. }
  59. function _setPrototypeOf(o, p) {
  60. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  61. o.__proto__ = p;
  62. return o;
  63. };
  64. return _setPrototypeOf(o, p);
  65. }
  66. function isNativeReflectConstruct() {
  67. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  68. if (Reflect.construct.sham) return false;
  69. if (typeof Proxy === "function") return true;
  70. try {
  71. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  72. return true;
  73. } catch (e) {
  74. return false;
  75. }
  76. }
  77. function _construct(Parent, args, Class) {
  78. if (isNativeReflectConstruct()) {
  79. _construct = Reflect.construct;
  80. } else {
  81. _construct = function _construct(Parent, args, Class) {
  82. var a = [null];
  83. a.push.apply(a, args);
  84. var Constructor = Function.bind.apply(Parent, a);
  85. var instance = new Constructor();
  86. if (Class) _setPrototypeOf(instance, Class.prototype);
  87. return instance;
  88. };
  89. }
  90. return _construct.apply(null, arguments);
  91. }
  92. function _assertThisInitialized(self) {
  93. if (self === void 0) {
  94. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  95. }
  96. return self;
  97. }
  98. function _possibleConstructorReturn(self, call) {
  99. if (call && (typeof call === "object" || typeof call === "function")) {
  100. return call;
  101. }
  102. return _assertThisInitialized(self);
  103. }
  104. function _toConsumableArray(arr) {
  105. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
  106. }
  107. function _arrayWithoutHoles(arr) {
  108. if (Array.isArray(arr)) {
  109. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  110. return arr2;
  111. }
  112. }
  113. function _iterableToArray(iter) {
  114. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  115. }
  116. function _nonIterableSpread() {
  117. throw new TypeError("Invalid attempt to spread non-iterable instance");
  118. }
  119. var fs;
  120. try {
  121. fs = require('graceful-fs');
  122. } catch (e) {
  123. fs = require('fs');
  124. }
  125. var fs$1 = fs;
  126. var AbstractFileManager =
  127. /*#__PURE__*/
  128. function () {
  129. function AbstractFileManager() {
  130. _classCallCheck(this, AbstractFileManager);
  131. }
  132. _createClass(AbstractFileManager, [{
  133. key: "getPath",
  134. value: function getPath(filename) {
  135. var j = filename.lastIndexOf('?');
  136. if (j > 0) {
  137. filename = filename.slice(0, j);
  138. }
  139. j = filename.lastIndexOf('/');
  140. if (j < 0) {
  141. j = filename.lastIndexOf('\\');
  142. }
  143. if (j < 0) {
  144. return '';
  145. }
  146. return filename.slice(0, j + 1);
  147. }
  148. }, {
  149. key: "tryAppendExtension",
  150. value: function tryAppendExtension(path, ext) {
  151. return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
  152. }
  153. }, {
  154. key: "tryAppendLessExtension",
  155. value: function tryAppendLessExtension(path) {
  156. return this.tryAppendExtension(path, '.less');
  157. }
  158. }, {
  159. key: "supportsSync",
  160. value: function supportsSync() {
  161. return false;
  162. }
  163. }, {
  164. key: "alwaysMakePathsAbsolute",
  165. value: function alwaysMakePathsAbsolute() {
  166. return false;
  167. }
  168. }, {
  169. key: "isPathAbsolute",
  170. value: function isPathAbsolute(filename) {
  171. return /^(?:[a-z-]+:|\/|\\|#)/i.test(filename);
  172. } // TODO: pull out / replace?
  173. }, {
  174. key: "join",
  175. value: function join(basePath, laterPath) {
  176. if (!basePath) {
  177. return laterPath;
  178. }
  179. return basePath + laterPath;
  180. }
  181. }, {
  182. key: "pathDiff",
  183. value: function pathDiff(url, baseUrl) {
  184. // diff between two paths to create a relative path
  185. var urlParts = this.extractUrlParts(url);
  186. var baseUrlParts = this.extractUrlParts(baseUrl);
  187. var i;
  188. var max;
  189. var urlDirectories;
  190. var baseUrlDirectories;
  191. var diff = '';
  192. if (urlParts.hostPart !== baseUrlParts.hostPart) {
  193. return '';
  194. }
  195. max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
  196. for (i = 0; i < max; i++) {
  197. if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
  198. break;
  199. }
  200. }
  201. baseUrlDirectories = baseUrlParts.directories.slice(i);
  202. urlDirectories = urlParts.directories.slice(i);
  203. for (i = 0; i < baseUrlDirectories.length - 1; i++) {
  204. diff += '../';
  205. }
  206. for (i = 0; i < urlDirectories.length - 1; i++) {
  207. diff += `${urlDirectories[i]}/`;
  208. }
  209. return diff;
  210. }
  211. }, {
  212. key: "extractUrlParts",
  213. // helper function, not part of API
  214. value: function extractUrlParts(url, baseUrl) {
  215. // urlParts[1] = protocol://hostname/ OR /
  216. // urlParts[2] = / if path relative to host base
  217. // urlParts[3] = directories
  218. // urlParts[4] = filename
  219. // urlParts[5] = parameters
  220. var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i;
  221. var urlParts = url.match(urlPartsRegex);
  222. var returner = {};
  223. var rawDirectories = [];
  224. var directories = [];
  225. var i;
  226. var baseUrlParts;
  227. if (!urlParts) {
  228. throw new Error(`Could not parse sheet href - '${url}'`);
  229. } // Stylesheets in IE don't always return the full path
  230. if (baseUrl && (!urlParts[1] || urlParts[2])) {
  231. baseUrlParts = baseUrl.match(urlPartsRegex);
  232. if (!baseUrlParts) {
  233. throw new Error(`Could not parse page url - '${baseUrl}'`);
  234. }
  235. urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
  236. if (!urlParts[2]) {
  237. urlParts[3] = baseUrlParts[3] + urlParts[3];
  238. }
  239. }
  240. if (urlParts[3]) {
  241. rawDirectories = urlParts[3].replace(/\\/g, '/').split('/'); // collapse '..' and skip '.'
  242. for (i = 0; i < rawDirectories.length; i++) {
  243. if (rawDirectories[i] === '..') {
  244. directories.pop();
  245. } else if (rawDirectories[i] !== '.') {
  246. directories.push(rawDirectories[i]);
  247. }
  248. }
  249. }
  250. returner.hostPart = urlParts[1];
  251. returner.directories = directories;
  252. returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
  253. returner.path = (urlParts[1] || '') + directories.join('/');
  254. returner.filename = urlParts[4];
  255. returner.fileUrl = returner.path + (urlParts[4] || '');
  256. returner.url = returner.fileUrl + (urlParts[5] || '');
  257. return returner;
  258. }
  259. }]);
  260. return AbstractFileManager;
  261. }();
  262. var FileManager =
  263. /*#__PURE__*/
  264. function (_AbstractFileManager) {
  265. _inherits(FileManager, _AbstractFileManager);
  266. function FileManager() {
  267. var _this;
  268. _classCallCheck(this, FileManager);
  269. _this = _possibleConstructorReturn(this, _getPrototypeOf(FileManager).call(this));
  270. _this.contents = {};
  271. return _this;
  272. }
  273. _createClass(FileManager, [{
  274. key: "supports",
  275. value: function supports(filename, currentDirectory, options, environment) {
  276. return true;
  277. }
  278. }, {
  279. key: "supportsSync",
  280. value: function supportsSync(filename, currentDirectory, options, environment) {
  281. return true;
  282. }
  283. }, {
  284. key: "loadFile",
  285. value: function loadFile(filename, currentDirectory, options, environment, callback) {
  286. var fullFilename;
  287. var isAbsoluteFilename = this.isPathAbsolute(filename);
  288. var filenamesTried = [];
  289. var self = this;
  290. var prefix = filename.slice(0, 1);
  291. var explicit = prefix === '.' || prefix === '/';
  292. var result = null;
  293. var isNodeModule = false;
  294. var npmPrefix = 'npm://';
  295. options = options || {};
  296. var paths = isAbsoluteFilename ? [''] : [currentDirectory];
  297. if (options.paths) {
  298. paths.push.apply(paths, _toConsumableArray(options.paths));
  299. }
  300. if (!isAbsoluteFilename && paths.indexOf('.') === -1) {
  301. paths.push('.');
  302. }
  303. var prefixes = options.prefixes || [''];
  304. var fileParts = this.extractUrlParts(filename);
  305. if (options.syncImport) {
  306. getFileData(returnData, returnData);
  307. if (callback) {
  308. callback(result.error, result);
  309. } else {
  310. return result;
  311. }
  312. } else {
  313. // promise is guaranteed to be asyncronous
  314. // which helps as it allows the file handle
  315. // to be closed before it continues with the next file
  316. return new Promise(getFileData);
  317. }
  318. function returnData(data) {
  319. if (!data.filename) {
  320. result = {
  321. error: data
  322. };
  323. } else {
  324. result = data;
  325. }
  326. }
  327. function getFileData(fulfill, reject) {
  328. (function tryPathIndex(i) {
  329. if (i < paths.length) {
  330. (function tryPrefix(j) {
  331. if (j < prefixes.length) {
  332. isNodeModule = false;
  333. fullFilename = fileParts.rawPath + prefixes[j] + fileParts.filename;
  334. if (paths[i]) {
  335. fullFilename = path.join(paths[i], fullFilename);
  336. }
  337. if (!explicit && paths[i] === '.') {
  338. try {
  339. fullFilename = require.resolve(fullFilename);
  340. isNodeModule = true;
  341. } catch (e) {
  342. filenamesTried.push(npmPrefix + fullFilename);
  343. tryWithExtension();
  344. }
  345. } else {
  346. tryWithExtension();
  347. }
  348. function tryWithExtension() {
  349. var extFilename = options.ext ? self.tryAppendExtension(fullFilename, options.ext) : fullFilename;
  350. if (extFilename !== fullFilename && !explicit && paths[i] === '.') {
  351. try {
  352. fullFilename = require.resolve(extFilename);
  353. isNodeModule = true;
  354. } catch (e) {
  355. filenamesTried.push(npmPrefix + extFilename);
  356. fullFilename = extFilename;
  357. }
  358. } else {
  359. fullFilename = extFilename;
  360. }
  361. }
  362. var modified = false;
  363. if (self.contents[fullFilename]) {
  364. try {
  365. var stat = fs$1.statSync.apply(this, [fullFilename]);
  366. if (stat.mtime.getTime() === self.contents[fullFilename].mtime.getTime()) {
  367. fulfill({
  368. contents: self.contents[fullFilename].data,
  369. filename: fullFilename
  370. });
  371. } else {
  372. modified = true;
  373. }
  374. } catch (e) {
  375. modified = true;
  376. }
  377. }
  378. if (modified || !self.contents[fullFilename]) {
  379. var readFileArgs = [fullFilename];
  380. if (!options.rawBuffer) {
  381. readFileArgs.push('utf-8');
  382. }
  383. if (options.syncImport) {
  384. try {
  385. var data = fs$1.readFileSync.apply(this, readFileArgs);
  386. var stat = fs$1.statSync.apply(this, [fullFilename]);
  387. self.contents[fullFilename] = {
  388. data,
  389. mtime: stat.mtime
  390. };
  391. fulfill({
  392. contents: data,
  393. filename: fullFilename
  394. });
  395. } catch (e) {
  396. filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
  397. return tryPrefix(j + 1);
  398. }
  399. } else {
  400. readFileArgs.push(function (e, data) {
  401. if (e) {
  402. filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
  403. return tryPrefix(j + 1);
  404. }
  405. var stat = fs$1.statSync.apply(this, [fullFilename]);
  406. self.contents[fullFilename] = {
  407. data,
  408. mtime: stat.mtime
  409. };
  410. fulfill({
  411. contents: data,
  412. filename: fullFilename
  413. });
  414. });
  415. fs$1.readFile.apply(this, readFileArgs);
  416. }
  417. }
  418. } else {
  419. tryPathIndex(i + 1);
  420. }
  421. })(0);
  422. } else {
  423. reject({
  424. type: 'File',
  425. message: `'${filename}' wasn't found. Tried - ${filenamesTried.join(',')}`
  426. });
  427. }
  428. })(0);
  429. }
  430. }
  431. }, {
  432. key: "loadFileSync",
  433. value: function loadFileSync(filename, currentDirectory, options, environment) {
  434. options.syncImport = true;
  435. return this.loadFile(filename, currentDirectory, options, environment);
  436. }
  437. }]);
  438. return FileManager;
  439. }(AbstractFileManager);
  440. var logger = {
  441. error: function error(msg) {
  442. this._fireEvent('error', msg);
  443. },
  444. warn: function warn(msg) {
  445. this._fireEvent('warn', msg);
  446. },
  447. info: function info(msg) {
  448. this._fireEvent('info', msg);
  449. },
  450. debug: function debug(msg) {
  451. this._fireEvent('debug', msg);
  452. },
  453. addListener: function addListener(listener) {
  454. this._listeners.push(listener);
  455. },
  456. removeListener: function removeListener(listener) {
  457. for (var i = 0; i < this._listeners.length; i++) {
  458. if (this._listeners[i] === listener) {
  459. this._listeners.splice(i, 1);
  460. return;
  461. }
  462. }
  463. },
  464. _fireEvent: function _fireEvent(type, msg) {
  465. for (var i = 0; i < this._listeners.length; i++) {
  466. var logFunction = this._listeners[i][type];
  467. if (logFunction) {
  468. logFunction(msg);
  469. }
  470. }
  471. },
  472. _listeners: []
  473. };
  474. var isUrlRe = /^(?:https?:)?\/\//i;
  475. var request;
  476. var UrlFileManager =
  477. /*#__PURE__*/
  478. function (_AbstractFileManager) {
  479. _inherits(UrlFileManager, _AbstractFileManager);
  480. function UrlFileManager() {
  481. _classCallCheck(this, UrlFileManager);
  482. return _possibleConstructorReturn(this, _getPrototypeOf(UrlFileManager).apply(this, arguments));
  483. }
  484. _createClass(UrlFileManager, [{
  485. key: "supports",
  486. value: function supports(filename, currentDirectory, options, environment) {
  487. return isUrlRe.test(filename) || isUrlRe.test(currentDirectory);
  488. }
  489. }, {
  490. key: "loadFile",
  491. value: function loadFile(filename, currentDirectory, options, environment) {
  492. return new Promise(function (fulfill, reject) {
  493. if (request === undefined) {
  494. try {
  495. request = require('request');
  496. } catch (e) {
  497. request = null;
  498. }
  499. }
  500. if (!request) {
  501. reject({
  502. type: 'File',
  503. message: 'optional dependency \'request\' required to import over http(s)\n'
  504. });
  505. return;
  506. }
  507. var urlStr = isUrlRe.test(filename) ? filename : url.resolve(currentDirectory, filename);
  508. var urlObj = url.parse(urlStr);
  509. if (!urlObj.protocol) {
  510. urlObj.protocol = 'http';
  511. urlStr = urlObj.format();
  512. }
  513. request.get({
  514. uri: urlStr,
  515. strictSSL: !options.insecure
  516. }, function (error, res, body) {
  517. if (error) {
  518. reject({
  519. type: 'File',
  520. message: `resource '${urlStr}' gave this Error:\n ${error}\n`
  521. });
  522. return;
  523. }
  524. if (res && res.statusCode === 404) {
  525. reject({
  526. type: 'File',
  527. message: `resource '${urlStr}' was not found\n`
  528. });
  529. return;
  530. }
  531. if (!body) {
  532. logger.warn(`Warning: Empty body (HTTP ${res.statusCode}) returned by "${urlStr}"`);
  533. }
  534. fulfill({
  535. contents: body,
  536. filename: urlStr
  537. });
  538. });
  539. });
  540. }
  541. }]);
  542. return UrlFileManager;
  543. }(AbstractFileManager);
  544. var colors = {
  545. 'aliceblue': '#f0f8ff',
  546. 'antiquewhite': '#faebd7',
  547. 'aqua': '#00ffff',
  548. 'aquamarine': '#7fffd4',
  549. 'azure': '#f0ffff',
  550. 'beige': '#f5f5dc',
  551. 'bisque': '#ffe4c4',
  552. 'black': '#000000',
  553. 'blanchedalmond': '#ffebcd',
  554. 'blue': '#0000ff',
  555. 'blueviolet': '#8a2be2',
  556. 'brown': '#a52a2a',
  557. 'burlywood': '#deb887',
  558. 'cadetblue': '#5f9ea0',
  559. 'chartreuse': '#7fff00',
  560. 'chocolate': '#d2691e',
  561. 'coral': '#ff7f50',
  562. 'cornflowerblue': '#6495ed',
  563. 'cornsilk': '#fff8dc',
  564. 'crimson': '#dc143c',
  565. 'cyan': '#00ffff',
  566. 'darkblue': '#00008b',
  567. 'darkcyan': '#008b8b',
  568. 'darkgoldenrod': '#b8860b',
  569. 'darkgray': '#a9a9a9',
  570. 'darkgrey': '#a9a9a9',
  571. 'darkgreen': '#006400',
  572. 'darkkhaki': '#bdb76b',
  573. 'darkmagenta': '#8b008b',
  574. 'darkolivegreen': '#556b2f',
  575. 'darkorange': '#ff8c00',
  576. 'darkorchid': '#9932cc',
  577. 'darkred': '#8b0000',
  578. 'darksalmon': '#e9967a',
  579. 'darkseagreen': '#8fbc8f',
  580. 'darkslateblue': '#483d8b',
  581. 'darkslategray': '#2f4f4f',
  582. 'darkslategrey': '#2f4f4f',
  583. 'darkturquoise': '#00ced1',
  584. 'darkviolet': '#9400d3',
  585. 'deeppink': '#ff1493',
  586. 'deepskyblue': '#00bfff',
  587. 'dimgray': '#696969',
  588. 'dimgrey': '#696969',
  589. 'dodgerblue': '#1e90ff',
  590. 'firebrick': '#b22222',
  591. 'floralwhite': '#fffaf0',
  592. 'forestgreen': '#228b22',
  593. 'fuchsia': '#ff00ff',
  594. 'gainsboro': '#dcdcdc',
  595. 'ghostwhite': '#f8f8ff',
  596. 'gold': '#ffd700',
  597. 'goldenrod': '#daa520',
  598. 'gray': '#808080',
  599. 'grey': '#808080',
  600. 'green': '#008000',
  601. 'greenyellow': '#adff2f',
  602. 'honeydew': '#f0fff0',
  603. 'hotpink': '#ff69b4',
  604. 'indianred': '#cd5c5c',
  605. 'indigo': '#4b0082',
  606. 'ivory': '#fffff0',
  607. 'khaki': '#f0e68c',
  608. 'lavender': '#e6e6fa',
  609. 'lavenderblush': '#fff0f5',
  610. 'lawngreen': '#7cfc00',
  611. 'lemonchiffon': '#fffacd',
  612. 'lightblue': '#add8e6',
  613. 'lightcoral': '#f08080',
  614. 'lightcyan': '#e0ffff',
  615. 'lightgoldenrodyellow': '#fafad2',
  616. 'lightgray': '#d3d3d3',
  617. 'lightgrey': '#d3d3d3',
  618. 'lightgreen': '#90ee90',
  619. 'lightpink': '#ffb6c1',
  620. 'lightsalmon': '#ffa07a',
  621. 'lightseagreen': '#20b2aa',
  622. 'lightskyblue': '#87cefa',
  623. 'lightslategray': '#778899',
  624. 'lightslategrey': '#778899',
  625. 'lightsteelblue': '#b0c4de',
  626. 'lightyellow': '#ffffe0',
  627. 'lime': '#00ff00',
  628. 'limegreen': '#32cd32',
  629. 'linen': '#faf0e6',
  630. 'magenta': '#ff00ff',
  631. 'maroon': '#800000',
  632. 'mediumaquamarine': '#66cdaa',
  633. 'mediumblue': '#0000cd',
  634. 'mediumorchid': '#ba55d3',
  635. 'mediumpurple': '#9370d8',
  636. 'mediumseagreen': '#3cb371',
  637. 'mediumslateblue': '#7b68ee',
  638. 'mediumspringgreen': '#00fa9a',
  639. 'mediumturquoise': '#48d1cc',
  640. 'mediumvioletred': '#c71585',
  641. 'midnightblue': '#191970',
  642. 'mintcream': '#f5fffa',
  643. 'mistyrose': '#ffe4e1',
  644. 'moccasin': '#ffe4b5',
  645. 'navajowhite': '#ffdead',
  646. 'navy': '#000080',
  647. 'oldlace': '#fdf5e6',
  648. 'olive': '#808000',
  649. 'olivedrab': '#6b8e23',
  650. 'orange': '#ffa500',
  651. 'orangered': '#ff4500',
  652. 'orchid': '#da70d6',
  653. 'palegoldenrod': '#eee8aa',
  654. 'palegreen': '#98fb98',
  655. 'paleturquoise': '#afeeee',
  656. 'palevioletred': '#d87093',
  657. 'papayawhip': '#ffefd5',
  658. 'peachpuff': '#ffdab9',
  659. 'peru': '#cd853f',
  660. 'pink': '#ffc0cb',
  661. 'plum': '#dda0dd',
  662. 'powderblue': '#b0e0e6',
  663. 'purple': '#800080',
  664. 'rebeccapurple': '#663399',
  665. 'red': '#ff0000',
  666. 'rosybrown': '#bc8f8f',
  667. 'royalblue': '#4169e1',
  668. 'saddlebrown': '#8b4513',
  669. 'salmon': '#fa8072',
  670. 'sandybrown': '#f4a460',
  671. 'seagreen': '#2e8b57',
  672. 'seashell': '#fff5ee',
  673. 'sienna': '#a0522d',
  674. 'silver': '#c0c0c0',
  675. 'skyblue': '#87ceeb',
  676. 'slateblue': '#6a5acd',
  677. 'slategray': '#708090',
  678. 'slategrey': '#708090',
  679. 'snow': '#fffafa',
  680. 'springgreen': '#00ff7f',
  681. 'steelblue': '#4682b4',
  682. 'tan': '#d2b48c',
  683. 'teal': '#008080',
  684. 'thistle': '#d8bfd8',
  685. 'tomato': '#ff6347',
  686. 'turquoise': '#40e0d0',
  687. 'violet': '#ee82ee',
  688. 'wheat': '#f5deb3',
  689. 'white': '#ffffff',
  690. 'whitesmoke': '#f5f5f5',
  691. 'yellow': '#ffff00',
  692. 'yellowgreen': '#9acd32'
  693. };
  694. var unitConversions = {
  695. length: {
  696. 'm': 1,
  697. 'cm': 0.01,
  698. 'mm': 0.001,
  699. 'in': 0.0254,
  700. 'px': 0.0254 / 96,
  701. 'pt': 0.0254 / 72,
  702. 'pc': 0.0254 / 72 * 12
  703. },
  704. duration: {
  705. 's': 1,
  706. 'ms': 0.001
  707. },
  708. angle: {
  709. 'rad': 1 / (2 * Math.PI),
  710. 'deg': 1 / 360,
  711. 'grad': 1 / 400,
  712. 'turn': 1
  713. }
  714. };
  715. var data = {
  716. colors,
  717. unitConversions
  718. };
  719. var Node =
  720. /*#__PURE__*/
  721. function () {
  722. function Node() {
  723. _classCallCheck(this, Node);
  724. this.parent = null;
  725. this.visibilityBlocks = undefined;
  726. this.nodeVisible = undefined;
  727. this.rootNode = null;
  728. this.parsed = null;
  729. var self = this;
  730. Object.defineProperty(this, 'currentFileInfo', {
  731. get: function get() {
  732. return self.fileInfo();
  733. }
  734. });
  735. Object.defineProperty(this, 'index', {
  736. get: function get() {
  737. return self.getIndex();
  738. }
  739. });
  740. }
  741. _createClass(Node, [{
  742. key: "setParent",
  743. value: function setParent(nodes, parent) {
  744. function set(node) {
  745. if (node && node instanceof Node) {
  746. node.parent = parent;
  747. }
  748. }
  749. if (Array.isArray(nodes)) {
  750. nodes.forEach(set);
  751. } else {
  752. set(nodes);
  753. }
  754. }
  755. }, {
  756. key: "getIndex",
  757. value: function getIndex() {
  758. return this._index || this.parent && this.parent.getIndex() || 0;
  759. }
  760. }, {
  761. key: "fileInfo",
  762. value: function fileInfo() {
  763. return this._fileInfo || this.parent && this.parent.fileInfo() || {};
  764. }
  765. }, {
  766. key: "isRulesetLike",
  767. value: function isRulesetLike() {
  768. return false;
  769. }
  770. }, {
  771. key: "toCSS",
  772. value: function toCSS(context) {
  773. var strs = [];
  774. this.genCSS(context, {
  775. add: function add(chunk, fileInfo, index) {
  776. strs.push(chunk);
  777. },
  778. isEmpty: function isEmpty() {
  779. return strs.length === 0;
  780. }
  781. });
  782. return strs.join('');
  783. }
  784. }, {
  785. key: "genCSS",
  786. value: function genCSS(context, output) {
  787. output.add(this.value);
  788. }
  789. }, {
  790. key: "accept",
  791. value: function accept(visitor) {
  792. this.value = visitor.visit(this.value);
  793. }
  794. }, {
  795. key: "eval",
  796. value: function _eval() {
  797. return this;
  798. }
  799. }, {
  800. key: "_operate",
  801. value: function _operate(context, op, a, b) {
  802. switch (op) {
  803. case '+':
  804. return a + b;
  805. case '-':
  806. return a - b;
  807. case '*':
  808. return a * b;
  809. case '/':
  810. return a / b;
  811. }
  812. }
  813. }, {
  814. key: "fround",
  815. value: function fround(context, value) {
  816. var precision = context && context.numPrecision; // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
  817. return precision ? Number((value + 2e-16).toFixed(precision)) : value;
  818. } // Returns true if this node represents root of ast imported by reference
  819. }, {
  820. key: "blocksVisibility",
  821. value: function blocksVisibility() {
  822. if (this.visibilityBlocks == null) {
  823. this.visibilityBlocks = 0;
  824. }
  825. return this.visibilityBlocks !== 0;
  826. }
  827. }, {
  828. key: "addVisibilityBlock",
  829. value: function addVisibilityBlock() {
  830. if (this.visibilityBlocks == null) {
  831. this.visibilityBlocks = 0;
  832. }
  833. this.visibilityBlocks = this.visibilityBlocks + 1;
  834. }
  835. }, {
  836. key: "removeVisibilityBlock",
  837. value: function removeVisibilityBlock() {
  838. if (this.visibilityBlocks == null) {
  839. this.visibilityBlocks = 0;
  840. }
  841. this.visibilityBlocks = this.visibilityBlocks - 1;
  842. } // Turns on node visibility - if called node will be shown in output regardless
  843. // of whether it comes from import by reference or not
  844. }, {
  845. key: "ensureVisibility",
  846. value: function ensureVisibility() {
  847. this.nodeVisible = true;
  848. } // Turns off node visibility - if called node will NOT be shown in output regardless
  849. // of whether it comes from import by reference or not
  850. }, {
  851. key: "ensureInvisibility",
  852. value: function ensureInvisibility() {
  853. this.nodeVisible = false;
  854. } // return values:
  855. // false - the node must not be visible
  856. // true - the node must be visible
  857. // undefined or null - the node has the same visibility as its parent
  858. }, {
  859. key: "isVisible",
  860. value: function isVisible() {
  861. return this.nodeVisible;
  862. }
  863. }, {
  864. key: "visibilityInfo",
  865. value: function visibilityInfo() {
  866. return {
  867. visibilityBlocks: this.visibilityBlocks,
  868. nodeVisible: this.nodeVisible
  869. };
  870. }
  871. }, {
  872. key: "copyVisibilityInfo",
  873. value: function copyVisibilityInfo(info) {
  874. if (!info) {
  875. return;
  876. }
  877. this.visibilityBlocks = info.visibilityBlocks;
  878. this.nodeVisible = info.nodeVisible;
  879. }
  880. }]);
  881. return Node;
  882. }();
  883. Node.compare = function (a, b) {
  884. /* returns:
  885. -1: a < b
  886. 0: a = b
  887. 1: a > b
  888. and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
  889. if (a.compare && // for "symmetric results" force toCSS-based comparison
  890. // of Quoted or Anonymous if either value is one of those
  891. !(b.type === 'Quoted' || b.type === 'Anonymous')) {
  892. return a.compare(b);
  893. } else if (b.compare) {
  894. return -b.compare(a);
  895. } else if (a.type !== b.type) {
  896. return undefined;
  897. }
  898. a = a.value;
  899. b = b.value;
  900. if (!Array.isArray(a)) {
  901. return a === b ? 0 : undefined;
  902. }
  903. if (a.length !== b.length) {
  904. return undefined;
  905. }
  906. for (var i = 0; i < a.length; i++) {
  907. if (Node.compare(a[i], b[i]) !== 0) {
  908. return undefined;
  909. }
  910. }
  911. return 0;
  912. };
  913. Node.numericCompare = function (a, b) {
  914. return a < b ? -1 : a === b ? 0 : a > b ? 1 : undefined;
  915. };
  916. // RGB Colors - #ff0014, #eee
  917. //
  918. var Color =
  919. /*#__PURE__*/
  920. function (_Node) {
  921. _inherits(Color, _Node);
  922. function Color(rgb, a, originalForm) {
  923. var _this;
  924. _classCallCheck(this, Color);
  925. _this = _possibleConstructorReturn(this, _getPrototypeOf(Color).call(this));
  926. var self = _assertThisInitialized(_this); //
  927. // The end goal here, is to parse the arguments
  928. // into an integer triplet, such as `128, 255, 0`
  929. //
  930. // This facilitates operations and conversions.
  931. //
  932. if (Array.isArray(rgb)) {
  933. _this.rgb = rgb;
  934. } else if (rgb.length >= 6) {
  935. _this.rgb = [];
  936. rgb.match(/.{2}/g).map(function (c, i) {
  937. if (i < 3) {
  938. self.rgb.push(parseInt(c, 16));
  939. } else {
  940. self.alpha = parseInt(c, 16) / 255;
  941. }
  942. });
  943. } else {
  944. _this.rgb = [];
  945. rgb.split('').map(function (c, i) {
  946. if (i < 3) {
  947. self.rgb.push(parseInt(c + c, 16));
  948. } else {
  949. self.alpha = parseInt(c + c, 16) / 255;
  950. }
  951. });
  952. }
  953. _this.alpha = _this.alpha || (typeof a === 'number' ? a : 1);
  954. if (typeof originalForm !== 'undefined') {
  955. _this.value = originalForm;
  956. }
  957. return _this;
  958. }
  959. _createClass(Color, [{
  960. key: "luma",
  961. value: function luma() {
  962. var r = this.rgb[0] / 255;
  963. var g = this.rgb[1] / 255;
  964. var b = this.rgb[2] / 255;
  965. r = r <= 0.03928 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4);
  966. g = g <= 0.03928 ? g / 12.92 : Math.pow((g + 0.055) / 1.055, 2.4);
  967. b = b <= 0.03928 ? b / 12.92 : Math.pow((b + 0.055) / 1.055, 2.4);
  968. return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  969. }
  970. }, {
  971. key: "genCSS",
  972. value: function genCSS(context, output) {
  973. output.add(this.toCSS(context));
  974. }
  975. }, {
  976. key: "toCSS",
  977. value: function toCSS(context, doNotCompress) {
  978. var compress = context && context.compress && !doNotCompress;
  979. var color;
  980. var alpha;
  981. var colorFunction;
  982. var args = []; // `value` is set if this color was originally
  983. // converted from a named color string so we need
  984. // to respect this and try to output named color too.
  985. alpha = this.fround(context, this.alpha);
  986. if (this.value) {
  987. if (this.value.indexOf('rgb') === 0) {
  988. if (alpha < 1) {
  989. colorFunction = 'rgba';
  990. }
  991. } else if (this.value.indexOf('hsl') === 0) {
  992. if (alpha < 1) {
  993. colorFunction = 'hsla';
  994. } else {
  995. colorFunction = 'hsl';
  996. }
  997. } else {
  998. return this.value;
  999. }
  1000. } else {
  1001. if (alpha < 1) {
  1002. colorFunction = 'rgba';
  1003. }
  1004. }
  1005. switch (colorFunction) {
  1006. case 'rgba':
  1007. args = this.rgb.map(function (c) {
  1008. return clamp(Math.round(c), 255);
  1009. }).concat(clamp(alpha, 1));
  1010. break;
  1011. case 'hsla':
  1012. args.push(clamp(alpha, 1));
  1013. case 'hsl':
  1014. color = this.toHSL();
  1015. args = [this.fround(context, color.h), `${this.fround(context, color.s * 100)}%`, `${this.fround(context, color.l * 100)}%`].concat(args);
  1016. }
  1017. if (colorFunction) {
  1018. // Values are capped between `0` and `255`, rounded and zero-padded.
  1019. return `${colorFunction}(${args.join(`,${compress ? '' : ' '}`)})`;
  1020. }
  1021. color = this.toRGB();
  1022. if (compress) {
  1023. var splitcolor = color.split(''); // Convert color to short format
  1024. if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
  1025. color = `#${splitcolor[1]}${splitcolor[3]}${splitcolor[5]}`;
  1026. }
  1027. }
  1028. return color;
  1029. } //
  1030. // Operations have to be done per-channel, if not,
  1031. // channels will spill onto each other. Once we have
  1032. // our result, in the form of an integer triplet,
  1033. // we create a new Color node to hold the result.
  1034. //
  1035. }, {
  1036. key: "operate",
  1037. value: function operate(context, op, other) {
  1038. var rgb = new Array(3);
  1039. var alpha = this.alpha * (1 - other.alpha) + other.alpha;
  1040. for (var c = 0; c < 3; c++) {
  1041. rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
  1042. }
  1043. return new Color(rgb, alpha);
  1044. }
  1045. }, {
  1046. key: "toRGB",
  1047. value: function toRGB() {
  1048. return toHex(this.rgb);
  1049. }
  1050. }, {
  1051. key: "toHSL",
  1052. value: function toHSL() {
  1053. var r = this.rgb[0] / 255;
  1054. var g = this.rgb[1] / 255;
  1055. var b = this.rgb[2] / 255;
  1056. var a = this.alpha;
  1057. var max = Math.max(r, g, b);
  1058. var min = Math.min(r, g, b);
  1059. var h;
  1060. var s;
  1061. var l = (max + min) / 2;
  1062. var d = max - min;
  1063. if (max === min) {
  1064. h = s = 0;
  1065. } else {
  1066. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  1067. switch (max) {
  1068. case r:
  1069. h = (g - b) / d + (g < b ? 6 : 0);
  1070. break;
  1071. case g:
  1072. h = (b - r) / d + 2;
  1073. break;
  1074. case b:
  1075. h = (r - g) / d + 4;
  1076. break;
  1077. }
  1078. h /= 6;
  1079. }
  1080. return {
  1081. h: h * 360,
  1082. s,
  1083. l,
  1084. a
  1085. };
  1086. } // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  1087. }, {
  1088. key: "toHSV",
  1089. value: function toHSV() {
  1090. var r = this.rgb[0] / 255;
  1091. var g = this.rgb[1] / 255;
  1092. var b = this.rgb[2] / 255;
  1093. var a = this.alpha;
  1094. var max = Math.max(r, g, b);
  1095. var min = Math.min(r, g, b);
  1096. var h;
  1097. var s;
  1098. var v = max;
  1099. var d = max - min;
  1100. if (max === 0) {
  1101. s = 0;
  1102. } else {
  1103. s = d / max;
  1104. }
  1105. if (max === min) {
  1106. h = 0;
  1107. } else {
  1108. switch (max) {
  1109. case r:
  1110. h = (g - b) / d + (g < b ? 6 : 0);
  1111. break;
  1112. case g:
  1113. h = (b - r) / d + 2;
  1114. break;
  1115. case b:
  1116. h = (r - g) / d + 4;
  1117. break;
  1118. }
  1119. h /= 6;
  1120. }
  1121. return {
  1122. h: h * 360,
  1123. s,
  1124. v,
  1125. a
  1126. };
  1127. }
  1128. }, {
  1129. key: "toARGB",
  1130. value: function toARGB() {
  1131. return toHex([this.alpha * 255].concat(this.rgb));
  1132. }
  1133. }, {
  1134. key: "compare",
  1135. value: function compare(x) {
  1136. return x.rgb && x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha ? 0 : undefined;
  1137. }
  1138. }]);
  1139. return Color;
  1140. }(Node);
  1141. Color.prototype.type = 'Color';
  1142. function clamp(v, max) {
  1143. return Math.min(Math.max(v, 0), max);
  1144. }
  1145. function toHex(v) {
  1146. return `#${v.map(function (c) {
  1147. c = clamp(Math.round(c), 255);
  1148. return (c < 16 ? '0' : '') + c.toString(16);
  1149. }).join('')}`;
  1150. }
  1151. Color.fromKeyword = function (keyword) {
  1152. var c;
  1153. var key = keyword.toLowerCase();
  1154. if (colors.hasOwnProperty(key)) {
  1155. c = new Color(colors[key].slice(1));
  1156. } else if (key === 'transparent') {
  1157. c = new Color([0, 0, 0], 0);
  1158. }
  1159. if (c) {
  1160. c.value = keyword;
  1161. return c;
  1162. }
  1163. };
  1164. var Paren =
  1165. /*#__PURE__*/
  1166. function (_Node) {
  1167. _inherits(Paren, _Node);
  1168. function Paren(node) {
  1169. var _this;
  1170. _classCallCheck(this, Paren);
  1171. _this = _possibleConstructorReturn(this, _getPrototypeOf(Paren).call(this));
  1172. _this.value = node;
  1173. return _this;
  1174. }
  1175. _createClass(Paren, [{
  1176. key: "genCSS",
  1177. value: function genCSS(context, output) {
  1178. output.add('(');
  1179. this.value.genCSS(context, output);
  1180. output.add(')');
  1181. }
  1182. }, {
  1183. key: "eval",
  1184. value: function _eval(context) {
  1185. return new Paren(this.value.eval(context));
  1186. }
  1187. }]);
  1188. return Paren;
  1189. }(Node);
  1190. Paren.prototype.type = 'Paren';
  1191. var _noSpaceCombinators = {
  1192. '': true,
  1193. ' ': true,
  1194. '|': true
  1195. };
  1196. var Combinator =
  1197. /*#__PURE__*/
  1198. function (_Node) {
  1199. _inherits(Combinator, _Node);
  1200. function Combinator(value) {
  1201. var _this;
  1202. _classCallCheck(this, Combinator);
  1203. _this = _possibleConstructorReturn(this, _getPrototypeOf(Combinator).call(this));
  1204. if (value === ' ') {
  1205. _this.value = ' ';
  1206. _this.emptyOrWhitespace = true;
  1207. } else {
  1208. _this.value = value ? value.trim() : '';
  1209. _this.emptyOrWhitespace = _this.value === '';
  1210. }
  1211. return _this;
  1212. }
  1213. _createClass(Combinator, [{
  1214. key: "genCSS",
  1215. value: function genCSS(context, output) {
  1216. var spaceOrEmpty = context.compress || _noSpaceCombinators[this.value] ? '' : ' ';
  1217. output.add(spaceOrEmpty + this.value + spaceOrEmpty);
  1218. }
  1219. }]);
  1220. return Combinator;
  1221. }(Node);
  1222. Combinator.prototype.type = 'Combinator';
  1223. var Element =
  1224. /*#__PURE__*/
  1225. function (_Node) {
  1226. _inherits(Element, _Node);
  1227. function Element(combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
  1228. var _this;
  1229. _classCallCheck(this, Element);
  1230. _this = _possibleConstructorReturn(this, _getPrototypeOf(Element).call(this));
  1231. _this.combinator = combinator instanceof Combinator ? combinator : new Combinator(combinator);
  1232. if (typeof value === 'string') {
  1233. _this.value = value.trim();
  1234. } else if (value) {
  1235. _this.value = value;
  1236. } else {
  1237. _this.value = '';
  1238. }
  1239. _this.isVariable = isVariable;
  1240. _this._index = index;
  1241. _this._fileInfo = currentFileInfo;
  1242. _this.copyVisibilityInfo(visibilityInfo);
  1243. _this.setParent(_this.combinator, _assertThisInitialized(_this));
  1244. return _this;
  1245. }
  1246. _createClass(Element, [{
  1247. key: "accept",
  1248. value: function accept(visitor) {
  1249. var value = this.value;
  1250. this.combinator = visitor.visit(this.combinator);
  1251. if (typeof value === 'object') {
  1252. this.value = visitor.visit(value);
  1253. }
  1254. }
  1255. }, {
  1256. key: "eval",
  1257. value: function _eval(context) {
  1258. return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  1259. }
  1260. }, {
  1261. key: "clone",
  1262. value: function clone() {
  1263. return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  1264. }
  1265. }, {
  1266. key: "genCSS",
  1267. value: function genCSS(context, output) {
  1268. output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
  1269. }
  1270. }, {
  1271. key: "toCSS",
  1272. value: function toCSS() {
  1273. var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1274. var value = this.value;
  1275. var firstSelector = context.firstSelector;
  1276. if (value instanceof Paren) {
  1277. // selector in parens should not be affected by outer selector
  1278. // flags (breaks only interpolated selectors - see #1973)
  1279. context.firstSelector = true;
  1280. }
  1281. value = value.toCSS ? value.toCSS(context) : value;
  1282. context.firstSelector = firstSelector;
  1283. if (value === '' && this.combinator.value.charAt(0) === '&') {
  1284. return '';
  1285. } else {
  1286. return this.combinator.toCSS(context) + value;
  1287. }
  1288. }
  1289. }]);
  1290. return Element;
  1291. }(Node);
  1292. Element.prototype.type = 'Element';
  1293. var Math$1 = {
  1294. ALWAYS: 0,
  1295. PARENS_DIVISION: 1,
  1296. PARENS: 2,
  1297. STRICT_LEGACY: 3
  1298. };
  1299. var RewriteUrls = {
  1300. OFF: 0,
  1301. LOCAL: 1,
  1302. ALL: 2
  1303. };
  1304. /* jshint proto: true */
  1305. function getLocation(index, inputStream) {
  1306. var n = index + 1;
  1307. var line = null;
  1308. var column = -1;
  1309. while (--n >= 0 && inputStream.charAt(n) !== '\n') {
  1310. column++;
  1311. }
  1312. if (typeof index === 'number') {
  1313. line = (inputStream.slice(0, index).match(/\n/g) || '').length;
  1314. }
  1315. return {
  1316. line,
  1317. column
  1318. };
  1319. }
  1320. function copyArray(arr) {
  1321. var i;
  1322. var length = arr.length;
  1323. var copy = new Array(length);
  1324. for (i = 0; i < length; i++) {
  1325. copy[i] = arr[i];
  1326. }
  1327. return copy;
  1328. }
  1329. function clone(obj) {
  1330. var cloned = {};
  1331. for (var prop in obj) {
  1332. if (obj.hasOwnProperty(prop)) {
  1333. cloned[prop] = obj[prop];
  1334. }
  1335. }
  1336. return cloned;
  1337. }
  1338. function defaults(obj1, obj2) {
  1339. var newObj = obj2 || {};
  1340. if (!obj2._defaults) {
  1341. newObj = {};
  1342. var _defaults = CloneHelper(obj1);
  1343. newObj._defaults = _defaults;
  1344. var cloned = obj2 ? CloneHelper(obj2) : {};
  1345. Object.assign(newObj, _defaults, cloned);
  1346. }
  1347. return newObj;
  1348. }
  1349. function copyOptions(obj1, obj2) {
  1350. if (obj2 && obj2._defaults) {
  1351. return obj2;
  1352. }
  1353. var opts = defaults(obj1, obj2);
  1354. if (opts.strictMath) {
  1355. opts.math = Math$1.STRICT_LEGACY;
  1356. } // Back compat with changed relativeUrls option
  1357. if (opts.relativeUrls) {
  1358. opts.rewriteUrls = RewriteUrls.ALL;
  1359. }
  1360. if (typeof opts.math === 'string') {
  1361. switch (opts.math.toLowerCase()) {
  1362. case 'always':
  1363. opts.math = Math$1.ALWAYS;
  1364. break;
  1365. case 'parens-division':
  1366. opts.math = Math$1.PARENS_DIVISION;
  1367. break;
  1368. case 'strict':
  1369. case 'parens':
  1370. opts.math = Math$1.PARENS;
  1371. break;
  1372. case 'strict-legacy':
  1373. opts.math = Math$1.STRICT_LEGACY;
  1374. }
  1375. }
  1376. if (typeof opts.rewriteUrls === 'string') {
  1377. switch (opts.rewriteUrls.toLowerCase()) {
  1378. case 'off':
  1379. opts.rewriteUrls = RewriteUrls.OFF;
  1380. break;
  1381. case 'local':
  1382. opts.rewriteUrls = RewriteUrls.LOCAL;
  1383. break;
  1384. case 'all':
  1385. opts.rewriteUrls = RewriteUrls.ALL;
  1386. break;
  1387. }
  1388. }
  1389. return opts;
  1390. }
  1391. function merge(obj1, obj2) {
  1392. for (var prop in obj2) {
  1393. if (obj2.hasOwnProperty(prop)) {
  1394. obj1[prop] = obj2[prop];
  1395. }
  1396. }
  1397. return obj1;
  1398. }
  1399. function flattenArray(arr) {
  1400. var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  1401. for (var i = 0, length = arr.length; i < length; i++) {
  1402. var value = arr[i];
  1403. if (Array.isArray(value)) {
  1404. flattenArray(value, result);
  1405. } else {
  1406. if (value !== undefined) {
  1407. result.push(value);
  1408. }
  1409. }
  1410. }
  1411. return result;
  1412. }
  1413. var utils = /*#__PURE__*/Object.freeze({
  1414. getLocation: getLocation,
  1415. copyArray: copyArray,
  1416. clone: clone,
  1417. defaults: defaults,
  1418. copyOptions: copyOptions,
  1419. merge: merge,
  1420. flattenArray: flattenArray
  1421. });
  1422. /**
  1423. * This is a centralized class of any error that could be thrown internally (mostly by the parser).
  1424. * Besides standard .message it keeps some additional data like a path to the file where the error
  1425. * occurred along with line and column numbers.
  1426. *
  1427. * @class
  1428. * @extends Error
  1429. * @type {module.LessError}
  1430. *
  1431. * @prop {string} type
  1432. * @prop {string} filename
  1433. * @prop {number} index
  1434. * @prop {number} line
  1435. * @prop {number} column
  1436. * @prop {number} callLine
  1437. * @prop {number} callExtract
  1438. * @prop {string[]} extract
  1439. *
  1440. * @param {Object} e - An error object to wrap around or just a descriptive object
  1441. * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
  1442. * @param {string} [currentFilename]
  1443. */
  1444. var LessError = function LessError(e, fileContentMap, currentFilename) {
  1445. Error.call(this);
  1446. var filename = e.filename || currentFilename;
  1447. this.message = e.message;
  1448. this.stack = e.stack;
  1449. if (fileContentMap && filename) {
  1450. var input = fileContentMap.contents[filename];
  1451. var loc = getLocation(e.index, input);
  1452. var line = loc.line;
  1453. var col = loc.column;
  1454. var callLine = e.call && getLocation(e.call, input).line;
  1455. var lines = input ? input.split('\n') : '';
  1456. this.type = e.type || 'Syntax';
  1457. this.filename = filename;
  1458. this.index = e.index;
  1459. this.line = typeof line === 'number' ? line + 1 : null;
  1460. this.column = col;
  1461. if (!this.line && this.stack) {
  1462. var found = this.stack.match(/(<anonymous>|Function):(\d+):(\d+)/);
  1463. if (found) {
  1464. if (found[2]) {
  1465. this.line = parseInt(found[2]) - 2;
  1466. }
  1467. if (found[3]) {
  1468. this.column = parseInt(found[3]);
  1469. }
  1470. }
  1471. }
  1472. this.callLine = callLine + 1;
  1473. this.callExtract = lines[callLine];
  1474. this.extract = [lines[this.line - 2], lines[this.line - 1], lines[this.line]];
  1475. }
  1476. };
  1477. if (typeof Object.create === 'undefined') {
  1478. var F = function F() {};
  1479. F.prototype = Error.prototype;
  1480. LessError.prototype = new F();
  1481. } else {
  1482. LessError.prototype = Object.create(Error.prototype);
  1483. }
  1484. LessError.prototype.constructor = LessError;
  1485. /**
  1486. * An overridden version of the default Object.prototype.toString
  1487. * which uses additional information to create a helpful message.
  1488. *
  1489. * @param {Object} options
  1490. * @returns {string}
  1491. */
  1492. LessError.prototype.toString = function () {
  1493. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1494. var message = '';
  1495. var extract = this.extract || [];
  1496. var error = [];
  1497. var stylize = function stylize(str) {
  1498. return str;
  1499. };
  1500. if (options.stylize) {
  1501. var type = typeof options.stylize;
  1502. if (type !== 'function') {
  1503. throw Error(`options.stylize should be a function, got a ${type}!`);
  1504. }
  1505. stylize = options.stylize;
  1506. }
  1507. if (this.line !== null) {
  1508. if (typeof extract[0] === 'string') {
  1509. error.push(stylize(`${this.line - 1} ${extract[0]}`, 'grey'));
  1510. }
  1511. if (typeof extract[1] === 'string') {
  1512. var errorTxt = `${this.line} `;
  1513. if (extract[1]) {
  1514. errorTxt += extract[1].slice(0, this.column) + stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') + extract[1].slice(this.column + 1), 'red'), 'inverse');
  1515. }
  1516. error.push(errorTxt);
  1517. }
  1518. if (typeof extract[2] === 'string') {
  1519. error.push(stylize(`${this.line + 1} ${extract[2]}`, 'grey'));
  1520. }
  1521. error = `${error.join('\n') + stylize('', 'reset')}\n`;
  1522. }
  1523. message += stylize(`${this.type}Error: ${this.message}`, 'red');
  1524. if (this.filename) {
  1525. message += stylize(' in ', 'red') + this.filename;
  1526. }
  1527. if (this.line) {
  1528. message += stylize(` on line ${this.line}, column ${this.column + 1}:`, 'grey');
  1529. }
  1530. message += `\n${error}`;
  1531. if (this.callLine) {
  1532. message += `${stylize('from ', 'red') + (this.filename || '')}/n`;
  1533. message += `${stylize(this.callLine, 'grey')} ${this.callExtract}/n`;
  1534. }
  1535. return message;
  1536. };
  1537. var Selector =
  1538. /*#__PURE__*/
  1539. function (_Node) {
  1540. _inherits(Selector, _Node);
  1541. function Selector(elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
  1542. var _this;
  1543. _classCallCheck(this, Selector);
  1544. _this = _possibleConstructorReturn(this, _getPrototypeOf(Selector).call(this));
  1545. _this.extendList = extendList;
  1546. _this.condition = condition;
  1547. _this.evaldCondition = !condition;
  1548. _this._index = index;
  1549. _this._fileInfo = currentFileInfo;
  1550. _this.elements = _this.getElements(elements);
  1551. _this.mixinElements_ = undefined;
  1552. _this.copyVisibilityInfo(visibilityInfo);
  1553. _this.setParent(_this.elements, _assertThisInitialized(_this));
  1554. return _this;
  1555. }
  1556. _createClass(Selector, [{
  1557. key: "accept",
  1558. value: function accept(visitor) {
  1559. if (this.elements) {
  1560. this.elements = visitor.visitArray(this.elements);
  1561. }
  1562. if (this.extendList) {
  1563. this.extendList = visitor.visitArray(this.extendList);
  1564. }
  1565. if (this.condition) {
  1566. this.condition = visitor.visit(this.condition);
  1567. }
  1568. }
  1569. }, {
  1570. key: "createDerived",
  1571. value: function createDerived(elements, extendList, evaldCondition) {
  1572. elements = this.getElements(elements);
  1573. var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  1574. newSelector.evaldCondition = evaldCondition != null ? evaldCondition : this.evaldCondition;
  1575. newSelector.mediaEmpty = this.mediaEmpty;
  1576. return newSelector;
  1577. }
  1578. }, {
  1579. key: "getElements",
  1580. value: function getElements(els) {
  1581. if (!els) {
  1582. return [new Element('', '&', false, this._index, this._fileInfo)];
  1583. }
  1584. if (typeof els === 'string') {
  1585. this.parse.parseNode(els, ['selector'], this._index, this._fileInfo, function (err, result) {
  1586. if (err) {
  1587. throw new LessError({
  1588. index: err.index,
  1589. message: err.message
  1590. }, this.parse.imports, this._fileInfo.filename);
  1591. }
  1592. els = result[0].elements;
  1593. });
  1594. }
  1595. return els;
  1596. }
  1597. }, {
  1598. key: "createEmptySelectors",
  1599. value: function createEmptySelectors() {
  1600. var el = new Element('', '&', false, this._index, this._fileInfo);
  1601. var sels = [new Selector([el], null, null, this._index, this._fileInfo)];
  1602. sels[0].mediaEmpty = true;
  1603. return sels;
  1604. }
  1605. }, {
  1606. key: "match",
  1607. value: function match(other) {
  1608. var elements = this.elements;
  1609. var len = elements.length;
  1610. var olen;
  1611. var i;
  1612. other = other.mixinElements();
  1613. olen = other.length;
  1614. if (olen === 0 || len < olen) {
  1615. return 0;
  1616. } else {
  1617. for (i = 0; i < olen; i++) {
  1618. if (elements[i].value !== other[i]) {
  1619. return 0;
  1620. }
  1621. }
  1622. }
  1623. return olen; // return number of matched elements
  1624. }
  1625. }, {
  1626. key: "mixinElements",
  1627. value: function mixinElements() {
  1628. if (this.mixinElements_) {
  1629. return this.mixinElements_;
  1630. }
  1631. var elements = this.elements.map(function (v) {
  1632. return v.combinator.value + (v.value.value || v.value);
  1633. }).join('').match(/[,&#\*\.\w-]([\w-]|(\\.))*/g);
  1634. if (elements) {
  1635. if (elements[0] === '&') {
  1636. elements.shift();
  1637. }
  1638. } else {
  1639. elements = [];
  1640. }
  1641. return this.mixinElements_ = elements;
  1642. }
  1643. }, {
  1644. key: "isJustParentSelector",
  1645. value: function isJustParentSelector() {
  1646. return !this.mediaEmpty && this.elements.length === 1 && this.elements[0].value === '&' && (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
  1647. }
  1648. }, {
  1649. key: "eval",
  1650. value: function _eval(context) {
  1651. var evaldCondition = this.condition && this.condition.eval(context);
  1652. var elements = this.elements;
  1653. var extendList = this.extendList;
  1654. elements = elements && elements.map(function (e) {
  1655. return e.eval(context);
  1656. });
  1657. extendList = extendList && extendList.map(function (extend) {
  1658. return extend.eval(context);
  1659. });
  1660. return this.createDerived(elements, extendList, evaldCondition);
  1661. }
  1662. }, {
  1663. key: "genCSS",
  1664. value: function genCSS(context, output) {
  1665. var i;
  1666. var element;
  1667. if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
  1668. output.add(' ', this.fileInfo(), this.getIndex());
  1669. }
  1670. for (i = 0; i < this.elements.length; i++) {
  1671. element = this.elements[i];
  1672. element.genCSS(context, output);
  1673. }
  1674. }
  1675. }, {
  1676. key: "getIsOutput",
  1677. value: function getIsOutput() {
  1678. return this.evaldCondition;
  1679. }
  1680. }]);
  1681. return Selector;
  1682. }(Node);
  1683. Selector.prototype.type = 'Selector';
  1684. var Value =
  1685. /*#__PURE__*/
  1686. function (_Node) {
  1687. _inherits(Value, _Node);
  1688. function Value(value) {
  1689. var _this;
  1690. _classCallCheck(this, Value);
  1691. _this = _possibleConstructorReturn(this, _getPrototypeOf(Value).call(this));
  1692. if (!value) {
  1693. throw new Error('Value requires an array argument');
  1694. }
  1695. if (!Array.isArray(value)) {
  1696. _this.value = [value];
  1697. } else {
  1698. _this.value = value;
  1699. }
  1700. return _this;
  1701. }
  1702. _createClass(Value, [{
  1703. key: "accept",
  1704. value: function accept(visitor) {
  1705. if (this.value) {
  1706. this.value = visitor.visitArray(this.value);
  1707. }
  1708. }
  1709. }, {
  1710. key: "eval",
  1711. value: function _eval(context) {
  1712. if (this.value.length === 1) {
  1713. return this.value[0].eval(context);
  1714. } else {
  1715. return new Value(this.value.map(function (v) {
  1716. return v.eval(context);
  1717. }));
  1718. }
  1719. }
  1720. }, {
  1721. key: "genCSS",
  1722. value: function genCSS(context, output) {
  1723. var i;
  1724. for (i = 0; i < this.value.length; i++) {
  1725. this.value[i].genCSS(context, output);
  1726. if (i + 1 < this.value.length) {
  1727. output.add(context && context.compress ? ',' : ', ');
  1728. }
  1729. }
  1730. }
  1731. }]);
  1732. return Value;
  1733. }(Node);
  1734. Value.prototype.type = 'Value';
  1735. var Keyword =
  1736. /*#__PURE__*/
  1737. function (_Node) {
  1738. _inherits(Keyword, _Node);
  1739. function Keyword(value) {
  1740. var _this;
  1741. _classCallCheck(this, Keyword);
  1742. _this = _possibleConstructorReturn(this, _getPrototypeOf(Keyword).call(this));
  1743. _this.value = value;
  1744. return _this;
  1745. }
  1746. _createClass(Keyword, [{
  1747. key: "genCSS",
  1748. value: function genCSS(context, output) {
  1749. if (this.value === '%') {
  1750. throw {
  1751. type: 'Syntax',
  1752. message: 'Invalid % without number'
  1753. };
  1754. }
  1755. output.add(this.value);
  1756. }
  1757. }]);
  1758. return Keyword;
  1759. }(Node);
  1760. Keyword.prototype.type = 'Keyword';
  1761. Keyword.True = new Keyword('true');
  1762. Keyword.False = new Keyword('false');
  1763. var Anonymous =
  1764. /*#__PURE__*/
  1765. function (_Node) {
  1766. _inherits(Anonymous, _Node);
  1767. function Anonymous(value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
  1768. var _this;
  1769. _classCallCheck(this, Anonymous);
  1770. _this = _possibleConstructorReturn(this, _getPrototypeOf(Anonymous).call(this));
  1771. _this.value = value;
  1772. _this._index = index;
  1773. _this._fileInfo = currentFileInfo;
  1774. _this.mapLines = mapLines;
  1775. _this.rulesetLike = typeof rulesetLike === 'undefined' ? false : rulesetLike;
  1776. _this.allowRoot = true;
  1777. _this.copyVisibilityInfo(visibilityInfo);
  1778. return _this;
  1779. }
  1780. _createClass(Anonymous, [{
  1781. key: "eval",
  1782. value: function _eval() {
  1783. return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
  1784. }
  1785. }, {
  1786. key: "compare",
  1787. value: function compare(other) {
  1788. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  1789. }
  1790. }, {
  1791. key: "isRulesetLike",
  1792. value: function isRulesetLike() {
  1793. return this.rulesetLike;
  1794. }
  1795. }, {
  1796. key: "genCSS",
  1797. value: function genCSS(context, output) {
  1798. this.nodeVisible = Boolean(this.value);
  1799. if (this.nodeVisible) {
  1800. output.add(this.value, this._fileInfo, this._index, this.mapLines);
  1801. }
  1802. }
  1803. }]);
  1804. return Anonymous;
  1805. }(Node);
  1806. Anonymous.prototype.type = 'Anonymous';
  1807. var MATH = Math$1;
  1808. var Declaration =
  1809. /*#__PURE__*/
  1810. function (_Node) {
  1811. _inherits(Declaration, _Node);
  1812. function Declaration(name, value, important, merge, index, currentFileInfo, inline, variable) {
  1813. var _this;
  1814. _classCallCheck(this, Declaration);
  1815. _this = _possibleConstructorReturn(this, _getPrototypeOf(Declaration).call(this));
  1816. _this.name = name;
  1817. _this.value = value instanceof Node ? value : new Value([value ? new Anonymous(value) : null]);
  1818. _this.important = important ? ` ${important.trim()}` : '';
  1819. _this.merge = merge;
  1820. _this._index = index;
  1821. _this._fileInfo = currentFileInfo;
  1822. _this.inline = inline || false;
  1823. _this.variable = variable !== undefined ? variable : name.charAt && name.charAt(0) === '@';
  1824. _this.allowRoot = true;
  1825. _this.setParent(_this.value, _assertThisInitialized(_this));
  1826. return _this;
  1827. }
  1828. _createClass(Declaration, [{
  1829. key: "genCSS",
  1830. value: function genCSS(context, output) {
  1831. output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
  1832. try {
  1833. this.value.genCSS(context, output);
  1834. } catch (e) {
  1835. e.index = this._index;
  1836. e.filename = this._fileInfo.filename;
  1837. throw e;
  1838. }
  1839. output.add(this.important + (this.inline || context.lastRule && context.compress ? '' : ';'), this._fileInfo, this._index);
  1840. }
  1841. }, {
  1842. key: "eval",
  1843. value: function _eval(context) {
  1844. var mathBypass = false;
  1845. var prevMath;
  1846. var name = this.name;
  1847. var evaldValue;
  1848. var variable = this.variable;
  1849. if (typeof name !== 'string') {
  1850. // expand 'primitive' name directly to get
  1851. // things faster (~10% for benchmark.less):
  1852. name = name.length === 1 && name[0] instanceof Keyword ? name[0].value : evalName(context, name);
  1853. variable = false; // never treat expanded interpolation as new variable name
  1854. } // @todo remove when parens-division is default
  1855. if (name === 'font' && context.math === MATH.ALWAYS) {
  1856. mathBypass = true;
  1857. prevMath = context.math;
  1858. context.math = MATH.PARENS_DIVISION;
  1859. }
  1860. try {
  1861. context.importantScope.push({});
  1862. evaldValue = this.value.eval(context);
  1863. if (!this.variable && evaldValue.type === 'DetachedRuleset') {
  1864. throw {
  1865. message: 'Rulesets cannot be evaluated on a property.',
  1866. index: this.getIndex(),
  1867. filename: this.fileInfo().filename
  1868. };
  1869. }
  1870. var important = this.important;
  1871. var importantResult = context.importantScope.pop();
  1872. if (!important && importantResult.important) {
  1873. important = importantResult.important;
  1874. }
  1875. return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
  1876. } catch (e) {
  1877. if (typeof e.index !== 'number') {
  1878. e.index = this.getIndex();
  1879. e.filename = this.fileInfo().filename;
  1880. }
  1881. throw e;
  1882. } finally {
  1883. if (mathBypass) {
  1884. context.math = prevMath;
  1885. }
  1886. }
  1887. }
  1888. }, {
  1889. key: "makeImportant",
  1890. value: function makeImportant() {
  1891. return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
  1892. }
  1893. }]);
  1894. return Declaration;
  1895. }(Node);
  1896. function evalName(context, name) {
  1897. var value = '';
  1898. var i;
  1899. var n = name.length;
  1900. var output = {
  1901. add: function add(s) {
  1902. value += s;
  1903. }
  1904. };
  1905. for (i = 0; i < n; i++) {
  1906. name[i].eval(context).genCSS(context, output);
  1907. }
  1908. return value;
  1909. }
  1910. Declaration.prototype.type = 'Declaration';
  1911. var debugInfo = function debugInfo(context, ctx, lineSeparator) {
  1912. var result = '';
  1913. if (context.dumpLineNumbers && !context.compress) {
  1914. switch (context.dumpLineNumbers) {
  1915. case 'comments':
  1916. result = debugInfo.asComment(ctx);
  1917. break;
  1918. case 'mediaquery':
  1919. result = debugInfo.asMediaQuery(ctx);
  1920. break;
  1921. case 'all':
  1922. result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx);
  1923. break;
  1924. }
  1925. }
  1926. return result;
  1927. };
  1928. debugInfo.asComment = function (ctx) {
  1929. return `/* line ${ctx.debugInfo.lineNumber}, ${ctx.debugInfo.fileName} */\n`;
  1930. };
  1931. debugInfo.asMediaQuery = function (ctx) {
  1932. var filenameWithProtocol = ctx.debugInfo.fileName;
  1933. if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
  1934. filenameWithProtocol = `file://${filenameWithProtocol}`;
  1935. }
  1936. return `@media -sass-debug-info{filename{font-family:${filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
  1937. if (a == '\\') {
  1938. a = '\/';
  1939. }
  1940. return `\\${a}`;
  1941. })}}line{font-family:\\00003${ctx.debugInfo.lineNumber}}}\n`;
  1942. };
  1943. var Comment =
  1944. /*#__PURE__*/
  1945. function (_Node) {
  1946. _inherits(Comment, _Node);
  1947. function Comment(value, isLineComment, index, currentFileInfo) {
  1948. var _this;
  1949. _classCallCheck(this, Comment);
  1950. _this = _possibleConstructorReturn(this, _getPrototypeOf(Comment).call(this));
  1951. _this.value = value;
  1952. _this.isLineComment = isLineComment;
  1953. _this._index = index;
  1954. _this._fileInfo = currentFileInfo;
  1955. _this.allowRoot = true;
  1956. return _this;
  1957. }
  1958. _createClass(Comment, [{
  1959. key: "genCSS",
  1960. value: function genCSS(context, output) {
  1961. if (this.debugInfo) {
  1962. output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
  1963. }
  1964. output.add(this.value);
  1965. }
  1966. }, {
  1967. key: "isSilent",
  1968. value: function isSilent(context) {
  1969. var isCompressed = context.compress && this.value[2] !== '!';
  1970. return this.isLineComment || isCompressed;
  1971. }
  1972. }]);
  1973. return Comment;
  1974. }(Node);
  1975. Comment.prototype.type = 'Comment';
  1976. var contexts = {};
  1977. var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
  1978. if (!original) {
  1979. return;
  1980. }
  1981. for (var i = 0; i < propertiesToCopy.length; i++) {
  1982. if (original.hasOwnProperty(propertiesToCopy[i])) {
  1983. destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
  1984. }
  1985. }
  1986. };
  1987. /*
  1988. parse is used whilst parsing
  1989. */
  1990. var parseCopyProperties = [// options
  1991. 'paths', // option - unmodified - paths to search for imports on
  1992. 'rewriteUrls', // option - whether to adjust URL's to be relative
  1993. 'rootpath', // option - rootpath to append to URL's
  1994. 'strictImports', // option -
  1995. 'insecure', // option - whether to allow imports from insecure ssl hosts
  1996. 'dumpLineNumbers', // option - whether to dump line numbers
  1997. 'compress', // option - whether to compress
  1998. 'syncImport', // option - whether to import synchronously
  1999. 'chunkInput', // option - whether to chunk input. more performant but causes parse issues.
  2000. 'mime', // browser only - mime type for sheet import
  2001. 'useFileCache', // browser only - whether to use the per file session cache
  2002. // context
  2003. 'processImports', // option & context - whether to process imports. if false then imports will not be imported.
  2004. // Used by the import manager to stop multiple import visitors being created.
  2005. 'pluginManager' // Used as the plugin manager for the session
  2006. ];
  2007. contexts.Parse = function (options) {
  2008. copyFromOriginal(options, this, parseCopyProperties);
  2009. if (typeof this.paths === 'string') {
  2010. this.paths = [this.paths];
  2011. }
  2012. };
  2013. var evalCopyProperties = ['paths', // additional include paths
  2014. 'compress', // whether to compress
  2015. 'math', // whether math has to be within parenthesis
  2016. 'strictUnits', // whether units need to evaluate correctly
  2017. 'sourceMap', // whether to output a source map
  2018. 'importMultiple', // whether we are currently importing multiple copies
  2019. 'urlArgs', // whether to add args into url tokens
  2020. 'javascriptEnabled', // option - whether Inline JavaScript is enabled. if undefined, defaults to false
  2021. 'pluginManager', // Used as the plugin manager for the session
  2022. 'importantScope', // used to bubble up !important statements
  2023. 'rewriteUrls' // option - whether to adjust URL's to be relative
  2024. ];
  2025. function isPathRelative(path) {
  2026. return !/^(?:[a-z-]+:|\/|#)/i.test(path);
  2027. }
  2028. function isPathLocalRelative(path) {
  2029. return path.charAt(0) === '.';
  2030. }
  2031. contexts.Eval =
  2032. /*#__PURE__*/
  2033. function () {
  2034. function _class(options, frames) {
  2035. _classCallCheck(this, _class);
  2036. copyFromOriginal(options, this, evalCopyProperties);
  2037. if (typeof this.paths === 'string') {
  2038. this.paths = [this.paths];
  2039. }
  2040. this.frames = frames || [];
  2041. this.importantScope = this.importantScope || [];
  2042. this.inCalc = false;
  2043. this.mathOn = true;
  2044. }
  2045. _createClass(_class, [{
  2046. key: "enterCalc",
  2047. value: function enterCalc() {
  2048. if (!this.calcStack) {
  2049. this.calcStack = [];
  2050. }
  2051. this.calcStack.push(true);
  2052. this.inCalc = true;
  2053. }
  2054. }, {
  2055. key: "exitCalc",
  2056. value: function exitCalc() {
  2057. this.calcStack.pop();
  2058. if (!this.calcStack) {
  2059. this.inCalc = false;
  2060. }
  2061. }
  2062. }, {
  2063. key: "inParenthesis",
  2064. value: function inParenthesis() {
  2065. if (!this.parensStack) {
  2066. this.parensStack = [];
  2067. }
  2068. this.parensStack.push(true);
  2069. }
  2070. }, {
  2071. key: "outOfParenthesis",
  2072. value: function outOfParenthesis() {
  2073. this.parensStack.pop();
  2074. }
  2075. }, {
  2076. key: "isMathOn",
  2077. value: function isMathOn(op) {
  2078. if (!this.mathOn) {
  2079. return false;
  2080. }
  2081. if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
  2082. return false;
  2083. }
  2084. if (this.math > Math$1.PARENS_DIVISION) {
  2085. return this.parensStack && this.parensStack.length;
  2086. }
  2087. return true;
  2088. }
  2089. }, {
  2090. key: "pathRequiresRewrite",
  2091. value: function pathRequiresRewrite(path) {
  2092. var isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
  2093. return isRelative(path);
  2094. }
  2095. }, {
  2096. key: "rewritePath",
  2097. value: function rewritePath(path, rootpath) {
  2098. var newPath;
  2099. rootpath = rootpath || '';
  2100. newPath = this.normalizePath(rootpath + path); // If a path was explicit relative and the rootpath was not an absolute path
  2101. // we must ensure that the new path is also explicit relative.
  2102. if (isPathLocalRelative(path) && isPathRelative(rootpath) && isPathLocalRelative(newPath) === false) {
  2103. newPath = `./${newPath}`;
  2104. }
  2105. return newPath;
  2106. }
  2107. }, {
  2108. key: "normalizePath",
  2109. value: function normalizePath(path) {
  2110. var segments = path.split('/').reverse();
  2111. var segment;
  2112. path = [];
  2113. while (segments.length !== 0) {
  2114. segment = segments.pop();
  2115. switch (segment) {
  2116. case '.':
  2117. break;
  2118. case '..':
  2119. if (path.length === 0 || path[path.length - 1] === '..') {
  2120. path.push(segment);
  2121. } else {
  2122. path.pop();
  2123. }
  2124. break;
  2125. default:
  2126. path.push(segment);
  2127. break;
  2128. }
  2129. }
  2130. return path.join('/');
  2131. }
  2132. }]);
  2133. return _class;
  2134. }();
  2135. function makeRegistry(base) {
  2136. return {
  2137. _data: {},
  2138. add: function add(name, func) {
  2139. // precautionary case conversion, as later querying of
  2140. // the registry by function-caller uses lower case as well.
  2141. name = name.toLowerCase();
  2142. if (this._data.hasOwnProperty(name)) ;
  2143. this._data[name] = func;
  2144. },
  2145. addMultiple: function addMultiple(functions) {
  2146. var _this = this;
  2147. Object.keys(functions).forEach(function (name) {
  2148. _this.add(name, functions[name]);
  2149. });
  2150. },
  2151. get: function get(name) {
  2152. return this._data[name] || base && base.get(name);
  2153. },
  2154. getLocalFunctions: function getLocalFunctions() {
  2155. return this._data;
  2156. },
  2157. inherit: function inherit() {
  2158. return makeRegistry(this);
  2159. },
  2160. create: function create(base) {
  2161. return makeRegistry(base);
  2162. }
  2163. };
  2164. }
  2165. var functionRegistry = makeRegistry(null);
  2166. var defaultFunc = {
  2167. eval: function _eval() {
  2168. var v = this.value_;
  2169. var e = this.error_;
  2170. if (e) {
  2171. throw e;
  2172. }
  2173. if (v != null) {
  2174. return v ? Keyword.True : Keyword.False;
  2175. }
  2176. },
  2177. value: function value(v) {
  2178. this.value_ = v;
  2179. },
  2180. error: function error(e) {
  2181. this.error_ = e;
  2182. },
  2183. reset: function reset() {
  2184. this.value_ = this.error_ = null;
  2185. }
  2186. };
  2187. var Ruleset =
  2188. /*#__PURE__*/
  2189. function (_Node) {
  2190. _inherits(Ruleset, _Node);
  2191. function Ruleset(selectors, rules, strictImports, visibilityInfo) {
  2192. var _this;
  2193. _classCallCheck(this, Ruleset);
  2194. _this = _possibleConstructorReturn(this, _getPrototypeOf(Ruleset).call(this));
  2195. _this.selectors = selectors;
  2196. _this.rules = rules;
  2197. _this._lookups = {};
  2198. _this._variables = null;
  2199. _this._properties = null;
  2200. _this.strictImports = strictImports;
  2201. _this.copyVisibilityInfo(visibilityInfo);
  2202. _this.allowRoot = true;
  2203. _this.setParent(_this.selectors, _assertThisInitialized(_this));
  2204. _this.setParent(_this.rules, _assertThisInitialized(_this));
  2205. return _this;
  2206. }
  2207. _createClass(Ruleset, [{
  2208. key: "isRulesetLike",
  2209. value: function isRulesetLike() {
  2210. return true;
  2211. }
  2212. }, {
  2213. key: "accept",
  2214. value: function accept(visitor) {
  2215. if (this.paths) {
  2216. this.paths = visitor.visitArray(this.paths, true);
  2217. } else if (this.selectors) {
  2218. this.selectors = visitor.visitArray(this.selectors);
  2219. }
  2220. if (this.rules && this.rules.length) {
  2221. this.rules = visitor.visitArray(this.rules);
  2222. }
  2223. }
  2224. }, {
  2225. key: "eval",
  2226. value: function _eval(context) {
  2227. var selectors;
  2228. var selCnt;
  2229. var selector;
  2230. var i;
  2231. var hasVariable;
  2232. var hasOnePassingSelector = false;
  2233. if (this.selectors && (selCnt = this.selectors.length)) {
  2234. selectors = new Array(selCnt);
  2235. defaultFunc.error({
  2236. type: 'Syntax',
  2237. message: 'it is currently only allowed in parametric mixin guards,'
  2238. });
  2239. for (i = 0; i < selCnt; i++) {
  2240. selector = this.selectors[i].eval(context);
  2241. for (var j = 0; j < selector.elements.length; j++) {
  2242. if (selector.elements[j].isVariable) {
  2243. hasVariable = true;
  2244. break;
  2245. }
  2246. }
  2247. selectors[i] = selector;
  2248. if (selector.evaldCondition) {
  2249. hasOnePassingSelector = true;
  2250. }
  2251. }
  2252. if (hasVariable) {
  2253. var toParseSelectors = new Array(selCnt);
  2254. for (i = 0; i < selCnt; i++) {
  2255. selector = selectors[i];
  2256. toParseSelectors[i] = selector.toCSS(context);
  2257. }
  2258. this.parse.parseNode(toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function (err, result) {
  2259. if (result) {
  2260. selectors = flattenArray(result);
  2261. }
  2262. });
  2263. }
  2264. defaultFunc.reset();
  2265. } else {
  2266. hasOnePassingSelector = true;
  2267. }
  2268. var rules = this.rules ? copyArray(this.rules) : null;
  2269. var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
  2270. var rule;
  2271. var subRule;
  2272. ruleset.originalRuleset = this;
  2273. ruleset.root = this.root;
  2274. ruleset.firstRoot = this.firstRoot;
  2275. ruleset.allowImports = this.allowImports;
  2276. if (this.debugInfo) {
  2277. ruleset.debugInfo = this.debugInfo;
  2278. }
  2279. if (!hasOnePassingSelector) {
  2280. rules.length = 0;
  2281. } // inherit a function registry from the frames stack when possible;
  2282. // otherwise from the global registry
  2283. ruleset.functionRegistry = function (frames) {
  2284. var i = 0;
  2285. var n = frames.length;
  2286. var found;
  2287. for (; i !== n; ++i) {
  2288. found = frames[i].functionRegistry;
  2289. if (found) {
  2290. return found;
  2291. }
  2292. }
  2293. return functionRegistry;
  2294. }(context.frames).inherit(); // push the current ruleset to the frames stack
  2295. var ctxFrames = context.frames;
  2296. ctxFrames.unshift(ruleset); // currrent selectors
  2297. var ctxSelectors = context.selectors;
  2298. if (!ctxSelectors) {
  2299. context.selectors = ctxSelectors = [];
  2300. }
  2301. ctxSelectors.unshift(this.selectors); // Evaluate imports
  2302. if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
  2303. ruleset.evalImports(context);
  2304. } // Store the frames around mixin definitions,
  2305. // so they can be evaluated like closures when the time comes.
  2306. var rsRules = ruleset.rules;
  2307. for (i = 0; rule = rsRules[i]; i++) {
  2308. if (rule.evalFirst) {
  2309. rsRules[i] = rule.eval(context);
  2310. }
  2311. }
  2312. var mediaBlockCount = context.mediaBlocks && context.mediaBlocks.length || 0; // Evaluate mixin calls.
  2313. for (i = 0; rule = rsRules[i]; i++) {
  2314. if (rule.type === 'MixinCall') {
  2315. /* jshint loopfunc:true */
  2316. rules = rule.eval(context).filter(function (r) {
  2317. if (r instanceof Declaration && r.variable) {
  2318. // do not pollute the scope if the variable is
  2319. // already there. consider returning false here
  2320. // but we need a way to "return" variable from mixins
  2321. return !ruleset.variable(r.name);
  2322. }
  2323. return true;
  2324. });
  2325. rsRules.splice.apply(rsRules, _toConsumableArray([i, 1].concat(rules)));
  2326. i += rules.length - 1;
  2327. ruleset.resetCache();
  2328. } else if (rule.type === 'VariableCall') {
  2329. /* jshint loopfunc:true */
  2330. rules = rule.eval(context).rules.filter(function (r) {
  2331. if (r instanceof Declaration && r.variable) {
  2332. // do not pollute the scope at all
  2333. return false;
  2334. }
  2335. return true;
  2336. });
  2337. rsRules.splice.apply(rsRules, _toConsumableArray([i, 1].concat(rules)));
  2338. i += rules.length - 1;
  2339. ruleset.resetCache();
  2340. }
  2341. } // Evaluate everything else
  2342. for (i = 0; rule = rsRules[i]; i++) {
  2343. if (!rule.evalFirst) {
  2344. rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
  2345. }
  2346. } // Evaluate everything else
  2347. for (i = 0; rule = rsRules[i]; i++) {
  2348. // for rulesets, check if it is a css guard and can be removed
  2349. if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
  2350. // check if it can be folded in (e.g. & where)
  2351. if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
  2352. rsRules.splice(i--, 1);
  2353. for (var j = 0; subRule = rule.rules[j]; j++) {
  2354. if (subRule instanceof Node) {
  2355. subRule.copyVisibilityInfo(rule.visibilityInfo());
  2356. if (!(subRule instanceof Declaration) || !subRule.variable) {
  2357. rsRules.splice(++i, 0, subRule);
  2358. }
  2359. }
  2360. }
  2361. }
  2362. }
  2363. } // Pop the stack
  2364. ctxFrames.shift();
  2365. ctxSelectors.shift();
  2366. if (context.mediaBlocks) {
  2367. for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
  2368. context.mediaBlocks[i].bubbleSelectors(selectors);
  2369. }
  2370. }
  2371. return ruleset;
  2372. }
  2373. }, {
  2374. key: "evalImports",
  2375. value: function evalImports(context) {
  2376. var rules = this.rules;
  2377. var i;
  2378. var importRules;
  2379. if (!rules) {
  2380. return;
  2381. }
  2382. for (i = 0; i < rules.length; i++) {
  2383. if (rules[i].type === 'Import') {
  2384. importRules = rules[i].eval(context);
  2385. if (importRules && (importRules.length || importRules.length === 0)) {
  2386. rules.splice.apply(rules, _toConsumableArray([i, 1].concat(importRules)));
  2387. i += importRules.length - 1;
  2388. } else {
  2389. rules.splice(i, 1, importRules);
  2390. }
  2391. this.resetCache();
  2392. }
  2393. }
  2394. }
  2395. }, {
  2396. key: "makeImportant",
  2397. value: function makeImportant() {
  2398. var result = new Ruleset(this.selectors, this.rules.map(function (r) {
  2399. if (r.makeImportant) {
  2400. return r.makeImportant();
  2401. } else {
  2402. return r;
  2403. }
  2404. }), this.strictImports, this.visibilityInfo());
  2405. return result;
  2406. }
  2407. }, {
  2408. key: "matchArgs",
  2409. value: function matchArgs(args) {
  2410. return !args || args.length === 0;
  2411. } // lets you call a css selector with a guard
  2412. }, {
  2413. key: "matchCondition",
  2414. value: function matchCondition(args, context) {
  2415. var lastSelector = this.selectors[this.selectors.length - 1];
  2416. if (!lastSelector.evaldCondition) {
  2417. return false;
  2418. }
  2419. if (lastSelector.condition && !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
  2420. return false;
  2421. }
  2422. return true;
  2423. }
  2424. }, {
  2425. key: "resetCache",
  2426. value: function resetCache() {
  2427. this._rulesets = null;
  2428. this._variables = null;
  2429. this._properties = null;
  2430. this._lookups = {};
  2431. }
  2432. }, {
  2433. key: "variables",
  2434. value: function variables() {
  2435. if (!this._variables) {
  2436. this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  2437. if (r instanceof Declaration && r.variable === true) {
  2438. hash[r.name] = r;
  2439. } // when evaluating variables in an import statement, imports have not been eval'd
  2440. // so we need to go inside import statements.
  2441. // guard against root being a string (in the case of inlined less)
  2442. if (r.type === 'Import' && r.root && r.root.variables) {
  2443. var vars = r.root.variables();
  2444. for (var name in vars) {
  2445. if (vars.hasOwnProperty(name)) {
  2446. hash[name] = r.root.variable(name);
  2447. }
  2448. }
  2449. }
  2450. return hash;
  2451. }, {});
  2452. }
  2453. return this._variables;
  2454. }
  2455. }, {
  2456. key: "properties",
  2457. value: function properties() {
  2458. if (!this._properties) {
  2459. this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  2460. if (r instanceof Declaration && r.variable !== true) {
  2461. var name = r.name.length === 1 && r.name[0] instanceof Keyword ? r.name[0].value : r.name; // Properties don't overwrite as they can merge
  2462. if (!hash[`$${name}`]) {
  2463. hash[`$${name}`] = [r];
  2464. } else {
  2465. hash[`$${name}`].push(r);
  2466. }
  2467. }
  2468. return hash;
  2469. }, {});
  2470. }
  2471. return this._properties;
  2472. }
  2473. }, {
  2474. key: "variable",
  2475. value: function variable(name) {
  2476. var decl = this.variables()[name];
  2477. if (decl) {
  2478. return this.parseValue(decl);
  2479. }
  2480. }
  2481. }, {
  2482. key: "property",
  2483. value: function property(name) {
  2484. var decl = this.properties()[name];
  2485. if (decl) {
  2486. return this.parseValue(decl);
  2487. }
  2488. }
  2489. }, {
  2490. key: "lastDeclaration",
  2491. value: function lastDeclaration() {
  2492. for (var i = this.rules.length; i > 0; i--) {
  2493. var decl = this.rules[i - 1];
  2494. if (decl instanceof Declaration) {
  2495. return this.parseValue(decl);
  2496. }
  2497. }
  2498. }
  2499. }, {
  2500. key: "parseValue",
  2501. value: function parseValue(toParse) {
  2502. var self = this;
  2503. function transformDeclaration(decl) {
  2504. if (decl.value instanceof Anonymous && !decl.parsed) {
  2505. if (typeof decl.value.value === 'string') {
  2506. this.parse.parseNode(decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
  2507. if (err) {
  2508. decl.parsed = true;
  2509. }
  2510. if (result) {
  2511. decl.value = result[0];
  2512. decl.important = result[1] || '';
  2513. decl.parsed = true;
  2514. }
  2515. });
  2516. } else {
  2517. decl.parsed = true;
  2518. }
  2519. return decl;
  2520. } else {
  2521. return decl;
  2522. }
  2523. }
  2524. if (!Array.isArray(toParse)) {
  2525. return transformDeclaration.call(self, toParse);
  2526. } else {
  2527. var nodes = [];
  2528. toParse.forEach(function (n) {
  2529. nodes.push(transformDeclaration.call(self, n));
  2530. });
  2531. return nodes;
  2532. }
  2533. }
  2534. }, {
  2535. key: "rulesets",
  2536. value: function rulesets() {
  2537. if (!this.rules) {
  2538. return [];
  2539. }
  2540. var filtRules = [];
  2541. var rules = this.rules;
  2542. var i;
  2543. var rule;
  2544. for (i = 0; rule = rules[i]; i++) {
  2545. if (rule.isRuleset) {
  2546. filtRules.push(rule);
  2547. }
  2548. }
  2549. return filtRules;
  2550. }
  2551. }, {
  2552. key: "prependRule",
  2553. value: function prependRule(rule) {
  2554. var rules = this.rules;
  2555. if (rules) {
  2556. rules.unshift(rule);
  2557. } else {
  2558. this.rules = [rule];
  2559. }
  2560. this.setParent(rule, this);
  2561. }
  2562. }, {
  2563. key: "find",
  2564. value: function find(selector) {
  2565. var self = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
  2566. var filter = arguments.length > 2 ? arguments[2] : undefined;
  2567. var rules = [];
  2568. var match;
  2569. var foundMixins;
  2570. var key = selector.toCSS();
  2571. if (key in this._lookups) {
  2572. return this._lookups[key];
  2573. }
  2574. this.rulesets().forEach(function (rule) {
  2575. if (rule !== self) {
  2576. for (var j = 0; j < rule.selectors.length; j++) {
  2577. match = selector.match(rule.selectors[j]);
  2578. if (match) {
  2579. if (selector.elements.length > match) {
  2580. if (!filter || filter(rule)) {
  2581. foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
  2582. for (var i = 0; i < foundMixins.length; ++i) {
  2583. foundMixins[i].path.push(rule);
  2584. }
  2585. Array.prototype.push.apply(rules, foundMixins);
  2586. }
  2587. } else {
  2588. rules.push({
  2589. rule,
  2590. path: []
  2591. });
  2592. }
  2593. break;
  2594. }
  2595. }
  2596. }
  2597. });
  2598. this._lookups[key] = rules;
  2599. return rules;
  2600. }
  2601. }, {
  2602. key: "genCSS",
  2603. value: function genCSS(context, output) {
  2604. var i;
  2605. var j;
  2606. var charsetRuleNodes = [];
  2607. var ruleNodes = [];
  2608. var // Line number debugging
  2609. debugInfo$1;
  2610. var rule;
  2611. var path;
  2612. context.tabLevel = context.tabLevel || 0;
  2613. if (!this.root) {
  2614. context.tabLevel++;
  2615. }
  2616. var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
  2617. var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
  2618. var sep;
  2619. var charsetNodeIndex = 0;
  2620. var importNodeIndex = 0;
  2621. for (i = 0; rule = this.rules[i]; i++) {
  2622. if (rule instanceof Comment) {
  2623. if (importNodeIndex === i) {
  2624. importNodeIndex++;
  2625. }
  2626. ruleNodes.push(rule);
  2627. } else if (rule.isCharset && rule.isCharset()) {
  2628. ruleNodes.splice(charsetNodeIndex, 0, rule);
  2629. charsetNodeIndex++;
  2630. importNodeIndex++;
  2631. } else if (rule.type === 'Import') {
  2632. ruleNodes.splice(importNodeIndex, 0, rule);
  2633. importNodeIndex++;
  2634. } else {
  2635. ruleNodes.push(rule);
  2636. }
  2637. }
  2638. ruleNodes = charsetRuleNodes.concat(ruleNodes); // If this is the root node, we don't render
  2639. // a selector, or {}.
  2640. if (!this.root) {
  2641. debugInfo$1 = debugInfo(context, this, tabSetStr);
  2642. if (debugInfo$1) {
  2643. output.add(debugInfo$1);
  2644. output.add(tabSetStr);
  2645. }
  2646. var paths = this.paths;
  2647. var pathCnt = paths.length;
  2648. var pathSubCnt;
  2649. sep = context.compress ? ',' : `,\n${tabSetStr}`;
  2650. for (i = 0; i < pathCnt; i++) {
  2651. path = paths[i];
  2652. if (!(pathSubCnt = path.length)) {
  2653. continue;
  2654. }
  2655. if (i > 0) {
  2656. output.add(sep);
  2657. }
  2658. context.firstSelector = true;
  2659. path[0].genCSS(context, output);
  2660. context.firstSelector = false;
  2661. for (j = 1; j < pathSubCnt; j++) {
  2662. path[j].genCSS(context, output);
  2663. }
  2664. }
  2665. output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
  2666. } // Compile rules and rulesets
  2667. for (i = 0; rule = ruleNodes[i]; i++) {
  2668. if (i + 1 === ruleNodes.length) {
  2669. context.lastRule = true;
  2670. }
  2671. var currentLastRule = context.lastRule;
  2672. if (rule.isRulesetLike(rule)) {
  2673. context.lastRule = false;
  2674. }
  2675. if (rule.genCSS) {
  2676. rule.genCSS(context, output);
  2677. } else if (rule.value) {
  2678. output.add(rule.value.toString());
  2679. }
  2680. context.lastRule = currentLastRule;
  2681. if (!context.lastRule && rule.isVisible()) {
  2682. output.add(context.compress ? '' : `\n${tabRuleStr}`);
  2683. } else {
  2684. context.lastRule = false;
  2685. }
  2686. }
  2687. if (!this.root) {
  2688. output.add(context.compress ? '}' : `\n${tabSetStr}}`);
  2689. context.tabLevel--;
  2690. }
  2691. if (!output.isEmpty() && !context.compress && this.firstRoot) {
  2692. output.add('\n');
  2693. }
  2694. }
  2695. }, {
  2696. key: "joinSelectors",
  2697. value: function joinSelectors(paths, context, selectors) {
  2698. for (var s = 0; s < selectors.length; s++) {
  2699. this.joinSelector(paths, context, selectors[s]);
  2700. }
  2701. }
  2702. }, {
  2703. key: "joinSelector",
  2704. value: function joinSelector(paths, context, selector) {
  2705. function createParenthesis(elementsToPak, originalElement) {
  2706. var replacementParen;
  2707. var j;
  2708. if (elementsToPak.length === 0) {
  2709. replacementParen = new Paren(elementsToPak[0]);
  2710. } else {
  2711. var insideParent = new Array(elementsToPak.length);
  2712. for (j = 0; j < elementsToPak.length; j++) {
  2713. insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  2714. }
  2715. replacementParen = new Paren(new Selector(insideParent));
  2716. }
  2717. return replacementParen;
  2718. }
  2719. function createSelector(containedElement, originalElement) {
  2720. var element;
  2721. var selector;
  2722. element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  2723. selector = new Selector([element]);
  2724. return selector;
  2725. } // joins selector path from `beginningPath` with selector path in `addPath`
  2726. // `replacedElement` contains element that is being replaced by `addPath`
  2727. // returns concatenated path
  2728. function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
  2729. var newSelectorPath;
  2730. var lastSelector;
  2731. var newJoinedSelector; // our new selector path
  2732. newSelectorPath = []; // construct the joined selector - if & is the first thing this will be empty,
  2733. // if not newJoinedSelector will be the last set of elements in the selector
  2734. if (beginningPath.length > 0) {
  2735. newSelectorPath = copyArray(beginningPath);
  2736. lastSelector = newSelectorPath.pop();
  2737. newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
  2738. } else {
  2739. newJoinedSelector = originalSelector.createDerived([]);
  2740. }
  2741. if (addPath.length > 0) {
  2742. // /deep/ is a CSS4 selector - (removed, so should deprecate)
  2743. // that is valid without anything in front of it
  2744. // so if the & does not have a combinator that is "" or " " then
  2745. // and there is a combinator on the parent, then grab that.
  2746. // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
  2747. var combinator = replacedElement.combinator;
  2748. var parentEl = addPath[0].elements[0];
  2749. if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
  2750. combinator = parentEl.combinator;
  2751. } // join the elements so far with the first part of the parent
  2752. newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
  2753. newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
  2754. } // now add the joined selector - but only if it is not empty
  2755. if (newJoinedSelector.elements.length !== 0) {
  2756. newSelectorPath.push(newJoinedSelector);
  2757. } // put together the parent selectors after the join (e.g. the rest of the parent)
  2758. if (addPath.length > 1) {
  2759. var restOfPath = addPath.slice(1);
  2760. restOfPath = restOfPath.map(function (selector) {
  2761. return selector.createDerived(selector.elements, []);
  2762. });
  2763. newSelectorPath = newSelectorPath.concat(restOfPath);
  2764. }
  2765. return newSelectorPath;
  2766. } // joins selector path from `beginningPath` with every selector path in `addPaths` array
  2767. // `replacedElement` contains element that is being replaced by `addPath`
  2768. // returns array with all concatenated paths
  2769. function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
  2770. var j;
  2771. for (j = 0; j < beginningPath.length; j++) {
  2772. var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
  2773. result.push(newSelectorPath);
  2774. }
  2775. return result;
  2776. }
  2777. function mergeElementsOnToSelectors(elements, selectors) {
  2778. var i;
  2779. var sel;
  2780. if (elements.length === 0) {
  2781. return;
  2782. }
  2783. if (selectors.length === 0) {
  2784. selectors.push([new Selector(elements)]);
  2785. return;
  2786. }
  2787. for (i = 0; sel = selectors[i]; i++) {
  2788. // if the previous thing in sel is a parent this needs to join on to it
  2789. if (sel.length > 0) {
  2790. sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
  2791. } else {
  2792. sel.push(new Selector(elements));
  2793. }
  2794. }
  2795. } // replace all parent selectors inside `inSelector` by content of `context` array
  2796. // resulting selectors are returned inside `paths` array
  2797. // returns true if `inSelector` contained at least one parent selector
  2798. function replaceParentSelector(paths, context, inSelector) {
  2799. // The paths are [[Selector]]
  2800. // The first list is a list of comma separated selectors
  2801. // The inner list is a list of inheritance separated selectors
  2802. // e.g.
  2803. // .a, .b {
  2804. // .c {
  2805. // }
  2806. // }
  2807. // == [[.a] [.c]] [[.b] [.c]]
  2808. //
  2809. var i;
  2810. var j;
  2811. var k;
  2812. var currentElements;
  2813. var newSelectors;
  2814. var selectorsMultiplied;
  2815. var sel;
  2816. var el;
  2817. var hadParentSelector = false;
  2818. var length;
  2819. var lastSelector;
  2820. function findNestedSelector(element) {
  2821. var maybeSelector;
  2822. if (!(element.value instanceof Paren)) {
  2823. return null;
  2824. }
  2825. maybeSelector = element.value.value;
  2826. if (!(maybeSelector instanceof Selector)) {
  2827. return null;
  2828. }
  2829. return maybeSelector;
  2830. } // the elements from the current selector so far
  2831. currentElements = []; // the current list of new selectors to add to the path.
  2832. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
  2833. // by the parents
  2834. newSelectors = [[]];
  2835. for (i = 0; el = inSelector.elements[i]; i++) {
  2836. // non parent reference elements just get added
  2837. if (el.value !== '&') {
  2838. var nestedSelector = findNestedSelector(el);
  2839. if (nestedSelector != null) {
  2840. // merge the current list of non parent selector elements
  2841. // on to the current list of selectors to add
  2842. mergeElementsOnToSelectors(currentElements, newSelectors);
  2843. var nestedPaths = [];
  2844. var replaced = void 0;
  2845. var replacedNewSelectors = [];
  2846. replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
  2847. hadParentSelector = hadParentSelector || replaced; // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
  2848. for (k = 0; k < nestedPaths.length; k++) {
  2849. var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
  2850. addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
  2851. }
  2852. newSelectors = replacedNewSelectors;
  2853. currentElements = [];
  2854. } else {
  2855. currentElements.push(el);
  2856. }
  2857. } else {
  2858. hadParentSelector = true; // the new list of selectors to add
  2859. selectorsMultiplied = []; // merge the current list of non parent selector elements
  2860. // on to the current list of selectors to add
  2861. mergeElementsOnToSelectors(currentElements, newSelectors); // loop through our current selectors
  2862. for (j = 0; j < newSelectors.length; j++) {
  2863. sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used
  2864. // whether there are parents or not
  2865. if (context.length === 0) {
  2866. // the combinator used on el should now be applied to the next element instead so that
  2867. // it is not lost
  2868. if (sel.length > 0) {
  2869. sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
  2870. }
  2871. selectorsMultiplied.push(sel);
  2872. } else {
  2873. // and the parent selectors
  2874. for (k = 0; k < context.length; k++) {
  2875. // We need to put the current selectors
  2876. // then join the last selector's elements on to the parents selectors
  2877. var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector); // add that to our new set of selectors
  2878. selectorsMultiplied.push(newSelectorPath);
  2879. }
  2880. }
  2881. } // our new selectors has been multiplied, so reset the state
  2882. newSelectors = selectorsMultiplied;
  2883. currentElements = [];
  2884. }
  2885. } // if we have any elements left over (e.g. .a& .b == .b)
  2886. // add them on to all the current selectors
  2887. mergeElementsOnToSelectors(currentElements, newSelectors);
  2888. for (i = 0; i < newSelectors.length; i++) {
  2889. length = newSelectors[i].length;
  2890. if (length > 0) {
  2891. paths.push(newSelectors[i]);
  2892. lastSelector = newSelectors[i][length - 1];
  2893. newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
  2894. }
  2895. }
  2896. return hadParentSelector;
  2897. }
  2898. function deriveSelector(visibilityInfo, deriveFrom) {
  2899. var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
  2900. newSelector.copyVisibilityInfo(visibilityInfo);
  2901. return newSelector;
  2902. } // joinSelector code follows
  2903. var i;
  2904. var newPaths;
  2905. var hadParentSelector;
  2906. newPaths = [];
  2907. hadParentSelector = replaceParentSelector(newPaths, context, selector);
  2908. if (!hadParentSelector) {
  2909. if (context.length > 0) {
  2910. newPaths = [];
  2911. for (i = 0; i < context.length; i++) {
  2912. var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
  2913. concatenated.push(selector);
  2914. newPaths.push(concatenated);
  2915. }
  2916. } else {
  2917. newPaths = [[selector]];
  2918. }
  2919. }
  2920. for (i = 0; i < newPaths.length; i++) {
  2921. paths.push(newPaths[i]);
  2922. }
  2923. }
  2924. }]);
  2925. return Ruleset;
  2926. }(Node);
  2927. Ruleset.prototype.type = 'Ruleset';
  2928. Ruleset.prototype.isRuleset = true;
  2929. var AtRule =
  2930. /*#__PURE__*/
  2931. function (_Node) {
  2932. _inherits(AtRule, _Node);
  2933. function AtRule(name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
  2934. var _this;
  2935. _classCallCheck(this, AtRule);
  2936. _this = _possibleConstructorReturn(this, _getPrototypeOf(AtRule).call(this));
  2937. var i;
  2938. _this.name = name;
  2939. _this.value = value instanceof Node ? value : value ? new Anonymous(value) : value;
  2940. if (rules) {
  2941. if (Array.isArray(rules)) {
  2942. _this.rules = rules;
  2943. } else {
  2944. _this.rules = [rules];
  2945. _this.rules[0].selectors = new Selector([], null, null, index, currentFileInfo).createEmptySelectors();
  2946. }
  2947. for (i = 0; i < _this.rules.length; i++) {
  2948. _this.rules[i].allowImports = true;
  2949. }
  2950. _this.setParent(_this.rules, _assertThisInitialized(_this));
  2951. }
  2952. _this._index = index;
  2953. _this._fileInfo = currentFileInfo;
  2954. _this.debugInfo = debugInfo;
  2955. _this.isRooted = isRooted || false;
  2956. _this.copyVisibilityInfo(visibilityInfo);
  2957. _this.allowRoot = true;
  2958. return _this;
  2959. }
  2960. _createClass(AtRule, [{
  2961. key: "accept",
  2962. value: function accept(visitor) {
  2963. var value = this.value;
  2964. var rules = this.rules;
  2965. if (rules) {
  2966. this.rules = visitor.visitArray(rules);
  2967. }
  2968. if (value) {
  2969. this.value = visitor.visit(value);
  2970. }
  2971. }
  2972. }, {
  2973. key: "isRulesetLike",
  2974. value: function isRulesetLike() {
  2975. return this.rules || !this.isCharset();
  2976. }
  2977. }, {
  2978. key: "isCharset",
  2979. value: function isCharset() {
  2980. return '@charset' === this.name;
  2981. }
  2982. }, {
  2983. key: "genCSS",
  2984. value: function genCSS(context, output) {
  2985. var value = this.value;
  2986. var rules = this.rules;
  2987. output.add(this.name, this.fileInfo(), this.getIndex());
  2988. if (value) {
  2989. output.add(' ');
  2990. value.genCSS(context, output);
  2991. }
  2992. if (rules) {
  2993. this.outputRuleset(context, output, rules);
  2994. } else {
  2995. output.add(';');
  2996. }
  2997. }
  2998. }, {
  2999. key: "eval",
  3000. value: function _eval(context) {
  3001. var mediaPathBackup;
  3002. var mediaBlocksBackup;
  3003. var value = this.value;
  3004. var rules = this.rules; // media stored inside other atrule should not bubble over it
  3005. // backpup media bubbling information
  3006. mediaPathBackup = context.mediaPath;
  3007. mediaBlocksBackup = context.mediaBlocks; // deleted media bubbling information
  3008. context.mediaPath = [];
  3009. context.mediaBlocks = [];
  3010. if (value) {
  3011. value = value.eval(context);
  3012. }
  3013. if (rules) {
  3014. // assuming that there is only one rule at this point - that is how parser constructs the rule
  3015. rules = [rules[0].eval(context)];
  3016. rules[0].root = true;
  3017. } // restore media bubbling information
  3018. context.mediaPath = mediaPathBackup;
  3019. context.mediaBlocks = mediaBlocksBackup;
  3020. return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
  3021. }
  3022. }, {
  3023. key: "variable",
  3024. value: function variable(name) {
  3025. if (this.rules) {
  3026. // assuming that there is only one rule at this point - that is how parser constructs the rule
  3027. return Ruleset.prototype.variable.call(this.rules[0], name);
  3028. }
  3029. }
  3030. }, {
  3031. key: "find",
  3032. value: function find() {
  3033. if (this.rules) {
  3034. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3035. args[_key] = arguments[_key];
  3036. }
  3037. // assuming that there is only one rule at this point - that is how parser constructs the rule
  3038. return Ruleset.prototype.find.apply(this.rules[0], args);
  3039. }
  3040. }
  3041. }, {
  3042. key: "rulesets",
  3043. value: function rulesets() {
  3044. if (this.rules) {
  3045. // assuming that there is only one rule at this point - that is how parser constructs the rule
  3046. return Ruleset.prototype.rulesets.apply(this.rules[0]);
  3047. }
  3048. }
  3049. }, {
  3050. key: "outputRuleset",
  3051. value: function outputRuleset(context, output, rules) {
  3052. var ruleCnt = rules.length;
  3053. var i;
  3054. context.tabLevel = (context.tabLevel | 0) + 1; // Compressed
  3055. if (context.compress) {
  3056. output.add('{');
  3057. for (i = 0; i < ruleCnt; i++) {
  3058. rules[i].genCSS(context, output);
  3059. }
  3060. output.add('}');
  3061. context.tabLevel--;
  3062. return;
  3063. } // Non-compressed
  3064. var tabSetStr = `\n${Array(context.tabLevel).join(' ')}`;
  3065. var tabRuleStr = `${tabSetStr} `;
  3066. if (!ruleCnt) {
  3067. output.add(` {${tabSetStr}}`);
  3068. } else {
  3069. output.add(` {${tabRuleStr}`);
  3070. rules[0].genCSS(context, output);
  3071. for (i = 1; i < ruleCnt; i++) {
  3072. output.add(tabRuleStr);
  3073. rules[i].genCSS(context, output);
  3074. }
  3075. output.add(`${tabSetStr}}`);
  3076. }
  3077. context.tabLevel--;
  3078. }
  3079. }]);
  3080. return AtRule;
  3081. }(Node);
  3082. AtRule.prototype.type = 'AtRule';
  3083. var DetachedRuleset =
  3084. /*#__PURE__*/
  3085. function (_Node) {
  3086. _inherits(DetachedRuleset, _Node);
  3087. function DetachedRuleset(ruleset, frames) {
  3088. var _this;
  3089. _classCallCheck(this, DetachedRuleset);
  3090. _this = _possibleConstructorReturn(this, _getPrototypeOf(DetachedRuleset).call(this));
  3091. _this.ruleset = ruleset;
  3092. _this.frames = frames;
  3093. _this.setParent(_this.ruleset, _assertThisInitialized(_this));
  3094. return _this;
  3095. }
  3096. _createClass(DetachedRuleset, [{
  3097. key: "accept",
  3098. value: function accept(visitor) {
  3099. this.ruleset = visitor.visit(this.ruleset);
  3100. }
  3101. }, {
  3102. key: "eval",
  3103. value: function _eval(context) {
  3104. var frames = this.frames || copyArray(context.frames);
  3105. return new DetachedRuleset(this.ruleset, frames);
  3106. }
  3107. }, {
  3108. key: "callEval",
  3109. value: function callEval(context) {
  3110. return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
  3111. }
  3112. }]);
  3113. return DetachedRuleset;
  3114. }(Node);
  3115. DetachedRuleset.prototype.type = 'DetachedRuleset';
  3116. DetachedRuleset.prototype.evalFirst = true;
  3117. var Unit =
  3118. /*#__PURE__*/
  3119. function (_Node) {
  3120. _inherits(Unit, _Node);
  3121. function Unit(numerator, denominator, backupUnit) {
  3122. var _this;
  3123. _classCallCheck(this, Unit);
  3124. _this = _possibleConstructorReturn(this, _getPrototypeOf(Unit).call(this));
  3125. _this.numerator = numerator ? copyArray(numerator).sort() : [];
  3126. _this.denominator = denominator ? copyArray(denominator).sort() : [];
  3127. if (backupUnit) {
  3128. _this.backupUnit = backupUnit;
  3129. } else if (numerator && numerator.length) {
  3130. _this.backupUnit = numerator[0];
  3131. }
  3132. return _this;
  3133. }
  3134. _createClass(Unit, [{
  3135. key: "clone",
  3136. value: function clone() {
  3137. return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
  3138. }
  3139. }, {
  3140. key: "genCSS",
  3141. value: function genCSS(context, output) {
  3142. // Dimension checks the unit is singular and throws an error if in strict math mode.
  3143. var strictUnits = context && context.strictUnits;
  3144. if (this.numerator.length === 1) {
  3145. output.add(this.numerator[0]); // the ideal situation
  3146. } else if (!strictUnits && this.backupUnit) {
  3147. output.add(this.backupUnit);
  3148. } else if (!strictUnits && this.denominator.length) {
  3149. output.add(this.denominator[0]);
  3150. }
  3151. }
  3152. }, {
  3153. key: "toString",
  3154. value: function toString() {
  3155. var i;
  3156. var returnStr = this.numerator.join('*');
  3157. for (i = 0; i < this.denominator.length; i++) {
  3158. returnStr += `/${this.denominator[i]}`;
  3159. }
  3160. return returnStr;
  3161. }
  3162. }, {
  3163. key: "compare",
  3164. value: function compare(other) {
  3165. return this.is(other.toString()) ? 0 : undefined;
  3166. }
  3167. }, {
  3168. key: "is",
  3169. value: function is(unitString) {
  3170. return this.toString().toUpperCase() === unitString.toUpperCase();
  3171. }
  3172. }, {
  3173. key: "isLength",
  3174. value: function isLength() {
  3175. return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
  3176. }
  3177. }, {
  3178. key: "isEmpty",
  3179. value: function isEmpty() {
  3180. return this.numerator.length === 0 && this.denominator.length === 0;
  3181. }
  3182. }, {
  3183. key: "isSingular",
  3184. value: function isSingular() {
  3185. return this.numerator.length <= 1 && this.denominator.length === 0;
  3186. }
  3187. }, {
  3188. key: "map",
  3189. value: function map(callback) {
  3190. var i;
  3191. for (i = 0; i < this.numerator.length; i++) {
  3192. this.numerator[i] = callback(this.numerator[i], false);
  3193. }
  3194. for (i = 0; i < this.denominator.length; i++) {
  3195. this.denominator[i] = callback(this.denominator[i], true);
  3196. }
  3197. }
  3198. }, {
  3199. key: "usedUnits",
  3200. value: function usedUnits() {
  3201. var group;
  3202. var result = {};
  3203. var mapUnit;
  3204. var groupName;
  3205. mapUnit = function mapUnit(atomicUnit) {
  3206. /* jshint loopfunc:true */
  3207. if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
  3208. result[groupName] = atomicUnit;
  3209. }
  3210. return atomicUnit;
  3211. };
  3212. for (groupName in unitConversions) {
  3213. if (unitConversions.hasOwnProperty(groupName)) {
  3214. group = unitConversions[groupName];
  3215. this.map(mapUnit);
  3216. }
  3217. }
  3218. return result;
  3219. }
  3220. }, {
  3221. key: "cancel",
  3222. value: function cancel() {
  3223. var counter = {};
  3224. var atomicUnit;
  3225. var i;
  3226. for (i = 0; i < this.numerator.length; i++) {
  3227. atomicUnit = this.numerator[i];
  3228. counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
  3229. }
  3230. for (i = 0; i < this.denominator.length; i++) {
  3231. atomicUnit = this.denominator[i];
  3232. counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
  3233. }
  3234. this.numerator = [];
  3235. this.denominator = [];
  3236. for (atomicUnit in counter) {
  3237. if (counter.hasOwnProperty(atomicUnit)) {
  3238. var count = counter[atomicUnit];
  3239. if (count > 0) {
  3240. for (i = 0; i < count; i++) {
  3241. this.numerator.push(atomicUnit);
  3242. }
  3243. } else if (count < 0) {
  3244. for (i = 0; i < -count; i++) {
  3245. this.denominator.push(atomicUnit);
  3246. }
  3247. }
  3248. }
  3249. }
  3250. this.numerator.sort();
  3251. this.denominator.sort();
  3252. }
  3253. }]);
  3254. return Unit;
  3255. }(Node);
  3256. Unit.prototype.type = 'Unit';
  3257. // A number with a unit
  3258. //
  3259. var Dimension =
  3260. /*#__PURE__*/
  3261. function (_Node) {
  3262. _inherits(Dimension, _Node);
  3263. function Dimension(value, unit) {
  3264. var _this;
  3265. _classCallCheck(this, Dimension);
  3266. _this = _possibleConstructorReturn(this, _getPrototypeOf(Dimension).call(this));
  3267. _this.value = parseFloat(value);
  3268. if (isNaN(_this.value)) {
  3269. throw new Error('Dimension is not a number.');
  3270. }
  3271. _this.unit = unit && unit instanceof Unit ? unit : new Unit(unit ? [unit] : undefined);
  3272. _this.setParent(_this.unit, _assertThisInitialized(_this));
  3273. return _this;
  3274. }
  3275. _createClass(Dimension, [{
  3276. key: "accept",
  3277. value: function accept(visitor) {
  3278. this.unit = visitor.visit(this.unit);
  3279. }
  3280. }, {
  3281. key: "eval",
  3282. value: function _eval(context) {
  3283. return this;
  3284. }
  3285. }, {
  3286. key: "toColor",
  3287. value: function toColor() {
  3288. return new Color([this.value, this.value, this.value]);
  3289. }
  3290. }, {
  3291. key: "genCSS",
  3292. value: function genCSS(context, output) {
  3293. if (context && context.strictUnits && !this.unit.isSingular()) {
  3294. throw new Error(`Multiple units in dimension. Correct the units or use the unit function. Bad unit: ${this.unit.toString()}`);
  3295. }
  3296. var value = this.fround(context, this.value);
  3297. var strValue = String(value);
  3298. if (value !== 0 && value < 0.000001 && value > -0.000001) {
  3299. // would be output 1e-6 etc.
  3300. strValue = value.toFixed(20).replace(/0+$/, '');
  3301. }
  3302. if (context && context.compress) {
  3303. // Zero values doesn't need a unit
  3304. if (value === 0 && this.unit.isLength()) {
  3305. output.add(strValue);
  3306. return;
  3307. } // Float values doesn't need a leading zero
  3308. if (value > 0 && value < 1) {
  3309. strValue = strValue.substr(1);
  3310. }
  3311. }
  3312. output.add(strValue);
  3313. this.unit.genCSS(context, output);
  3314. } // In an operation between two Dimensions,
  3315. // we default to the first Dimension's unit,
  3316. // so `1px + 2` will yield `3px`.
  3317. }, {
  3318. key: "operate",
  3319. value: function operate(context, op, other) {
  3320. /* jshint noempty:false */
  3321. var value = this._operate(context, op, this.value, other.value);
  3322. var unit = this.unit.clone();
  3323. if (op === '+' || op === '-') {
  3324. if (unit.numerator.length === 0 && unit.denominator.length === 0) {
  3325. unit = other.unit.clone();
  3326. if (this.unit.backupUnit) {
  3327. unit.backupUnit = this.unit.backupUnit;
  3328. }
  3329. } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ; else {
  3330. other = other.convertTo(this.unit.usedUnits());
  3331. if (context.strictUnits && other.unit.toString() !== unit.toString()) {
  3332. throw new Error(`Incompatible units. Change the units or use the unit function. ` + `Bad units: '${unit.toString()}' and '${other.unit.toString()}'.`);
  3333. }
  3334. value = this._operate(context, op, this.value, other.value);
  3335. }
  3336. } else if (op === '*') {
  3337. unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
  3338. unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
  3339. unit.cancel();
  3340. } else if (op === '/') {
  3341. unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
  3342. unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
  3343. unit.cancel();
  3344. }
  3345. return new Dimension(value, unit);
  3346. }
  3347. }, {
  3348. key: "compare",
  3349. value: function compare(other) {
  3350. var a;
  3351. var b;
  3352. if (!(other instanceof Dimension)) {
  3353. return undefined;
  3354. }
  3355. if (this.unit.isEmpty() || other.unit.isEmpty()) {
  3356. a = this;
  3357. b = other;
  3358. } else {
  3359. a = this.unify();
  3360. b = other.unify();
  3361. if (a.unit.compare(b.unit) !== 0) {
  3362. return undefined;
  3363. }
  3364. }
  3365. return Node.numericCompare(a.value, b.value);
  3366. }
  3367. }, {
  3368. key: "unify",
  3369. value: function unify() {
  3370. return this.convertTo({
  3371. length: 'px',
  3372. duration: 's',
  3373. angle: 'rad'
  3374. });
  3375. }
  3376. }, {
  3377. key: "convertTo",
  3378. value: function convertTo(conversions) {
  3379. var value = this.value;
  3380. var unit = this.unit.clone();
  3381. var i;
  3382. var groupName;
  3383. var group;
  3384. var targetUnit;
  3385. var derivedConversions = {};
  3386. var applyUnit;
  3387. if (typeof conversions === 'string') {
  3388. for (i in unitConversions) {
  3389. if (unitConversions[i].hasOwnProperty(conversions)) {
  3390. derivedConversions = {};
  3391. derivedConversions[i] = conversions;
  3392. }
  3393. }
  3394. conversions = derivedConversions;
  3395. }
  3396. applyUnit = function applyUnit(atomicUnit, denominator) {
  3397. /* jshint loopfunc:true */
  3398. if (group.hasOwnProperty(atomicUnit)) {
  3399. if (denominator) {
  3400. value = value / (group[atomicUnit] / group[targetUnit]);
  3401. } else {
  3402. value = value * (group[atomicUnit] / group[targetUnit]);
  3403. }
  3404. return targetUnit;
  3405. }
  3406. return atomicUnit;
  3407. };
  3408. for (groupName in conversions) {
  3409. if (conversions.hasOwnProperty(groupName)) {
  3410. targetUnit = conversions[groupName];
  3411. group = unitConversions[groupName];
  3412. unit.map(applyUnit);
  3413. }
  3414. }
  3415. unit.cancel();
  3416. return new Dimension(value, unit);
  3417. }
  3418. }]);
  3419. return Dimension;
  3420. }(Node);
  3421. Dimension.prototype.type = 'Dimension';
  3422. var MATH$1 = Math$1;
  3423. var Operation =
  3424. /*#__PURE__*/
  3425. function (_Node) {
  3426. _inherits(Operation, _Node);
  3427. function Operation(op, operands, isSpaced) {
  3428. var _this;
  3429. _classCallCheck(this, Operation);
  3430. _this = _possibleConstructorReturn(this, _getPrototypeOf(Operation).call(this));
  3431. _this.op = op.trim();
  3432. _this.operands = operands;
  3433. _this.isSpaced = isSpaced;
  3434. return _this;
  3435. }
  3436. _createClass(Operation, [{
  3437. key: "accept",
  3438. value: function accept(visitor) {
  3439. this.operands = visitor.visitArray(this.operands);
  3440. }
  3441. }, {
  3442. key: "eval",
  3443. value: function _eval(context) {
  3444. var a = this.operands[0].eval(context);
  3445. var b = this.operands[1].eval(context);
  3446. var op;
  3447. if (context.isMathOn(this.op)) {
  3448. op = this.op === './' ? '/' : this.op;
  3449. if (a instanceof Dimension && b instanceof Color) {
  3450. a = a.toColor();
  3451. }
  3452. if (b instanceof Dimension && a instanceof Color) {
  3453. b = b.toColor();
  3454. }
  3455. if (!a.operate) {
  3456. if (a instanceof Operation && a.op === '/' && context.math === MATH$1.PARENS_DIVISION) {
  3457. return new Operation(this.op, [a, b], this.isSpaced);
  3458. }
  3459. throw {
  3460. type: 'Operation',
  3461. message: 'Operation on an invalid type'
  3462. };
  3463. }
  3464. return a.operate(context, op, b);
  3465. } else {
  3466. return new Operation(this.op, [a, b], this.isSpaced);
  3467. }
  3468. }
  3469. }, {
  3470. key: "genCSS",
  3471. value: function genCSS(context, output) {
  3472. this.operands[0].genCSS(context, output);
  3473. if (this.isSpaced) {
  3474. output.add(' ');
  3475. }
  3476. output.add(this.op);
  3477. if (this.isSpaced) {
  3478. output.add(' ');
  3479. }
  3480. this.operands[1].genCSS(context, output);
  3481. }
  3482. }]);
  3483. return Operation;
  3484. }(Node);
  3485. Operation.prototype.type = 'Operation';
  3486. var MATH$2 = Math$1;
  3487. var Expression =
  3488. /*#__PURE__*/
  3489. function (_Node) {
  3490. _inherits(Expression, _Node);
  3491. function Expression(value, noSpacing) {
  3492. var _this;
  3493. _classCallCheck(this, Expression);
  3494. _this = _possibleConstructorReturn(this, _getPrototypeOf(Expression).call(this));
  3495. _this.value = value;
  3496. _this.noSpacing = noSpacing;
  3497. if (!value) {
  3498. throw new Error('Expression requires an array parameter');
  3499. }
  3500. return _this;
  3501. }
  3502. _createClass(Expression, [{
  3503. key: "accept",
  3504. value: function accept(visitor) {
  3505. this.value = visitor.visitArray(this.value);
  3506. }
  3507. }, {
  3508. key: "eval",
  3509. value: function _eval(context) {
  3510. var returnValue;
  3511. var mathOn = context.isMathOn();
  3512. var inParenthesis = this.parens && (context.math !== MATH$2.STRICT_LEGACY || !this.parensInOp);
  3513. var doubleParen = false;
  3514. if (inParenthesis) {
  3515. context.inParenthesis();
  3516. }
  3517. if (this.value.length > 1) {
  3518. returnValue = new Expression(this.value.map(function (e) {
  3519. if (!e.eval) {
  3520. return e;
  3521. }
  3522. return e.eval(context);
  3523. }), this.noSpacing);
  3524. } else if (this.value.length === 1) {
  3525. if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
  3526. doubleParen = true;
  3527. }
  3528. returnValue = this.value[0].eval(context);
  3529. } else {
  3530. returnValue = this;
  3531. }
  3532. if (inParenthesis) {
  3533. context.outOfParenthesis();
  3534. }
  3535. if (this.parens && this.parensInOp && !mathOn && !doubleParen && !(returnValue instanceof Dimension)) {
  3536. returnValue = new Paren(returnValue);
  3537. }
  3538. return returnValue;
  3539. }
  3540. }, {
  3541. key: "genCSS",
  3542. value: function genCSS(context, output) {
  3543. for (var i = 0; i < this.value.length; i++) {
  3544. this.value[i].genCSS(context, output);
  3545. if (!this.noSpacing && i + 1 < this.value.length) {
  3546. output.add(' ');
  3547. }
  3548. }
  3549. }
  3550. }, {
  3551. key: "throwAwayComments",
  3552. value: function throwAwayComments() {
  3553. this.value = this.value.filter(function (v) {
  3554. return !(v instanceof Comment);
  3555. });
  3556. }
  3557. }]);
  3558. return Expression;
  3559. }(Node);
  3560. Expression.prototype.type = 'Expression';
  3561. var functionCaller =
  3562. /*#__PURE__*/
  3563. function () {
  3564. function functionCaller(name, context, index, currentFileInfo) {
  3565. _classCallCheck(this, functionCaller);
  3566. this.name = name.toLowerCase();
  3567. this.index = index;
  3568. this.context = context;
  3569. this.currentFileInfo = currentFileInfo;
  3570. this.func = context.frames[0].functionRegistry.get(this.name);
  3571. }
  3572. _createClass(functionCaller, [{
  3573. key: "isValid",
  3574. value: function isValid() {
  3575. return Boolean(this.func);
  3576. }
  3577. }, {
  3578. key: "call",
  3579. value: function call(args) {
  3580. // This code is terrible and should be replaced as per this issue...
  3581. // https://github.com/less/less.js/issues/2477
  3582. if (Array.isArray(args)) {
  3583. args = args.filter(function (item) {
  3584. if (item.type === 'Comment') {
  3585. return false;
  3586. }
  3587. return true;
  3588. }).map(function (item) {
  3589. if (item.type === 'Expression') {
  3590. var subNodes = item.value.filter(function (item) {
  3591. if (item.type === 'Comment') {
  3592. return false;
  3593. }
  3594. return true;
  3595. });
  3596. if (subNodes.length === 1) {
  3597. return subNodes[0];
  3598. } else {
  3599. return new Expression(subNodes);
  3600. }
  3601. }
  3602. return item;
  3603. });
  3604. }
  3605. return this.func.apply(this, _toConsumableArray(args));
  3606. }
  3607. }]);
  3608. return functionCaller;
  3609. }();
  3610. // A function call node.
  3611. //
  3612. var Call =
  3613. /*#__PURE__*/
  3614. function (_Node) {
  3615. _inherits(Call, _Node);
  3616. function Call(name, args, index, currentFileInfo) {
  3617. var _this;
  3618. _classCallCheck(this, Call);
  3619. _this = _possibleConstructorReturn(this, _getPrototypeOf(Call).call(this));
  3620. _this.name = name;
  3621. _this.args = args;
  3622. _this.calc = name === 'calc';
  3623. _this._index = index;
  3624. _this._fileInfo = currentFileInfo;
  3625. return _this;
  3626. }
  3627. _createClass(Call, [{
  3628. key: "accept",
  3629. value: function accept(visitor) {
  3630. if (this.args) {
  3631. this.args = visitor.visitArray(this.args);
  3632. }
  3633. } //
  3634. // When evaluating a function call,
  3635. // we either find the function in the functionRegistry,
  3636. // in which case we call it, passing the evaluated arguments,
  3637. // if this returns null or we cannot find the function, we
  3638. // simply print it out as it appeared originally [2].
  3639. //
  3640. // The reason why we evaluate the arguments, is in the case where
  3641. // we try to pass a variable to a function, like: `saturate(@color)`.
  3642. // The function should receive the value, not the variable.
  3643. //
  3644. }, {
  3645. key: "eval",
  3646. value: function _eval(context) {
  3647. /**
  3648. * Turn off math for calc(), and switch back on for evaluating nested functions
  3649. */
  3650. var currentMathContext = context.mathOn;
  3651. context.mathOn = !this.calc;
  3652. if (this.calc || context.inCalc) {
  3653. context.enterCalc();
  3654. }
  3655. var args = this.args.map(function (a) {
  3656. return a.eval(context);
  3657. });
  3658. if (this.calc || context.inCalc) {
  3659. context.exitCalc();
  3660. }
  3661. context.mathOn = currentMathContext;
  3662. var result;
  3663. var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
  3664. if (funcCaller.isValid()) {
  3665. try {
  3666. result = funcCaller.call(args);
  3667. } catch (e) {
  3668. throw {
  3669. type: e.type || 'Runtime',
  3670. message: `error evaluating function \`${this.name}\`${e.message ? `: ${e.message}` : ''}`,
  3671. index: this.getIndex(),
  3672. filename: this.fileInfo().filename,
  3673. line: e.lineNumber,
  3674. column: e.columnNumber
  3675. };
  3676. }
  3677. if (result !== null && result !== undefined) {
  3678. // Results that that are not nodes are cast as Anonymous nodes
  3679. // Falsy values or booleans are returned as empty nodes
  3680. if (!(result instanceof Node)) {
  3681. if (!result || result === true) {
  3682. result = new Anonymous(null);
  3683. } else {
  3684. result = new Anonymous(result.toString());
  3685. }
  3686. }
  3687. result._index = this._index;
  3688. result._fileInfo = this._fileInfo;
  3689. return result;
  3690. }
  3691. }
  3692. return new Call(this.name, args, this.getIndex(), this.fileInfo());
  3693. }
  3694. }, {
  3695. key: "genCSS",
  3696. value: function genCSS(context, output) {
  3697. output.add(`${this.name}(`, this.fileInfo(), this.getIndex());
  3698. for (var i = 0; i < this.args.length; i++) {
  3699. this.args[i].genCSS(context, output);
  3700. if (i + 1 < this.args.length) {
  3701. output.add(', ');
  3702. }
  3703. }
  3704. output.add(')');
  3705. }
  3706. }]);
  3707. return Call;
  3708. }(Node);
  3709. Call.prototype.type = 'Call';
  3710. var Variable =
  3711. /*#__PURE__*/
  3712. function (_Node) {
  3713. _inherits(Variable, _Node);
  3714. function Variable(name, index, currentFileInfo) {
  3715. var _this;
  3716. _classCallCheck(this, Variable);
  3717. _this = _possibleConstructorReturn(this, _getPrototypeOf(Variable).call(this));
  3718. _this.name = name;
  3719. _this._index = index;
  3720. _this._fileInfo = currentFileInfo;
  3721. return _this;
  3722. }
  3723. _createClass(Variable, [{
  3724. key: "eval",
  3725. value: function _eval(context) {
  3726. var variable;
  3727. var name = this.name;
  3728. if (name.indexOf('@@') === 0) {
  3729. name = `@${new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value}`;
  3730. }
  3731. if (this.evaluating) {
  3732. throw {
  3733. type: 'Name',
  3734. message: `Recursive variable definition for ${name}`,
  3735. filename: this.fileInfo().filename,
  3736. index: this.getIndex()
  3737. };
  3738. }
  3739. this.evaluating = true;
  3740. variable = this.find(context.frames, function (frame) {
  3741. var v = frame.variable(name);
  3742. if (v) {
  3743. if (v.important) {
  3744. var importantScope = context.importantScope[context.importantScope.length - 1];
  3745. importantScope.important = v.important;
  3746. } // If in calc, wrap vars in a function call to cascade evaluate args first
  3747. if (context.inCalc) {
  3748. return new Call('_SELF', [v.value]).eval(context);
  3749. } else {
  3750. return v.value.eval(context);
  3751. }
  3752. }
  3753. });
  3754. if (variable) {
  3755. this.evaluating = false;
  3756. return variable;
  3757. } else {
  3758. throw {
  3759. type: 'Name',
  3760. message: `variable ${name} is undefined`,
  3761. filename: this.fileInfo().filename,
  3762. index: this.getIndex()
  3763. };
  3764. }
  3765. }
  3766. }, {
  3767. key: "find",
  3768. value: function find(obj, fun) {
  3769. for (var i = 0, r; i < obj.length; i++) {
  3770. r = fun.call(obj, obj[i]);
  3771. if (r) {
  3772. return r;
  3773. }
  3774. }
  3775. return null;
  3776. }
  3777. }]);
  3778. return Variable;
  3779. }(Node);
  3780. Variable.prototype.type = 'Variable';
  3781. var Property =
  3782. /*#__PURE__*/
  3783. function (_Node) {
  3784. _inherits(Property, _Node);
  3785. function Property(name, index, currentFileInfo) {
  3786. var _this;
  3787. _classCallCheck(this, Property);
  3788. _this = _possibleConstructorReturn(this, _getPrototypeOf(Property).call(this));
  3789. _this.name = name;
  3790. _this._index = index;
  3791. _this._fileInfo = currentFileInfo;
  3792. return _this;
  3793. }
  3794. _createClass(Property, [{
  3795. key: "eval",
  3796. value: function _eval(context) {
  3797. var property;
  3798. var name = this.name; // TODO: shorten this reference
  3799. var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
  3800. if (this.evaluating) {
  3801. throw {
  3802. type: 'Name',
  3803. message: `Recursive property reference for ${name}`,
  3804. filename: this.fileInfo().filename,
  3805. index: this.getIndex()
  3806. };
  3807. }
  3808. this.evaluating = true;
  3809. property = this.find(context.frames, function (frame) {
  3810. var v;
  3811. var vArr = frame.property(name);
  3812. if (vArr) {
  3813. for (var i = 0; i < vArr.length; i++) {
  3814. v = vArr[i];
  3815. vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
  3816. }
  3817. mergeRules(vArr);
  3818. v = vArr[vArr.length - 1];
  3819. if (v.important) {
  3820. var importantScope = context.importantScope[context.importantScope.length - 1];
  3821. importantScope.important = v.important;
  3822. }
  3823. v = v.value.eval(context);
  3824. return v;
  3825. }
  3826. });
  3827. if (property) {
  3828. this.evaluating = false;
  3829. return property;
  3830. } else {
  3831. throw {
  3832. type: 'Name',
  3833. message: `Property '${name}' is undefined`,
  3834. filename: this.currentFileInfo.filename,
  3835. index: this.index
  3836. };
  3837. }
  3838. }
  3839. }, {
  3840. key: "find",
  3841. value: function find(obj, fun) {
  3842. for (var i = 0, r; i < obj.length; i++) {
  3843. r = fun.call(obj, obj[i]);
  3844. if (r) {
  3845. return r;
  3846. }
  3847. }
  3848. return null;
  3849. }
  3850. }]);
  3851. return Property;
  3852. }(Node);
  3853. Property.prototype.type = 'Property';
  3854. var Attribute =
  3855. /*#__PURE__*/
  3856. function (_Node) {
  3857. _inherits(Attribute, _Node);
  3858. function Attribute(key, op, value) {
  3859. var _this;
  3860. _classCallCheck(this, Attribute);
  3861. _this = _possibleConstructorReturn(this, _getPrototypeOf(Attribute).call(this));
  3862. _this.key = key;
  3863. _this.op = op;
  3864. _this.value = value;
  3865. return _this;
  3866. }
  3867. _createClass(Attribute, [{
  3868. key: "eval",
  3869. value: function _eval(context) {
  3870. return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, this.value && this.value.eval ? this.value.eval(context) : this.value);
  3871. }
  3872. }, {
  3873. key: "genCSS",
  3874. value: function genCSS(context, output) {
  3875. output.add(this.toCSS(context));
  3876. }
  3877. }, {
  3878. key: "toCSS",
  3879. value: function toCSS(context) {
  3880. var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
  3881. if (this.op) {
  3882. value += this.op;
  3883. value += this.value.toCSS ? this.value.toCSS(context) : this.value;
  3884. }
  3885. return `[${value}]`;
  3886. }
  3887. }]);
  3888. return Attribute;
  3889. }(Node);
  3890. Attribute.prototype.type = 'Attribute';
  3891. var Quoted =
  3892. /*#__PURE__*/
  3893. function (_Node) {
  3894. _inherits(Quoted, _Node);
  3895. function Quoted(str, content, escaped, index, currentFileInfo) {
  3896. var _this;
  3897. _classCallCheck(this, Quoted);
  3898. _this = _possibleConstructorReturn(this, _getPrototypeOf(Quoted).call(this));
  3899. _this.escaped = escaped == null ? true : escaped;
  3900. _this.value = content || '';
  3901. _this.quote = str.charAt(0);
  3902. _this._index = index;
  3903. _this._fileInfo = currentFileInfo;
  3904. _this.variableRegex = /@\{([\w-]+)\}/g;
  3905. _this.propRegex = /\$\{([\w-]+)\}/g;
  3906. _this.allowRoot = escaped;
  3907. return _this;
  3908. }
  3909. _createClass(Quoted, [{
  3910. key: "genCSS",
  3911. value: function genCSS(context, output) {
  3912. if (!this.escaped) {
  3913. output.add(this.quote, this.fileInfo(), this.getIndex());
  3914. }
  3915. output.add(this.value);
  3916. if (!this.escaped) {
  3917. output.add(this.quote);
  3918. }
  3919. }
  3920. }, {
  3921. key: "containsVariables",
  3922. value: function containsVariables() {
  3923. return this.value.match(this.variableRegex);
  3924. }
  3925. }, {
  3926. key: "eval",
  3927. value: function _eval(context) {
  3928. var that = this;
  3929. var value = this.value;
  3930. var variableReplacement = function variableReplacement(_, name) {
  3931. var v = new Variable(`@${name}`, that.getIndex(), that.fileInfo()).eval(context, true);
  3932. return v instanceof Quoted ? v.value : v.toCSS();
  3933. };
  3934. var propertyReplacement = function propertyReplacement(_, name) {
  3935. var v = new Property(`$${name}`, that.getIndex(), that.fileInfo()).eval(context, true);
  3936. return v instanceof Quoted ? v.value : v.toCSS();
  3937. };
  3938. function iterativeReplace(value, regexp, replacementFnc) {
  3939. var evaluatedValue = value;
  3940. do {
  3941. value = evaluatedValue.toString();
  3942. evaluatedValue = value.replace(regexp, replacementFnc);
  3943. } while (value !== evaluatedValue);
  3944. return evaluatedValue;
  3945. }
  3946. value = iterativeReplace(value, this.variableRegex, variableReplacement);
  3947. value = iterativeReplace(value, this.propRegex, propertyReplacement);
  3948. return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
  3949. }
  3950. }, {
  3951. key: "compare",
  3952. value: function compare(other) {
  3953. // when comparing quoted strings allow the quote to differ
  3954. if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
  3955. return Node.numericCompare(this.value, other.value);
  3956. } else {
  3957. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  3958. }
  3959. }
  3960. }]);
  3961. return Quoted;
  3962. }(Node);
  3963. Quoted.prototype.type = 'Quoted';
  3964. var URL =
  3965. /*#__PURE__*/
  3966. function (_Node) {
  3967. _inherits(URL, _Node);
  3968. function URL(val, index, currentFileInfo, isEvald) {
  3969. var _this;
  3970. _classCallCheck(this, URL);
  3971. _this = _possibleConstructorReturn(this, _getPrototypeOf(URL).call(this));
  3972. _this.value = val;
  3973. _this._index = index;
  3974. _this._fileInfo = currentFileInfo;
  3975. _this.isEvald = isEvald;
  3976. return _this;
  3977. }
  3978. _createClass(URL, [{
  3979. key: "accept",
  3980. value: function accept(visitor) {
  3981. this.value = visitor.visit(this.value);
  3982. }
  3983. }, {
  3984. key: "genCSS",
  3985. value: function genCSS(context, output) {
  3986. output.add('url(');
  3987. this.value.genCSS(context, output);
  3988. output.add(')');
  3989. }
  3990. }, {
  3991. key: "eval",
  3992. value: function _eval(context) {
  3993. var val = this.value.eval(context);
  3994. var rootpath;
  3995. if (!this.isEvald) {
  3996. // Add the rootpath if the URL requires a rewrite
  3997. rootpath = this.fileInfo() && this.fileInfo().rootpath;
  3998. if (typeof rootpath === 'string' && typeof val.value === 'string' && context.pathRequiresRewrite(val.value)) {
  3999. if (!val.quote) {
  4000. rootpath = escapePath(rootpath);
  4001. }
  4002. val.value = context.rewritePath(val.value, rootpath);
  4003. } else {
  4004. val.value = context.normalizePath(val.value);
  4005. } // Add url args if enabled
  4006. if (context.urlArgs) {
  4007. if (!val.value.match(/^\s*data:/)) {
  4008. var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
  4009. var urlArgs = delimiter + context.urlArgs;
  4010. if (val.value.indexOf('#') !== -1) {
  4011. val.value = val.value.replace('#', `${urlArgs}#`);
  4012. } else {
  4013. val.value += urlArgs;
  4014. }
  4015. }
  4016. }
  4017. }
  4018. return new URL(val, this.getIndex(), this.fileInfo(), true);
  4019. }
  4020. }]);
  4021. return URL;
  4022. }(Node);
  4023. URL.prototype.type = 'Url';
  4024. function escapePath(path) {
  4025. return path.replace(/[\(\)'"\s]/g, function (match) {
  4026. return `\\${match}`;
  4027. });
  4028. }
  4029. var Media =
  4030. /*#__PURE__*/
  4031. function (_AtRule) {
  4032. _inherits(Media, _AtRule);
  4033. function Media(value, features, index, currentFileInfo, visibilityInfo) {
  4034. var _this;
  4035. _classCallCheck(this, Media);
  4036. _this = _possibleConstructorReturn(this, _getPrototypeOf(Media).call(this));
  4037. _this._index = index;
  4038. _this._fileInfo = currentFileInfo;
  4039. var selectors = new Selector([], null, null, _this._index, _this._fileInfo).createEmptySelectors();
  4040. _this.features = new Value(features);
  4041. _this.rules = [new Ruleset(selectors, value)];
  4042. _this.rules[0].allowImports = true;
  4043. _this.copyVisibilityInfo(visibilityInfo);
  4044. _this.allowRoot = true;
  4045. _this.setParent(selectors, _assertThisInitialized(_this));
  4046. _this.setParent(_this.features, _assertThisInitialized(_this));
  4047. _this.setParent(_this.rules, _assertThisInitialized(_this));
  4048. return _this;
  4049. }
  4050. _createClass(Media, [{
  4051. key: "isRulesetLike",
  4052. value: function isRulesetLike() {
  4053. return true;
  4054. }
  4055. }, {
  4056. key: "accept",
  4057. value: function accept(visitor) {
  4058. if (this.features) {
  4059. this.features = visitor.visit(this.features);
  4060. }
  4061. if (this.rules) {
  4062. this.rules = visitor.visitArray(this.rules);
  4063. }
  4064. }
  4065. }, {
  4066. key: "genCSS",
  4067. value: function genCSS(context, output) {
  4068. output.add('@media ', this._fileInfo, this._index);
  4069. this.features.genCSS(context, output);
  4070. this.outputRuleset(context, output, this.rules);
  4071. }
  4072. }, {
  4073. key: "eval",
  4074. value: function _eval(context) {
  4075. if (!context.mediaBlocks) {
  4076. context.mediaBlocks = [];
  4077. context.mediaPath = [];
  4078. }
  4079. var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
  4080. if (this.debugInfo) {
  4081. this.rules[0].debugInfo = this.debugInfo;
  4082. media.debugInfo = this.debugInfo;
  4083. }
  4084. media.features = this.features.eval(context);
  4085. context.mediaPath.push(media);
  4086. context.mediaBlocks.push(media);
  4087. this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
  4088. context.frames.unshift(this.rules[0]);
  4089. media.rules = [this.rules[0].eval(context)];
  4090. context.frames.shift();
  4091. context.mediaPath.pop();
  4092. return context.mediaPath.length === 0 ? media.evalTop(context) : media.evalNested(context);
  4093. }
  4094. }, {
  4095. key: "evalTop",
  4096. value: function evalTop(context) {
  4097. var result = this; // Render all dependent Media blocks.
  4098. if (context.mediaBlocks.length > 1) {
  4099. var selectors = new Selector([], null, null, this.getIndex(), this.fileInfo()).createEmptySelectors();
  4100. result = new Ruleset(selectors, context.mediaBlocks);
  4101. result.multiMedia = true;
  4102. result.copyVisibilityInfo(this.visibilityInfo());
  4103. this.setParent(result, this);
  4104. }
  4105. delete context.mediaBlocks;
  4106. delete context.mediaPath;
  4107. return result;
  4108. }
  4109. }, {
  4110. key: "evalNested",
  4111. value: function evalNested(context) {
  4112. var i;
  4113. var value;
  4114. var path = context.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR).
  4115. for (i = 0; i < path.length; i++) {
  4116. value = path[i].features instanceof Value ? path[i].features.value : path[i].features;
  4117. path[i] = Array.isArray(value) ? value : [value];
  4118. } // Trace all permutations to generate the resulting media-query.
  4119. //
  4120. // (a, b and c) with nested (d, e) ->
  4121. // a and d
  4122. // a and e
  4123. // b and c and d
  4124. // b and c and e
  4125. this.features = new Value(this.permute(path).map(function (path) {
  4126. path = path.map(function (fragment) {
  4127. return fragment.toCSS ? fragment : new Anonymous(fragment);
  4128. });
  4129. for (i = path.length - 1; i > 0; i--) {
  4130. path.splice(i, 0, new Anonymous('and'));
  4131. }
  4132. return new Expression(path);
  4133. }));
  4134. this.setParent(this.features, this); // Fake a tree-node that doesn't output anything.
  4135. return new Ruleset([], []);
  4136. }
  4137. }, {
  4138. key: "permute",
  4139. value: function permute(arr) {
  4140. if (arr.length === 0) {
  4141. return [];
  4142. } else if (arr.length === 1) {
  4143. return arr[0];
  4144. } else {
  4145. var result = [];
  4146. var rest = this.permute(arr.slice(1));
  4147. for (var i = 0; i < rest.length; i++) {
  4148. for (var j = 0; j < arr[0].length; j++) {
  4149. result.push([arr[0][j]].concat(rest[i]));
  4150. }
  4151. }
  4152. return result;
  4153. }
  4154. }
  4155. }, {
  4156. key: "bubbleSelectors",
  4157. value: function bubbleSelectors(selectors) {
  4158. if (!selectors) {
  4159. return;
  4160. }
  4161. this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
  4162. this.setParent(this.rules, this);
  4163. }
  4164. }]);
  4165. return Media;
  4166. }(AtRule);
  4167. Media.prototype.type = 'Media';
  4168. // CSS @import node
  4169. //
  4170. // The general strategy here is that we don't want to wait
  4171. // for the parsing to be completed, before we start importing
  4172. // the file. That's because in the context of a browser,
  4173. // most of the time will be spent waiting for the server to respond.
  4174. //
  4175. // On creation, we push the import path to our import queue, though
  4176. // `import,push`, we also pass it a callback, which it'll call once
  4177. // the file has been fetched, and parsed.
  4178. //
  4179. var Import =
  4180. /*#__PURE__*/
  4181. function (_Node) {
  4182. _inherits(Import, _Node);
  4183. function Import(path, features, options, index, currentFileInfo, visibilityInfo) {
  4184. var _this;
  4185. _classCallCheck(this, Import);
  4186. _this = _possibleConstructorReturn(this, _getPrototypeOf(Import).call(this));
  4187. _this.options = options;
  4188. _this._index = index;
  4189. _this._fileInfo = currentFileInfo;
  4190. _this.path = path;
  4191. _this.features = features;
  4192. _this.allowRoot = true;
  4193. if (_this.options.less !== undefined || _this.options.inline) {
  4194. _this.css = !_this.options.less || _this.options.inline;
  4195. } else {
  4196. var pathValue = _this.getPath();
  4197. if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
  4198. _this.css = true;
  4199. }
  4200. }
  4201. _this.copyVisibilityInfo(visibilityInfo);
  4202. _this.setParent(_this.features, _assertThisInitialized(_this));
  4203. _this.setParent(_this.path, _assertThisInitialized(_this));
  4204. return _this;
  4205. }
  4206. _createClass(Import, [{
  4207. key: "accept",
  4208. value: function accept(visitor) {
  4209. if (this.features) {
  4210. this.features = visitor.visit(this.features);
  4211. }
  4212. this.path = visitor.visit(this.path);
  4213. if (!this.options.isPlugin && !this.options.inline && this.root) {
  4214. this.root = visitor.visit(this.root);
  4215. }
  4216. }
  4217. }, {
  4218. key: "genCSS",
  4219. value: function genCSS(context, output) {
  4220. if (this.css && this.path._fileInfo.reference === undefined) {
  4221. output.add('@import ', this._fileInfo, this._index);
  4222. this.path.genCSS(context, output);
  4223. if (this.features) {
  4224. output.add(' ');
  4225. this.features.genCSS(context, output);
  4226. }
  4227. output.add(';');
  4228. }
  4229. }
  4230. }, {
  4231. key: "getPath",
  4232. value: function getPath() {
  4233. return this.path instanceof URL ? this.path.value.value : this.path.value;
  4234. }
  4235. }, {
  4236. key: "isVariableImport",
  4237. value: function isVariableImport() {
  4238. var path = this.path;
  4239. if (path instanceof URL) {
  4240. path = path.value;
  4241. }
  4242. if (path instanceof Quoted) {
  4243. return path.containsVariables();
  4244. }
  4245. return true;
  4246. }
  4247. }, {
  4248. key: "evalForImport",
  4249. value: function evalForImport(context) {
  4250. var path = this.path;
  4251. if (path instanceof URL) {
  4252. path = path.value;
  4253. }
  4254. return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
  4255. }
  4256. }, {
  4257. key: "evalPath",
  4258. value: function evalPath(context) {
  4259. var path = this.path.eval(context);
  4260. var fileInfo = this._fileInfo;
  4261. if (!(path instanceof URL)) {
  4262. // Add the rootpath if the URL requires a rewrite
  4263. var pathValue = path.value;
  4264. if (fileInfo && pathValue && context.pathRequiresRewrite(pathValue)) {
  4265. path.value = context.rewritePath(pathValue, fileInfo.rootpath);
  4266. } else {
  4267. path.value = context.normalizePath(path.value);
  4268. }
  4269. }
  4270. return path;
  4271. }
  4272. }, {
  4273. key: "eval",
  4274. value: function _eval(context) {
  4275. var result = this.doEval(context);
  4276. if (this.options.reference || this.blocksVisibility()) {
  4277. if (result.length || result.length === 0) {
  4278. result.forEach(function (node) {
  4279. node.addVisibilityBlock();
  4280. });
  4281. } else {
  4282. result.addVisibilityBlock();
  4283. }
  4284. }
  4285. return result;
  4286. }
  4287. }, {
  4288. key: "doEval",
  4289. value: function doEval(context) {
  4290. var ruleset;
  4291. var registry;
  4292. var features = this.features && this.features.eval(context);
  4293. if (this.options.isPlugin) {
  4294. if (this.root && this.root.eval) {
  4295. try {
  4296. this.root.eval(context);
  4297. } catch (e) {
  4298. e.message = 'Plugin error during evaluation';
  4299. throw new LessError(e, this.root.imports, this.root.filename);
  4300. }
  4301. }
  4302. registry = context.frames[0] && context.frames[0].functionRegistry;
  4303. if (registry && this.root && this.root.functions) {
  4304. registry.addMultiple(this.root.functions);
  4305. }
  4306. return [];
  4307. }
  4308. if (this.skip) {
  4309. if (typeof this.skip === 'function') {
  4310. this.skip = this.skip();
  4311. }
  4312. if (this.skip) {
  4313. return [];
  4314. }
  4315. }
  4316. if (this.options.inline) {
  4317. var contents = new Anonymous(this.root, 0, {
  4318. filename: this.importedFilename,
  4319. reference: this.path._fileInfo && this.path._fileInfo.reference
  4320. }, true, true);
  4321. return this.features ? new Media([contents], this.features.value) : [contents];
  4322. } else if (this.css) {
  4323. var newImport = new Import(this.evalPath(context), features, this.options, this._index);
  4324. if (!newImport.css && this.error) {
  4325. throw this.error;
  4326. }
  4327. return newImport;
  4328. } else {
  4329. ruleset = new Ruleset(null, copyArray(this.root.rules));
  4330. ruleset.evalImports(context);
  4331. return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
  4332. }
  4333. }
  4334. }]);
  4335. return Import;
  4336. }(Node);
  4337. Import.prototype.type = 'Import';
  4338. var JsEvalNode =
  4339. /*#__PURE__*/
  4340. function (_Node) {
  4341. _inherits(JsEvalNode, _Node);
  4342. function JsEvalNode() {
  4343. _classCallCheck(this, JsEvalNode);
  4344. return _possibleConstructorReturn(this, _getPrototypeOf(JsEvalNode).apply(this, arguments));
  4345. }
  4346. _createClass(JsEvalNode, [{
  4347. key: "evaluateJavaScript",
  4348. value: function evaluateJavaScript(expression, context) {
  4349. var result;
  4350. var that = this;
  4351. var evalContext = {};
  4352. if (!context.javascriptEnabled) {
  4353. throw {
  4354. message: 'Inline JavaScript is not enabled. Is it set in your options?',
  4355. filename: this.fileInfo().filename,
  4356. index: this.getIndex()
  4357. };
  4358. }
  4359. expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
  4360. return that.jsify(new Variable(`@${name}`, that.getIndex(), that.fileInfo()).eval(context));
  4361. });
  4362. try {
  4363. expression = new Function(`return (${expression})`);
  4364. } catch (e) {
  4365. throw {
  4366. message: `JavaScript evaluation error: ${e.message} from \`${expression}\``,
  4367. filename: this.fileInfo().filename,
  4368. index: this.getIndex()
  4369. };
  4370. }
  4371. var variables = context.frames[0].variables();
  4372. for (var k in variables) {
  4373. if (variables.hasOwnProperty(k)) {
  4374. /* jshint loopfunc:true */
  4375. evalContext[k.slice(1)] = {
  4376. value: variables[k].value,
  4377. toJS: function toJS() {
  4378. return this.value.eval(context).toCSS();
  4379. }
  4380. };
  4381. }
  4382. }
  4383. try {
  4384. result = expression.call(evalContext);
  4385. } catch (e) {
  4386. throw {
  4387. message: `JavaScript evaluation error: '${e.name}: ${e.message.replace(/["]/g, '\'')}'`,
  4388. filename: this.fileInfo().filename,
  4389. index: this.getIndex()
  4390. };
  4391. }
  4392. return result;
  4393. }
  4394. }, {
  4395. key: "jsify",
  4396. value: function jsify(obj) {
  4397. if (Array.isArray(obj.value) && obj.value.length > 1) {
  4398. return `[${obj.value.map(function (v) {
  4399. return v.toCSS();
  4400. }).join(', ')}]`;
  4401. } else {
  4402. return obj.toCSS();
  4403. }
  4404. }
  4405. }]);
  4406. return JsEvalNode;
  4407. }(Node);
  4408. var JavaScript =
  4409. /*#__PURE__*/
  4410. function (_JsEvalNode) {
  4411. _inherits(JavaScript, _JsEvalNode);
  4412. function JavaScript(string, escaped, index, currentFileInfo) {
  4413. var _this;
  4414. _classCallCheck(this, JavaScript);
  4415. _this = _possibleConstructorReturn(this, _getPrototypeOf(JavaScript).call(this));
  4416. _this.escaped = escaped;
  4417. _this.expression = string;
  4418. _this._index = index;
  4419. _this._fileInfo = currentFileInfo;
  4420. return _this;
  4421. }
  4422. _createClass(JavaScript, [{
  4423. key: "eval",
  4424. value: function _eval(context) {
  4425. var result = this.evaluateJavaScript(this.expression, context);
  4426. var type = typeof result;
  4427. if (type === 'number' && !isNaN(result)) {
  4428. return new Dimension(result);
  4429. } else if (type === 'string') {
  4430. return new Quoted(`"${result}"`, result, this.escaped, this._index);
  4431. } else if (Array.isArray(result)) {
  4432. return new Anonymous(result.join(', '));
  4433. } else {
  4434. return new Anonymous(result);
  4435. }
  4436. }
  4437. }]);
  4438. return JavaScript;
  4439. }(JsEvalNode);
  4440. JavaScript.prototype.type = 'JavaScript';
  4441. var Assignment =
  4442. /*#__PURE__*/
  4443. function (_Node) {
  4444. _inherits(Assignment, _Node);
  4445. function Assignment(key, val) {
  4446. var _this;
  4447. _classCallCheck(this, Assignment);
  4448. _this = _possibleConstructorReturn(this, _getPrototypeOf(Assignment).call(this));
  4449. _this.key = key;
  4450. _this.value = val;
  4451. return _this;
  4452. }
  4453. _createClass(Assignment, [{
  4454. key: "accept",
  4455. value: function accept(visitor) {
  4456. this.value = visitor.visit(this.value);
  4457. }
  4458. }, {
  4459. key: "eval",
  4460. value: function _eval(context) {
  4461. if (this.value.eval) {
  4462. return new Assignment(this.key, this.value.eval(context));
  4463. }
  4464. return this;
  4465. }
  4466. }, {
  4467. key: "genCSS",
  4468. value: function genCSS(context, output) {
  4469. output.add(`${this.key}=`);
  4470. if (this.value.genCSS) {
  4471. this.value.genCSS(context, output);
  4472. } else {
  4473. output.add(this.value);
  4474. }
  4475. }
  4476. }]);
  4477. return Assignment;
  4478. }(Node);
  4479. Assignment.prototype.type = 'Assignment';
  4480. var Condition =
  4481. /*#__PURE__*/
  4482. function (_Node) {
  4483. _inherits(Condition, _Node);
  4484. function Condition(op, l, r, i, negate) {
  4485. var _this;
  4486. _classCallCheck(this, Condition);
  4487. _this = _possibleConstructorReturn(this, _getPrototypeOf(Condition).call(this));
  4488. _this.op = op.trim();
  4489. _this.lvalue = l;
  4490. _this.rvalue = r;
  4491. _this._index = i;
  4492. _this.negate = negate;
  4493. return _this;
  4494. }
  4495. _createClass(Condition, [{
  4496. key: "accept",
  4497. value: function accept(visitor) {
  4498. this.lvalue = visitor.visit(this.lvalue);
  4499. this.rvalue = visitor.visit(this.rvalue);
  4500. }
  4501. }, {
  4502. key: "eval",
  4503. value: function _eval(context) {
  4504. var result = function (op, a, b) {
  4505. switch (op) {
  4506. case 'and':
  4507. return a && b;
  4508. case 'or':
  4509. return a || b;
  4510. default:
  4511. switch (Node.compare(a, b)) {
  4512. case -1:
  4513. return op === '<' || op === '=<' || op === '<=';
  4514. case 0:
  4515. return op === '=' || op === '>=' || op === '=<' || op === '<=';
  4516. case 1:
  4517. return op === '>' || op === '>=';
  4518. default:
  4519. return false;
  4520. }
  4521. }
  4522. }(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
  4523. return this.negate ? !result : result;
  4524. }
  4525. }]);
  4526. return Condition;
  4527. }(Node);
  4528. Condition.prototype.type = 'Condition';
  4529. var UnicodeDescriptor =
  4530. /*#__PURE__*/
  4531. function (_Node) {
  4532. _inherits(UnicodeDescriptor, _Node);
  4533. function UnicodeDescriptor(value) {
  4534. var _this;
  4535. _classCallCheck(this, UnicodeDescriptor);
  4536. _this = _possibleConstructorReturn(this, _getPrototypeOf(UnicodeDescriptor).call(this));
  4537. _this.value = value;
  4538. return _this;
  4539. }
  4540. return UnicodeDescriptor;
  4541. }(Node);
  4542. UnicodeDescriptor.prototype.type = 'UnicodeDescriptor';
  4543. var Negative =
  4544. /*#__PURE__*/
  4545. function (_Node) {
  4546. _inherits(Negative, _Node);
  4547. function Negative(node) {
  4548. var _this;
  4549. _classCallCheck(this, Negative);
  4550. _this = _possibleConstructorReturn(this, _getPrototypeOf(Negative).call(this));
  4551. _this.value = node;
  4552. return _this;
  4553. }
  4554. _createClass(Negative, [{
  4555. key: "genCSS",
  4556. value: function genCSS(context, output) {
  4557. output.add('-');
  4558. this.value.genCSS(context, output);
  4559. }
  4560. }, {
  4561. key: "eval",
  4562. value: function _eval(context) {
  4563. if (context.isMathOn()) {
  4564. return new Operation('*', [new Dimension(-1), this.value]).eval(context);
  4565. }
  4566. return new Negative(this.value.eval(context));
  4567. }
  4568. }]);
  4569. return Negative;
  4570. }(Node);
  4571. Negative.prototype.type = 'Negative';
  4572. var Extend =
  4573. /*#__PURE__*/
  4574. function (_Node) {
  4575. _inherits(Extend, _Node);
  4576. function Extend(selector, option, index, currentFileInfo, visibilityInfo) {
  4577. var _this;
  4578. _classCallCheck(this, Extend);
  4579. _this = _possibleConstructorReturn(this, _getPrototypeOf(Extend).call(this));
  4580. _this.selector = selector;
  4581. _this.option = option;
  4582. _this.object_id = Extend.next_id++;
  4583. _this.parent_ids = [_this.object_id];
  4584. _this._index = index;
  4585. _this._fileInfo = currentFileInfo;
  4586. _this.copyVisibilityInfo(visibilityInfo);
  4587. _this.allowRoot = true;
  4588. switch (option) {
  4589. case 'all':
  4590. _this.allowBefore = true;
  4591. _this.allowAfter = true;
  4592. break;
  4593. default:
  4594. _this.allowBefore = false;
  4595. _this.allowAfter = false;
  4596. break;
  4597. }
  4598. _this.setParent(_this.selector, _assertThisInitialized(_this));
  4599. return _this;
  4600. }
  4601. _createClass(Extend, [{
  4602. key: "accept",
  4603. value: function accept(visitor) {
  4604. this.selector = visitor.visit(this.selector);
  4605. }
  4606. }, {
  4607. key: "eval",
  4608. value: function _eval(context) {
  4609. return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  4610. }
  4611. }, {
  4612. key: "clone",
  4613. value: function clone(context) {
  4614. return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  4615. } // it concatenates (joins) all selectors in selector array
  4616. }, {
  4617. key: "findSelfSelectors",
  4618. value: function findSelfSelectors(selectors) {
  4619. var selfElements = [];
  4620. var i;
  4621. var selectorElements;
  4622. for (i = 0; i < selectors.length; i++) {
  4623. selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node.
  4624. // future TODO - move both logics into the selector joiner visitor
  4625. if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
  4626. selectorElements[0].combinator.value = ' ';
  4627. }
  4628. selfElements = selfElements.concat(selectors[i].elements);
  4629. }
  4630. this.selfSelectors = [new Selector(selfElements)];
  4631. this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
  4632. }
  4633. }]);
  4634. return Extend;
  4635. }(Node);
  4636. Extend.next_id = 0;
  4637. Extend.prototype.type = 'Extend';
  4638. var VariableCall =
  4639. /*#__PURE__*/
  4640. function (_Node) {
  4641. _inherits(VariableCall, _Node);
  4642. function VariableCall(variable, index, currentFileInfo) {
  4643. var _this;
  4644. _classCallCheck(this, VariableCall);
  4645. _this = _possibleConstructorReturn(this, _getPrototypeOf(VariableCall).call(this));
  4646. _this.variable = variable;
  4647. _this._index = index;
  4648. _this._fileInfo = currentFileInfo;
  4649. _this.allowRoot = true;
  4650. return _this;
  4651. }
  4652. _createClass(VariableCall, [{
  4653. key: "eval",
  4654. value: function _eval(context) {
  4655. var rules;
  4656. var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
  4657. var error = new LessError({
  4658. message: `Could not evaluate variable call ${this.variable}`
  4659. });
  4660. if (!detachedRuleset.ruleset) {
  4661. if (detachedRuleset.rules) {
  4662. rules = detachedRuleset;
  4663. } else if (Array.isArray(detachedRuleset)) {
  4664. rules = new Ruleset('', detachedRuleset);
  4665. } else if (Array.isArray(detachedRuleset.value)) {
  4666. rules = new Ruleset('', detachedRuleset.value);
  4667. } else {
  4668. throw error;
  4669. }
  4670. detachedRuleset = new DetachedRuleset(rules);
  4671. }
  4672. if (detachedRuleset.ruleset) {
  4673. return detachedRuleset.callEval(context);
  4674. }
  4675. throw error;
  4676. }
  4677. }]);
  4678. return VariableCall;
  4679. }(Node);
  4680. VariableCall.prototype.type = 'VariableCall';
  4681. var NamespaceValue =
  4682. /*#__PURE__*/
  4683. function (_Node) {
  4684. _inherits(NamespaceValue, _Node);
  4685. function NamespaceValue(ruleCall, lookups, important, index, fileInfo) {
  4686. var _this;
  4687. _classCallCheck(this, NamespaceValue);
  4688. _this = _possibleConstructorReturn(this, _getPrototypeOf(NamespaceValue).call(this));
  4689. _this.value = ruleCall;
  4690. _this.lookups = lookups;
  4691. _this.important = important;
  4692. _this._index = index;
  4693. _this._fileInfo = fileInfo;
  4694. return _this;
  4695. }
  4696. _createClass(NamespaceValue, [{
  4697. key: "eval",
  4698. value: function _eval(context) {
  4699. var i;
  4700. var name;
  4701. var rules = this.value.eval(context);
  4702. for (i = 0; i < this.lookups.length; i++) {
  4703. name = this.lookups[i];
  4704. /**
  4705. * Eval'd DRs return rulesets.
  4706. * Eval'd mixins return rules, so let's make a ruleset if we need it.
  4707. * We need to do this because of late parsing of values
  4708. */
  4709. if (Array.isArray(rules)) {
  4710. rules = new Ruleset([new Selector()], rules);
  4711. }
  4712. if (name === '') {
  4713. rules = rules.lastDeclaration();
  4714. } else if (name.charAt(0) === '@') {
  4715. if (name.charAt(1) === '@') {
  4716. name = `@${new Variable(name.substr(1)).eval(context).value}`;
  4717. }
  4718. if (rules.variables) {
  4719. rules = rules.variable(name);
  4720. }
  4721. if (!rules) {
  4722. throw {
  4723. type: 'Name',
  4724. message: `variable ${name} not found`,
  4725. filename: this.fileInfo().filename,
  4726. index: this.getIndex()
  4727. };
  4728. }
  4729. } else {
  4730. if (name.substring(0, 2) === '$@') {
  4731. name = `$${new Variable(name.substr(1)).eval(context).value}`;
  4732. } else {
  4733. name = name.charAt(0) === '$' ? name : `$${name}`;
  4734. }
  4735. if (rules.properties) {
  4736. rules = rules.property(name);
  4737. }
  4738. if (!rules) {
  4739. throw {
  4740. type: 'Name',
  4741. message: `property "${name.substr(1)}" not found`,
  4742. filename: this.fileInfo().filename,
  4743. index: this.getIndex()
  4744. };
  4745. } // Properties are an array of values, since a ruleset can have multiple props.
  4746. // We pick the last one (the "cascaded" value)
  4747. rules = rules[rules.length - 1];
  4748. }
  4749. if (rules.value) {
  4750. rules = rules.eval(context).value;
  4751. }
  4752. if (rules.ruleset) {
  4753. rules = rules.ruleset.eval(context);
  4754. }
  4755. }
  4756. return rules;
  4757. }
  4758. }]);
  4759. return NamespaceValue;
  4760. }(Node);
  4761. NamespaceValue.prototype.type = 'NamespaceValue';
  4762. var Definition =
  4763. /*#__PURE__*/
  4764. function (_Ruleset) {
  4765. _inherits(Definition, _Ruleset);
  4766. function Definition(name, params, rules, condition, variadic, frames, visibilityInfo) {
  4767. var _this;
  4768. _classCallCheck(this, Definition);
  4769. _this = _possibleConstructorReturn(this, _getPrototypeOf(Definition).call(this));
  4770. _this.name = name || 'anonymous mixin';
  4771. _this.selectors = [new Selector([new Element(null, name, false, _this._index, _this._fileInfo)])];
  4772. _this.params = params;
  4773. _this.condition = condition;
  4774. _this.variadic = variadic;
  4775. _this.arity = params.length;
  4776. _this.rules = rules;
  4777. _this._lookups = {};
  4778. var optionalParameters = [];
  4779. _this.required = params.reduce(function (count, p) {
  4780. if (!p.name || p.name && !p.value) {
  4781. return count + 1;
  4782. } else {
  4783. optionalParameters.push(p.name);
  4784. return count;
  4785. }
  4786. }, 0);
  4787. _this.optionalParameters = optionalParameters;
  4788. _this.frames = frames;
  4789. _this.copyVisibilityInfo(visibilityInfo);
  4790. _this.allowRoot = true;
  4791. return _this;
  4792. }
  4793. _createClass(Definition, [{
  4794. key: "accept",
  4795. value: function accept(visitor) {
  4796. if (this.params && this.params.length) {
  4797. this.params = visitor.visitArray(this.params);
  4798. }
  4799. this.rules = visitor.visitArray(this.rules);
  4800. if (this.condition) {
  4801. this.condition = visitor.visit(this.condition);
  4802. }
  4803. }
  4804. }, {
  4805. key: "evalParams",
  4806. value: function evalParams(context, mixinEnv, args, evaldArguments) {
  4807. /* jshint boss:true */
  4808. var frame = new Ruleset(null, null);
  4809. var varargs;
  4810. var arg;
  4811. var params = copyArray(this.params);
  4812. var i;
  4813. var j;
  4814. var val;
  4815. var name;
  4816. var isNamedFound;
  4817. var argIndex;
  4818. var argsLength = 0;
  4819. if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
  4820. frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
  4821. }
  4822. mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
  4823. if (args) {
  4824. args = copyArray(args);
  4825. argsLength = args.length;
  4826. for (i = 0; i < argsLength; i++) {
  4827. arg = args[i];
  4828. if (name = arg && arg.name) {
  4829. isNamedFound = false;
  4830. for (j = 0; j < params.length; j++) {
  4831. if (!evaldArguments[j] && name === params[j].name) {
  4832. evaldArguments[j] = arg.value.eval(context);
  4833. frame.prependRule(new Declaration(name, arg.value.eval(context)));
  4834. isNamedFound = true;
  4835. break;
  4836. }
  4837. }
  4838. if (isNamedFound) {
  4839. args.splice(i, 1);
  4840. i--;
  4841. continue;
  4842. } else {
  4843. throw {
  4844. type: 'Runtime',
  4845. message: `Named argument for ${this.name} ${args[i].name} not found`
  4846. };
  4847. }
  4848. }
  4849. }
  4850. }
  4851. argIndex = 0;
  4852. for (i = 0; i < params.length; i++) {
  4853. if (evaldArguments[i]) {
  4854. continue;
  4855. }
  4856. arg = args && args[argIndex];
  4857. if (name = params[i].name) {
  4858. if (params[i].variadic) {
  4859. varargs = [];
  4860. for (j = argIndex; j < argsLength; j++) {
  4861. varargs.push(args[j].value.eval(context));
  4862. }
  4863. frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
  4864. } else {
  4865. val = arg && arg.value;
  4866. if (val) {
  4867. // This was a mixin call, pass in a detached ruleset of it's eval'd rules
  4868. if (Array.isArray(val)) {
  4869. val = new DetachedRuleset(new Ruleset('', val));
  4870. } else {
  4871. val = val.eval(context);
  4872. }
  4873. } else if (params[i].value) {
  4874. val = params[i].value.eval(mixinEnv);
  4875. frame.resetCache();
  4876. } else {
  4877. throw {
  4878. type: 'Runtime',
  4879. message: `wrong number of arguments for ${this.name} (${argsLength} for ${this.arity})`
  4880. };
  4881. }
  4882. frame.prependRule(new Declaration(name, val));
  4883. evaldArguments[i] = val;
  4884. }
  4885. }
  4886. if (params[i].variadic && args) {
  4887. for (j = argIndex; j < argsLength; j++) {
  4888. evaldArguments[j] = args[j].value.eval(context);
  4889. }
  4890. }
  4891. argIndex++;
  4892. }
  4893. return frame;
  4894. }
  4895. }, {
  4896. key: "makeImportant",
  4897. value: function makeImportant() {
  4898. var rules = !this.rules ? this.rules : this.rules.map(function (r) {
  4899. if (r.makeImportant) {
  4900. return r.makeImportant(true);
  4901. } else {
  4902. return r;
  4903. }
  4904. });
  4905. var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
  4906. return result;
  4907. }
  4908. }, {
  4909. key: "eval",
  4910. value: function _eval(context) {
  4911. return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
  4912. }
  4913. }, {
  4914. key: "evalCall",
  4915. value: function evalCall(context, args, important) {
  4916. var _arguments = [];
  4917. var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
  4918. var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
  4919. var rules;
  4920. var ruleset;
  4921. frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
  4922. rules = copyArray(this.rules);
  4923. ruleset = new Ruleset(null, rules);
  4924. ruleset.originalRuleset = this;
  4925. ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
  4926. if (important) {
  4927. ruleset = ruleset.makeImportant();
  4928. }
  4929. return ruleset;
  4930. }
  4931. }, {
  4932. key: "matchCondition",
  4933. value: function matchCondition(args, context) {
  4934. if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context,
  4935. /* the parameter variables */
  4936. new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])].concat(this.frames || []) // the parent namespace/mixin frames
  4937. .concat(context.frames)))) {
  4938. // the current environment frames
  4939. return false;
  4940. }
  4941. return true;
  4942. }
  4943. }, {
  4944. key: "matchArgs",
  4945. value: function matchArgs(args, context) {
  4946. var allArgsCnt = args && args.length || 0;
  4947. var len;
  4948. var optionalParameters = this.optionalParameters;
  4949. var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
  4950. if (optionalParameters.indexOf(p.name) < 0) {
  4951. return count + 1;
  4952. } else {
  4953. return count;
  4954. }
  4955. }, 0);
  4956. if (!this.variadic) {
  4957. if (requiredArgsCnt < this.required) {
  4958. return false;
  4959. }
  4960. if (allArgsCnt > this.params.length) {
  4961. return false;
  4962. }
  4963. } else {
  4964. if (requiredArgsCnt < this.required - 1) {
  4965. return false;
  4966. }
  4967. } // check patterns
  4968. len = Math.min(requiredArgsCnt, this.arity);
  4969. for (var i = 0; i < len; i++) {
  4970. if (!this.params[i].name && !this.params[i].variadic) {
  4971. if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
  4972. return false;
  4973. }
  4974. }
  4975. }
  4976. return true;
  4977. }
  4978. }]);
  4979. return Definition;
  4980. }(Ruleset);
  4981. Definition.prototype.type = 'MixinDefinition';
  4982. Definition.prototype.evalFirst = true;
  4983. var MixinCall =
  4984. /*#__PURE__*/
  4985. function (_Node) {
  4986. _inherits(MixinCall, _Node);
  4987. function MixinCall(elements, args, index, currentFileInfo, important) {
  4988. var _this;
  4989. _classCallCheck(this, MixinCall);
  4990. _this = _possibleConstructorReturn(this, _getPrototypeOf(MixinCall).call(this));
  4991. _this.selector = new Selector(elements);
  4992. _this.arguments = args || [];
  4993. _this._index = index;
  4994. _this._fileInfo = currentFileInfo;
  4995. _this.important = important;
  4996. _this.allowRoot = true;
  4997. _this.setParent(_this.selector, _assertThisInitialized(_this));
  4998. return _this;
  4999. }
  5000. _createClass(MixinCall, [{
  5001. key: "accept",
  5002. value: function accept(visitor) {
  5003. if (this.selector) {
  5004. this.selector = visitor.visit(this.selector);
  5005. }
  5006. if (this.arguments.length) {
  5007. this.arguments = visitor.visitArray(this.arguments);
  5008. }
  5009. }
  5010. }, {
  5011. key: "eval",
  5012. value: function _eval(context) {
  5013. var mixins;
  5014. var mixin;
  5015. var mixinPath;
  5016. var args = [];
  5017. var arg;
  5018. var argValue;
  5019. var rules = [];
  5020. var match = false;
  5021. var i;
  5022. var m;
  5023. var f;
  5024. var isRecursive;
  5025. var isOneFound;
  5026. var candidates = [];
  5027. var candidate;
  5028. var conditionResult = [];
  5029. var defaultResult;
  5030. var defFalseEitherCase = -1;
  5031. var defNone = 0;
  5032. var defTrue = 1;
  5033. var defFalse = 2;
  5034. var count;
  5035. var originalRuleset;
  5036. var noArgumentsFilter;
  5037. this.selector = this.selector.eval(context);
  5038. function calcDefGroup(mixin, mixinPath) {
  5039. var f;
  5040. var p;
  5041. var namespace;
  5042. for (f = 0; f < 2; f++) {
  5043. conditionResult[f] = true;
  5044. defaultFunc.value(f);
  5045. for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
  5046. namespace = mixinPath[p];
  5047. if (namespace.matchCondition) {
  5048. conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
  5049. }
  5050. }
  5051. if (mixin.matchCondition) {
  5052. conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
  5053. }
  5054. }
  5055. if (conditionResult[0] || conditionResult[1]) {
  5056. if (conditionResult[0] != conditionResult[1]) {
  5057. return conditionResult[1] ? defTrue : defFalse;
  5058. }
  5059. return defNone;
  5060. }
  5061. return defFalseEitherCase;
  5062. }
  5063. for (i = 0; i < this.arguments.length; i++) {
  5064. arg = this.arguments[i];
  5065. argValue = arg.value.eval(context);
  5066. if (arg.expand && Array.isArray(argValue.value)) {
  5067. argValue = argValue.value;
  5068. for (m = 0; m < argValue.length; m++) {
  5069. args.push({
  5070. value: argValue[m]
  5071. });
  5072. }
  5073. } else {
  5074. args.push({
  5075. name: arg.name,
  5076. value: argValue
  5077. });
  5078. }
  5079. }
  5080. noArgumentsFilter = function noArgumentsFilter(rule) {
  5081. return rule.matchArgs(null, context);
  5082. };
  5083. for (i = 0; i < context.frames.length; i++) {
  5084. if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
  5085. isOneFound = true; // To make `default()` function independent of definition order we have two "subpasses" here.
  5086. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
  5087. // and build candidate list with corresponding flags. Then, when we know all possible matches,
  5088. // we make a final decision.
  5089. for (m = 0; m < mixins.length; m++) {
  5090. mixin = mixins[m].rule;
  5091. mixinPath = mixins[m].path;
  5092. isRecursive = false;
  5093. for (f = 0; f < context.frames.length; f++) {
  5094. if (!(mixin instanceof Definition) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
  5095. isRecursive = true;
  5096. break;
  5097. }
  5098. }
  5099. if (isRecursive) {
  5100. continue;
  5101. }
  5102. if (mixin.matchArgs(args, context)) {
  5103. candidate = {
  5104. mixin,
  5105. group: calcDefGroup(mixin, mixinPath)
  5106. };
  5107. if (candidate.group !== defFalseEitherCase) {
  5108. candidates.push(candidate);
  5109. }
  5110. match = true;
  5111. }
  5112. }
  5113. defaultFunc.reset();
  5114. count = [0, 0, 0];
  5115. for (m = 0; m < candidates.length; m++) {
  5116. count[candidates[m].group]++;
  5117. }
  5118. if (count[defNone] > 0) {
  5119. defaultResult = defFalse;
  5120. } else {
  5121. defaultResult = defTrue;
  5122. if (count[defTrue] + count[defFalse] > 1) {
  5123. throw {
  5124. type: 'Runtime',
  5125. message: `Ambiguous use of \`default()\` found when matching for \`${this.format(args)}\``,
  5126. index: this.getIndex(),
  5127. filename: this.fileInfo().filename
  5128. };
  5129. }
  5130. }
  5131. for (m = 0; m < candidates.length; m++) {
  5132. candidate = candidates[m].group;
  5133. if (candidate === defNone || candidate === defaultResult) {
  5134. try {
  5135. mixin = candidates[m].mixin;
  5136. if (!(mixin instanceof Definition)) {
  5137. originalRuleset = mixin.originalRuleset || mixin;
  5138. mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
  5139. mixin.originalRuleset = originalRuleset;
  5140. }
  5141. var newRules = mixin.evalCall(context, args, this.important).rules;
  5142. this._setVisibilityToReplacement(newRules);
  5143. Array.prototype.push.apply(rules, newRules);
  5144. } catch (e) {
  5145. throw {
  5146. message: e.message,
  5147. index: this.getIndex(),
  5148. filename: this.fileInfo().filename,
  5149. stack: e.stack
  5150. };
  5151. }
  5152. }
  5153. }
  5154. if (match) {
  5155. return rules;
  5156. }
  5157. }
  5158. }
  5159. if (isOneFound) {
  5160. throw {
  5161. type: 'Runtime',
  5162. message: `No matching definition was found for \`${this.format(args)}\``,
  5163. index: this.getIndex(),
  5164. filename: this.fileInfo().filename
  5165. };
  5166. } else {
  5167. throw {
  5168. type: 'Name',
  5169. message: `${this.selector.toCSS().trim()} is undefined`,
  5170. index: this.getIndex(),
  5171. filename: this.fileInfo().filename
  5172. };
  5173. }
  5174. }
  5175. }, {
  5176. key: "_setVisibilityToReplacement",
  5177. value: function _setVisibilityToReplacement(replacement) {
  5178. var i;
  5179. var rule;
  5180. if (this.blocksVisibility()) {
  5181. for (i = 0; i < replacement.length; i++) {
  5182. rule = replacement[i];
  5183. rule.addVisibilityBlock();
  5184. }
  5185. }
  5186. }
  5187. }, {
  5188. key: "format",
  5189. value: function format(args) {
  5190. return `${this.selector.toCSS().trim()}(${args ? args.map(function (a) {
  5191. var argValue = '';
  5192. if (a.name) {
  5193. argValue += `${a.name}:`;
  5194. }
  5195. if (a.value.toCSS) {
  5196. argValue += a.value.toCSS();
  5197. } else {
  5198. argValue += '???';
  5199. }
  5200. return argValue;
  5201. }).join(', ') : ''})`;
  5202. }
  5203. }]);
  5204. return MixinCall;
  5205. }(Node);
  5206. MixinCall.prototype.type = 'MixinCall';
  5207. var tree = {
  5208. Node,
  5209. Color,
  5210. AtRule,
  5211. DetachedRuleset,
  5212. Operation,
  5213. Dimension,
  5214. Unit,
  5215. Keyword,
  5216. Variable,
  5217. Property,
  5218. Ruleset,
  5219. Element,
  5220. Attribute,
  5221. Combinator,
  5222. Selector,
  5223. Quoted,
  5224. Expression,
  5225. Declaration,
  5226. Call,
  5227. URL,
  5228. Import,
  5229. Comment,
  5230. Anonymous,
  5231. Value,
  5232. JavaScript,
  5233. Assignment,
  5234. Condition,
  5235. Paren,
  5236. Media,
  5237. UnicodeDescriptor,
  5238. Negative,
  5239. Extend,
  5240. VariableCall,
  5241. NamespaceValue,
  5242. mixin: {
  5243. Call: MixinCall,
  5244. Definition: Definition
  5245. }
  5246. };
  5247. var environment$1 =
  5248. /*#__PURE__*/
  5249. function () {
  5250. function environment(externalEnvironment, fileManagers) {
  5251. _classCallCheck(this, environment);
  5252. this.fileManagers = fileManagers || [];
  5253. externalEnvironment = externalEnvironment || {};
  5254. var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
  5255. var requiredFunctions = [];
  5256. var functions = requiredFunctions.concat(optionalFunctions);
  5257. for (var i = 0; i < functions.length; i++) {
  5258. var propName = functions[i];
  5259. var environmentFunc = externalEnvironment[propName];
  5260. if (environmentFunc) {
  5261. this[propName] = environmentFunc.bind(externalEnvironment);
  5262. } else if (i < requiredFunctions.length) {
  5263. this.warn(`missing required function in environment - ${propName}`);
  5264. }
  5265. }
  5266. }
  5267. _createClass(environment, [{
  5268. key: "getFileManager",
  5269. value: function getFileManager(filename, currentDirectory, options, environment, isSync) {
  5270. if (!filename) {
  5271. logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
  5272. }
  5273. if (currentDirectory == null) {
  5274. logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
  5275. }
  5276. var fileManagers = this.fileManagers;
  5277. if (options.pluginManager) {
  5278. fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
  5279. }
  5280. for (var i = fileManagers.length - 1; i >= 0; i--) {
  5281. var fileManager = fileManagers[i];
  5282. if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
  5283. return fileManager;
  5284. }
  5285. }
  5286. return null;
  5287. }
  5288. }, {
  5289. key: "addFileManager",
  5290. value: function addFileManager(fileManager) {
  5291. this.fileManagers.push(fileManager);
  5292. }
  5293. }, {
  5294. key: "clearFileManagers",
  5295. value: function clearFileManagers() {
  5296. this.fileManagers = [];
  5297. }
  5298. }]);
  5299. return environment;
  5300. }();
  5301. var AbstractPluginLoader =
  5302. /*#__PURE__*/
  5303. function () {
  5304. function AbstractPluginLoader() {
  5305. _classCallCheck(this, AbstractPluginLoader);
  5306. // Implemented by Node.js plugin loader
  5307. this.require = function () {
  5308. return null;
  5309. };
  5310. }
  5311. _createClass(AbstractPluginLoader, [{
  5312. key: "evalPlugin",
  5313. value: function evalPlugin(contents, context, imports, pluginOptions, fileInfo) {
  5314. var loader;
  5315. var registry;
  5316. var pluginObj;
  5317. var localModule;
  5318. var pluginManager;
  5319. var filename;
  5320. var result;
  5321. pluginManager = context.pluginManager;
  5322. if (fileInfo) {
  5323. if (typeof fileInfo === 'string') {
  5324. filename = fileInfo;
  5325. } else {
  5326. filename = fileInfo.filename;
  5327. }
  5328. }
  5329. var shortname = new this.less.FileManager().extractUrlParts(filename).filename;
  5330. if (filename) {
  5331. pluginObj = pluginManager.get(filename);
  5332. if (pluginObj) {
  5333. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  5334. if (result) {
  5335. return result;
  5336. }
  5337. try {
  5338. if (pluginObj.use) {
  5339. pluginObj.use.call(this.context, pluginObj);
  5340. }
  5341. } catch (e) {
  5342. e.message = e.message || 'Error during @plugin call';
  5343. return new LessError(e, imports, filename);
  5344. }
  5345. return pluginObj;
  5346. }
  5347. }
  5348. localModule = {
  5349. exports: {},
  5350. pluginManager,
  5351. fileInfo
  5352. };
  5353. registry = functionRegistry.create();
  5354. var registerPlugin = function registerPlugin(obj) {
  5355. pluginObj = obj;
  5356. };
  5357. try {
  5358. loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
  5359. loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
  5360. } catch (e) {
  5361. return new LessError(e, imports, filename);
  5362. }
  5363. if (!pluginObj) {
  5364. pluginObj = localModule.exports;
  5365. }
  5366. pluginObj = this.validatePlugin(pluginObj, filename, shortname);
  5367. if (pluginObj instanceof LessError) {
  5368. return pluginObj;
  5369. }
  5370. if (pluginObj) {
  5371. pluginObj.imports = imports;
  5372. pluginObj.filename = filename; // For < 3.x (or unspecified minVersion) - setOptions() before install()
  5373. if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
  5374. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  5375. if (result) {
  5376. return result;
  5377. }
  5378. } // Run on first load
  5379. pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
  5380. pluginObj.functions = registry.getLocalFunctions(); // Need to call setOptions again because the pluginObj might have functions
  5381. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  5382. if (result) {
  5383. return result;
  5384. } // Run every @plugin call
  5385. try {
  5386. if (pluginObj.use) {
  5387. pluginObj.use.call(this.context, pluginObj);
  5388. }
  5389. } catch (e) {
  5390. e.message = e.message || 'Error during @plugin call';
  5391. return new LessError(e, imports, filename);
  5392. }
  5393. } else {
  5394. return new LessError({
  5395. message: 'Not a valid plugin'
  5396. }, imports, filename);
  5397. }
  5398. return pluginObj;
  5399. }
  5400. }, {
  5401. key: "trySetOptions",
  5402. value: function trySetOptions(plugin, filename, name, options) {
  5403. if (options && !plugin.setOptions) {
  5404. return new LessError({
  5405. message: `Options have been provided but the plugin ${name} does not support any options.`
  5406. });
  5407. }
  5408. try {
  5409. plugin.setOptions && plugin.setOptions(options);
  5410. } catch (e) {
  5411. return new LessError(e);
  5412. }
  5413. }
  5414. }, {
  5415. key: "validatePlugin",
  5416. value: function validatePlugin(plugin, filename, name) {
  5417. if (plugin) {
  5418. // support plugins being a function
  5419. // so that the plugin can be more usable programmatically
  5420. if (typeof plugin === 'function') {
  5421. plugin = new plugin();
  5422. }
  5423. if (plugin.minVersion) {
  5424. if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
  5425. return new LessError({
  5426. message: `Plugin ${name} requires version ${this.versionToString(plugin.minVersion)}`
  5427. });
  5428. }
  5429. }
  5430. return plugin;
  5431. }
  5432. return null;
  5433. }
  5434. }, {
  5435. key: "compareVersion",
  5436. value: function compareVersion(aVersion, bVersion) {
  5437. if (typeof aVersion === 'string') {
  5438. aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
  5439. aVersion.shift();
  5440. }
  5441. for (var i = 0; i < aVersion.length; i++) {
  5442. if (aVersion[i] !== bVersion[i]) {
  5443. return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
  5444. }
  5445. }
  5446. return 0;
  5447. }
  5448. }, {
  5449. key: "versionToString",
  5450. value: function versionToString(version) {
  5451. var versionString = '';
  5452. for (var i = 0; i < version.length; i++) {
  5453. versionString += (versionString ? '.' : '') + version[i];
  5454. }
  5455. return versionString;
  5456. }
  5457. }, {
  5458. key: "printUsage",
  5459. value: function printUsage(plugins) {
  5460. for (var i = 0; i < plugins.length; i++) {
  5461. var plugin = plugins[i];
  5462. if (plugin.printUsage) {
  5463. plugin.printUsage();
  5464. }
  5465. }
  5466. }
  5467. }]);
  5468. return AbstractPluginLoader;
  5469. }();
  5470. var _visitArgs = {
  5471. visitDeeper: true
  5472. };
  5473. var _hasIndexed = false;
  5474. function _noop(node) {
  5475. return node;
  5476. }
  5477. function indexNodeTypes(parent, ticker) {
  5478. // add .typeIndex to tree node types for lookup table
  5479. var key;
  5480. var child;
  5481. for (key in parent) {
  5482. /* eslint guard-for-in: 0 */
  5483. child = parent[key];
  5484. switch (typeof child) {
  5485. case 'function':
  5486. // ignore bound functions directly on tree which do not have a prototype
  5487. // or aren't nodes
  5488. if (child.prototype && child.prototype.type) {
  5489. child.prototype.typeIndex = ticker++;
  5490. }
  5491. break;
  5492. case 'object':
  5493. ticker = indexNodeTypes(child, ticker);
  5494. break;
  5495. }
  5496. }
  5497. return ticker;
  5498. }
  5499. var Visitor =
  5500. /*#__PURE__*/
  5501. function () {
  5502. function Visitor(implementation) {
  5503. _classCallCheck(this, Visitor);
  5504. this._implementation = implementation;
  5505. this._visitInCache = {};
  5506. this._visitOutCache = {};
  5507. if (!_hasIndexed) {
  5508. indexNodeTypes(tree, 1);
  5509. _hasIndexed = true;
  5510. }
  5511. }
  5512. _createClass(Visitor, [{
  5513. key: "visit",
  5514. value: function visit(node) {
  5515. if (!node) {
  5516. return node;
  5517. }
  5518. var nodeTypeIndex = node.typeIndex;
  5519. if (!nodeTypeIndex) {
  5520. // MixinCall args aren't a node type?
  5521. if (node.value && node.value.typeIndex) {
  5522. this.visit(node.value);
  5523. }
  5524. return node;
  5525. }
  5526. var impl = this._implementation;
  5527. var func = this._visitInCache[nodeTypeIndex];
  5528. var funcOut = this._visitOutCache[nodeTypeIndex];
  5529. var visitArgs = _visitArgs;
  5530. var fnName;
  5531. visitArgs.visitDeeper = true;
  5532. if (!func) {
  5533. fnName = `visit${node.type}`;
  5534. func = impl[fnName] || _noop;
  5535. funcOut = impl[`${fnName}Out`] || _noop;
  5536. this._visitInCache[nodeTypeIndex] = func;
  5537. this._visitOutCache[nodeTypeIndex] = funcOut;
  5538. }
  5539. if (func !== _noop) {
  5540. var newNode = func.call(impl, node, visitArgs);
  5541. if (node && impl.isReplacing) {
  5542. node = newNode;
  5543. }
  5544. }
  5545. if (visitArgs.visitDeeper && node && node.accept) {
  5546. node.accept(this);
  5547. }
  5548. if (funcOut != _noop) {
  5549. funcOut.call(impl, node);
  5550. }
  5551. return node;
  5552. }
  5553. }, {
  5554. key: "visitArray",
  5555. value: function visitArray(nodes, nonReplacing) {
  5556. if (!nodes) {
  5557. return nodes;
  5558. }
  5559. var cnt = nodes.length;
  5560. var i; // Non-replacing
  5561. if (nonReplacing || !this._implementation.isReplacing) {
  5562. for (i = 0; i < cnt; i++) {
  5563. this.visit(nodes[i]);
  5564. }
  5565. return nodes;
  5566. } // Replacing
  5567. var out = [];
  5568. for (i = 0; i < cnt; i++) {
  5569. var evald = this.visit(nodes[i]);
  5570. if (evald === undefined) {
  5571. continue;
  5572. }
  5573. if (!evald.splice) {
  5574. out.push(evald);
  5575. } else if (evald.length) {
  5576. this.flatten(evald, out);
  5577. }
  5578. }
  5579. return out;
  5580. }
  5581. }, {
  5582. key: "flatten",
  5583. value: function flatten(arr, out) {
  5584. if (!out) {
  5585. out = [];
  5586. }
  5587. var cnt;
  5588. var i;
  5589. var item;
  5590. var nestedCnt;
  5591. var j;
  5592. var nestedItem;
  5593. for (i = 0, cnt = arr.length; i < cnt; i++) {
  5594. item = arr[i];
  5595. if (item === undefined) {
  5596. continue;
  5597. }
  5598. if (!item.splice) {
  5599. out.push(item);
  5600. continue;
  5601. }
  5602. for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
  5603. nestedItem = item[j];
  5604. if (nestedItem === undefined) {
  5605. continue;
  5606. }
  5607. if (!nestedItem.splice) {
  5608. out.push(nestedItem);
  5609. } else if (nestedItem.length) {
  5610. this.flatten(nestedItem, out);
  5611. }
  5612. }
  5613. }
  5614. return out;
  5615. }
  5616. }]);
  5617. return Visitor;
  5618. }();
  5619. var ImportSequencer =
  5620. /*#__PURE__*/
  5621. function () {
  5622. function ImportSequencer(onSequencerEmpty) {
  5623. _classCallCheck(this, ImportSequencer);
  5624. this.imports = [];
  5625. this.variableImports = [];
  5626. this._onSequencerEmpty = onSequencerEmpty;
  5627. this._currentDepth = 0;
  5628. }
  5629. _createClass(ImportSequencer, [{
  5630. key: "addImport",
  5631. value: function addImport(callback) {
  5632. var importSequencer = this;
  5633. var importItem = {
  5634. callback,
  5635. args: null,
  5636. isReady: false
  5637. };
  5638. this.imports.push(importItem);
  5639. return function () {
  5640. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  5641. args[_key] = arguments[_key];
  5642. }
  5643. importItem.args = Array.prototype.slice.call(args, 0);
  5644. importItem.isReady = true;
  5645. importSequencer.tryRun();
  5646. };
  5647. }
  5648. }, {
  5649. key: "addVariableImport",
  5650. value: function addVariableImport(callback) {
  5651. this.variableImports.push(callback);
  5652. }
  5653. }, {
  5654. key: "tryRun",
  5655. value: function tryRun() {
  5656. this._currentDepth++;
  5657. try {
  5658. while (true) {
  5659. while (this.imports.length > 0) {
  5660. var importItem = this.imports[0];
  5661. if (!importItem.isReady) {
  5662. return;
  5663. }
  5664. this.imports = this.imports.slice(1);
  5665. importItem.callback.apply(null, importItem.args);
  5666. }
  5667. if (this.variableImports.length === 0) {
  5668. break;
  5669. }
  5670. var variableImport = this.variableImports[0];
  5671. this.variableImports = this.variableImports.slice(1);
  5672. variableImport();
  5673. }
  5674. } finally {
  5675. this._currentDepth--;
  5676. }
  5677. if (this._currentDepth === 0 && this._onSequencerEmpty) {
  5678. this._onSequencerEmpty();
  5679. }
  5680. }
  5681. }]);
  5682. return ImportSequencer;
  5683. }();
  5684. var ImportVisitor = function ImportVisitor(importer, finish) {
  5685. this._visitor = new Visitor(this);
  5686. this._importer = importer;
  5687. this._finish = finish;
  5688. this.context = new contexts.Eval();
  5689. this.importCount = 0;
  5690. this.onceFileDetectionMap = {};
  5691. this.recursionDetector = {};
  5692. this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
  5693. };
  5694. ImportVisitor.prototype = {
  5695. isReplacing: false,
  5696. run: function run(root) {
  5697. try {
  5698. // process the contents
  5699. this._visitor.visit(root);
  5700. } catch (e) {
  5701. this.error = e;
  5702. }
  5703. this.isFinished = true;
  5704. this._sequencer.tryRun();
  5705. },
  5706. _onSequencerEmpty: function _onSequencerEmpty() {
  5707. if (!this.isFinished) {
  5708. return;
  5709. }
  5710. this._finish(this.error);
  5711. },
  5712. visitImport: function visitImport(importNode, visitArgs) {
  5713. var inlineCSS = importNode.options.inline;
  5714. if (!importNode.css || inlineCSS) {
  5715. var context = new contexts.Eval(this.context, copyArray(this.context.frames));
  5716. var importParent = context.frames[0];
  5717. this.importCount++;
  5718. if (importNode.isVariableImport()) {
  5719. this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
  5720. } else {
  5721. this.processImportNode(importNode, context, importParent);
  5722. }
  5723. }
  5724. visitArgs.visitDeeper = false;
  5725. },
  5726. processImportNode: function processImportNode(importNode, context, importParent) {
  5727. var evaldImportNode;
  5728. var inlineCSS = importNode.options.inline;
  5729. try {
  5730. evaldImportNode = importNode.evalForImport(context);
  5731. } catch (e) {
  5732. if (!e.filename) {
  5733. e.index = importNode.getIndex();
  5734. e.filename = importNode.fileInfo().filename;
  5735. } // attempt to eval properly and treat as css
  5736. importNode.css = true; // if that fails, this error will be thrown
  5737. importNode.error = e;
  5738. }
  5739. if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
  5740. if (evaldImportNode.options.multiple) {
  5741. context.importMultiple = true;
  5742. } // try appending if we haven't determined if it is css or not
  5743. var tryAppendLessExtension = evaldImportNode.css === undefined;
  5744. for (var i = 0; i < importParent.rules.length; i++) {
  5745. if (importParent.rules[i] === importNode) {
  5746. importParent.rules[i] = evaldImportNode;
  5747. break;
  5748. }
  5749. }
  5750. var onImported = this.onImported.bind(this, evaldImportNode, context);
  5751. var sequencedOnImported = this._sequencer.addImport(onImported);
  5752. this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
  5753. } else {
  5754. this.importCount--;
  5755. if (this.isFinished) {
  5756. this._sequencer.tryRun();
  5757. }
  5758. }
  5759. },
  5760. onImported: function onImported(importNode, context, e, root, importedAtRoot, fullPath) {
  5761. if (e) {
  5762. if (!e.filename) {
  5763. e.index = importNode.getIndex();
  5764. e.filename = importNode.fileInfo().filename;
  5765. }
  5766. this.error = e;
  5767. }
  5768. var importVisitor = this;
  5769. var inlineCSS = importNode.options.inline;
  5770. var isPlugin = importNode.options.isPlugin;
  5771. var isOptional = importNode.options.optional;
  5772. var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
  5773. if (!context.importMultiple) {
  5774. if (duplicateImport) {
  5775. importNode.skip = true;
  5776. } else {
  5777. importNode.skip = function () {
  5778. if (fullPath in importVisitor.onceFileDetectionMap) {
  5779. return true;
  5780. }
  5781. importVisitor.onceFileDetectionMap[fullPath] = true;
  5782. return false;
  5783. };
  5784. }
  5785. }
  5786. if (!fullPath && isOptional) {
  5787. importNode.skip = true;
  5788. }
  5789. if (root) {
  5790. importNode.root = root;
  5791. importNode.importedFilename = fullPath;
  5792. if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
  5793. importVisitor.recursionDetector[fullPath] = true;
  5794. var oldContext = this.context;
  5795. this.context = context;
  5796. try {
  5797. this._visitor.visit(root);
  5798. } catch (e) {
  5799. this.error = e;
  5800. }
  5801. this.context = oldContext;
  5802. }
  5803. }
  5804. importVisitor.importCount--;
  5805. if (importVisitor.isFinished) {
  5806. importVisitor._sequencer.tryRun();
  5807. }
  5808. },
  5809. visitDeclaration: function visitDeclaration(declNode, visitArgs) {
  5810. if (declNode.value.type === 'DetachedRuleset') {
  5811. this.context.frames.unshift(declNode);
  5812. } else {
  5813. visitArgs.visitDeeper = false;
  5814. }
  5815. },
  5816. visitDeclarationOut: function visitDeclarationOut(declNode) {
  5817. if (declNode.value.type === 'DetachedRuleset') {
  5818. this.context.frames.shift();
  5819. }
  5820. },
  5821. visitAtRule: function visitAtRule(atRuleNode, visitArgs) {
  5822. this.context.frames.unshift(atRuleNode);
  5823. },
  5824. visitAtRuleOut: function visitAtRuleOut(atRuleNode) {
  5825. this.context.frames.shift();
  5826. },
  5827. visitMixinDefinition: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  5828. this.context.frames.unshift(mixinDefinitionNode);
  5829. },
  5830. visitMixinDefinitionOut: function visitMixinDefinitionOut(mixinDefinitionNode) {
  5831. this.context.frames.shift();
  5832. },
  5833. visitRuleset: function visitRuleset(rulesetNode, visitArgs) {
  5834. this.context.frames.unshift(rulesetNode);
  5835. },
  5836. visitRulesetOut: function visitRulesetOut(rulesetNode) {
  5837. this.context.frames.shift();
  5838. },
  5839. visitMedia: function visitMedia(mediaNode, visitArgs) {
  5840. this.context.frames.unshift(mediaNode.rules[0]);
  5841. },
  5842. visitMediaOut: function visitMediaOut(mediaNode) {
  5843. this.context.frames.shift();
  5844. }
  5845. };
  5846. var SetTreeVisibilityVisitor =
  5847. /*#__PURE__*/
  5848. function () {
  5849. function SetTreeVisibilityVisitor(visible) {
  5850. _classCallCheck(this, SetTreeVisibilityVisitor);
  5851. this.visible = visible;
  5852. }
  5853. _createClass(SetTreeVisibilityVisitor, [{
  5854. key: "run",
  5855. value: function run(root) {
  5856. this.visit(root);
  5857. }
  5858. }, {
  5859. key: "visitArray",
  5860. value: function visitArray(nodes) {
  5861. if (!nodes) {
  5862. return nodes;
  5863. }
  5864. var cnt = nodes.length;
  5865. var i;
  5866. for (i = 0; i < cnt; i++) {
  5867. this.visit(nodes[i]);
  5868. }
  5869. return nodes;
  5870. }
  5871. }, {
  5872. key: "visit",
  5873. value: function visit(node) {
  5874. if (!node) {
  5875. return node;
  5876. }
  5877. if (node.constructor === Array) {
  5878. return this.visitArray(node);
  5879. }
  5880. if (!node.blocksVisibility || node.blocksVisibility()) {
  5881. return node;
  5882. }
  5883. if (this.visible) {
  5884. node.ensureVisibility();
  5885. } else {
  5886. node.ensureInvisibility();
  5887. }
  5888. node.accept(this);
  5889. return node;
  5890. }
  5891. }]);
  5892. return SetTreeVisibilityVisitor;
  5893. }();
  5894. /* jshint loopfunc:true */
  5895. var ExtendFinderVisitor =
  5896. /*#__PURE__*/
  5897. function () {
  5898. function ExtendFinderVisitor() {
  5899. _classCallCheck(this, ExtendFinderVisitor);
  5900. this._visitor = new Visitor(this);
  5901. this.contexts = [];
  5902. this.allExtendsStack = [[]];
  5903. }
  5904. _createClass(ExtendFinderVisitor, [{
  5905. key: "run",
  5906. value: function run(root) {
  5907. root = this._visitor.visit(root);
  5908. root.allExtends = this.allExtendsStack[0];
  5909. return root;
  5910. }
  5911. }, {
  5912. key: "visitDeclaration",
  5913. value: function visitDeclaration(declNode, visitArgs) {
  5914. visitArgs.visitDeeper = false;
  5915. }
  5916. }, {
  5917. key: "visitMixinDefinition",
  5918. value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  5919. visitArgs.visitDeeper = false;
  5920. }
  5921. }, {
  5922. key: "visitRuleset",
  5923. value: function visitRuleset(rulesetNode, visitArgs) {
  5924. if (rulesetNode.root) {
  5925. return;
  5926. }
  5927. var i;
  5928. var j;
  5929. var extend;
  5930. var allSelectorsExtendList = [];
  5931. var extendList; // get &:extend(.a); rules which apply to all selectors in this ruleset
  5932. var rules = rulesetNode.rules;
  5933. var ruleCnt = rules ? rules.length : 0;
  5934. for (i = 0; i < ruleCnt; i++) {
  5935. if (rulesetNode.rules[i] instanceof tree.Extend) {
  5936. allSelectorsExtendList.push(rules[i]);
  5937. rulesetNode.extendOnEveryPath = true;
  5938. }
  5939. } // now find every selector and apply the extends that apply to all extends
  5940. // and the ones which apply to an individual extend
  5941. var paths = rulesetNode.paths;
  5942. for (i = 0; i < paths.length; i++) {
  5943. var selectorPath = paths[i];
  5944. var selector = selectorPath[selectorPath.length - 1];
  5945. var selExtendList = selector.extendList;
  5946. extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList) : allSelectorsExtendList;
  5947. if (extendList) {
  5948. extendList = extendList.map(function (allSelectorsExtend) {
  5949. return allSelectorsExtend.clone();
  5950. });
  5951. }
  5952. for (j = 0; j < extendList.length; j++) {
  5953. this.foundExtends = true;
  5954. extend = extendList[j];
  5955. extend.findSelfSelectors(selectorPath);
  5956. extend.ruleset = rulesetNode;
  5957. if (j === 0) {
  5958. extend.firstExtendOnThisSelectorPath = true;
  5959. }
  5960. this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
  5961. }
  5962. }
  5963. this.contexts.push(rulesetNode.selectors);
  5964. }
  5965. }, {
  5966. key: "visitRulesetOut",
  5967. value: function visitRulesetOut(rulesetNode) {
  5968. if (!rulesetNode.root) {
  5969. this.contexts.length = this.contexts.length - 1;
  5970. }
  5971. }
  5972. }, {
  5973. key: "visitMedia",
  5974. value: function visitMedia(mediaNode, visitArgs) {
  5975. mediaNode.allExtends = [];
  5976. this.allExtendsStack.push(mediaNode.allExtends);
  5977. }
  5978. }, {
  5979. key: "visitMediaOut",
  5980. value: function visitMediaOut(mediaNode) {
  5981. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  5982. }
  5983. }, {
  5984. key: "visitAtRule",
  5985. value: function visitAtRule(atRuleNode, visitArgs) {
  5986. atRuleNode.allExtends = [];
  5987. this.allExtendsStack.push(atRuleNode.allExtends);
  5988. }
  5989. }, {
  5990. key: "visitAtRuleOut",
  5991. value: function visitAtRuleOut(atRuleNode) {
  5992. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  5993. }
  5994. }]);
  5995. return ExtendFinderVisitor;
  5996. }();
  5997. var ProcessExtendsVisitor =
  5998. /*#__PURE__*/
  5999. function () {
  6000. function ProcessExtendsVisitor() {
  6001. _classCallCheck(this, ProcessExtendsVisitor);
  6002. this._visitor = new Visitor(this);
  6003. }
  6004. _createClass(ProcessExtendsVisitor, [{
  6005. key: "run",
  6006. value: function run(root) {
  6007. var extendFinder = new ExtendFinderVisitor();
  6008. this.extendIndices = {};
  6009. extendFinder.run(root);
  6010. if (!extendFinder.foundExtends) {
  6011. return root;
  6012. }
  6013. root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
  6014. this.allExtendsStack = [root.allExtends];
  6015. var newRoot = this._visitor.visit(root);
  6016. this.checkExtendsForNonMatched(root.allExtends);
  6017. return newRoot;
  6018. }
  6019. }, {
  6020. key: "checkExtendsForNonMatched",
  6021. value: function checkExtendsForNonMatched(extendList) {
  6022. var indices = this.extendIndices;
  6023. extendList.filter(function (extend) {
  6024. return !extend.hasFoundMatches && extend.parent_ids.length == 1;
  6025. }).forEach(function (extend) {
  6026. var selector = '_unknown_';
  6027. try {
  6028. selector = extend.selector.toCSS({});
  6029. } catch (_) {}
  6030. if (!indices[`${extend.index} ${selector}`]) {
  6031. indices[`${extend.index} ${selector}`] = true;
  6032. logger.warn(`extend '${selector}' has no matches`);
  6033. }
  6034. });
  6035. }
  6036. }, {
  6037. key: "doExtendChaining",
  6038. value: function doExtendChaining(extendsList, extendsListTarget, iterationCount) {
  6039. //
  6040. // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
  6041. // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
  6042. // this means this new extend can then go and alter other extends
  6043. //
  6044. // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
  6045. // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
  6046. // processed if we look at each selector at a time, as is done in visitRuleset
  6047. var extendIndex;
  6048. var targetExtendIndex;
  6049. var matches;
  6050. var extendsToAdd = [];
  6051. var newSelector;
  6052. var extendVisitor = this;
  6053. var selectorPath;
  6054. var extend;
  6055. var targetExtend;
  6056. var newExtend;
  6057. iterationCount = iterationCount || 0; // loop through comparing every extend with every target extend.
  6058. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
  6059. // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
  6060. // and the second is the target.
  6061. // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
  6062. // case when processing media queries
  6063. for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
  6064. for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
  6065. extend = extendsList[extendIndex];
  6066. targetExtend = extendsListTarget[targetExtendIndex]; // look for circular references
  6067. if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
  6068. continue;
  6069. } // find a match in the target extends self selector (the bit before :extend)
  6070. selectorPath = [targetExtend.selfSelectors[0]];
  6071. matches = extendVisitor.findMatch(extend, selectorPath);
  6072. if (matches.length) {
  6073. extend.hasFoundMatches = true; // we found a match, so for each self selector..
  6074. extend.selfSelectors.forEach(function (selfSelector) {
  6075. var info = targetExtend.visibilityInfo(); // process the extend as usual
  6076. newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible()); // but now we create a new extend from it
  6077. newExtend = new tree.Extend(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
  6078. newExtend.selfSelectors = newSelector; // add the extend onto the list of extends for that selector
  6079. newSelector[newSelector.length - 1].extendList = [newExtend]; // record that we need to add it.
  6080. extendsToAdd.push(newExtend);
  6081. newExtend.ruleset = targetExtend.ruleset; // remember its parents for circular references
  6082. newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); // only process the selector once.. if we have :extend(.a,.b) then multiple
  6083. // extends will look at the same selector path, so when extending
  6084. // we know that any others will be duplicates in terms of what is added to the css
  6085. if (targetExtend.firstExtendOnThisSelectorPath) {
  6086. newExtend.firstExtendOnThisSelectorPath = true;
  6087. targetExtend.ruleset.paths.push(newSelector);
  6088. }
  6089. });
  6090. }
  6091. }
  6092. }
  6093. if (extendsToAdd.length) {
  6094. // try to detect circular references to stop a stack overflow.
  6095. // may no longer be needed.
  6096. this.extendChainCount++;
  6097. if (iterationCount > 100) {
  6098. var selectorOne = '{unable to calculate}';
  6099. var selectorTwo = '{unable to calculate}';
  6100. try {
  6101. selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
  6102. selectorTwo = extendsToAdd[0].selector.toCSS();
  6103. } catch (e) {}
  6104. throw {
  6105. message: `extend circular reference detected. One of the circular extends is currently:${selectorOne}:extend(${selectorTwo})`
  6106. };
  6107. } // now process the new extends on the existing rules so that we can handle a extending b extending c extending
  6108. // d extending e...
  6109. return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
  6110. } else {
  6111. return extendsToAdd;
  6112. }
  6113. }
  6114. }, {
  6115. key: "visitDeclaration",
  6116. value: function visitDeclaration(ruleNode, visitArgs) {
  6117. visitArgs.visitDeeper = false;
  6118. }
  6119. }, {
  6120. key: "visitMixinDefinition",
  6121. value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  6122. visitArgs.visitDeeper = false;
  6123. }
  6124. }, {
  6125. key: "visitSelector",
  6126. value: function visitSelector(selectorNode, visitArgs) {
  6127. visitArgs.visitDeeper = false;
  6128. }
  6129. }, {
  6130. key: "visitRuleset",
  6131. value: function visitRuleset(rulesetNode, visitArgs) {
  6132. if (rulesetNode.root) {
  6133. return;
  6134. }
  6135. var matches;
  6136. var pathIndex;
  6137. var extendIndex;
  6138. var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
  6139. var selectorsToAdd = [];
  6140. var extendVisitor = this;
  6141. var selectorPath; // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
  6142. for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
  6143. for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
  6144. selectorPath = rulesetNode.paths[pathIndex]; // extending extends happens initially, before the main pass
  6145. if (rulesetNode.extendOnEveryPath) {
  6146. continue;
  6147. }
  6148. var extendList = selectorPath[selectorPath.length - 1].extendList;
  6149. if (extendList && extendList.length) {
  6150. continue;
  6151. }
  6152. matches = this.findMatch(allExtends[extendIndex], selectorPath);
  6153. if (matches.length) {
  6154. allExtends[extendIndex].hasFoundMatches = true;
  6155. allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
  6156. var extendedSelectors;
  6157. extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
  6158. selectorsToAdd.push(extendedSelectors);
  6159. });
  6160. }
  6161. }
  6162. }
  6163. rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
  6164. }
  6165. }, {
  6166. key: "findMatch",
  6167. value: function findMatch(extend, haystackSelectorPath) {
  6168. //
  6169. // look through the haystack selector path to try and find the needle - extend.selector
  6170. // returns an array of selector matches that can then be replaced
  6171. //
  6172. var haystackSelectorIndex;
  6173. var hackstackSelector;
  6174. var hackstackElementIndex;
  6175. var haystackElement;
  6176. var targetCombinator;
  6177. var i;
  6178. var extendVisitor = this;
  6179. var needleElements = extend.selector.elements;
  6180. var potentialMatches = [];
  6181. var potentialMatch;
  6182. var matches = []; // loop through the haystack elements
  6183. for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
  6184. hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
  6185. for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
  6186. haystackElement = hackstackSelector.elements[hackstackElementIndex]; // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
  6187. if (extend.allowBefore || haystackSelectorIndex === 0 && hackstackElementIndex === 0) {
  6188. potentialMatches.push({
  6189. pathIndex: haystackSelectorIndex,
  6190. index: hackstackElementIndex,
  6191. matched: 0,
  6192. initialCombinator: haystackElement.combinator
  6193. });
  6194. }
  6195. for (i = 0; i < potentialMatches.length; i++) {
  6196. potentialMatch = potentialMatches[i]; // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
  6197. // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
  6198. // work out what the resulting combinator will be
  6199. targetCombinator = haystackElement.combinator.value;
  6200. if (targetCombinator === '' && hackstackElementIndex === 0) {
  6201. targetCombinator = ' ';
  6202. } // if we don't match, null our match to indicate failure
  6203. if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator) {
  6204. potentialMatch = null;
  6205. } else {
  6206. potentialMatch.matched++;
  6207. } // if we are still valid and have finished, test whether we have elements after and whether these are allowed
  6208. if (potentialMatch) {
  6209. potentialMatch.finished = potentialMatch.matched === needleElements.length;
  6210. if (potentialMatch.finished && !extend.allowAfter && (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length)) {
  6211. potentialMatch = null;
  6212. }
  6213. } // if null we remove, if not, we are still valid, so either push as a valid match or continue
  6214. if (potentialMatch) {
  6215. if (potentialMatch.finished) {
  6216. potentialMatch.length = needleElements.length;
  6217. potentialMatch.endPathIndex = haystackSelectorIndex;
  6218. potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
  6219. potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
  6220. matches.push(potentialMatch);
  6221. }
  6222. } else {
  6223. potentialMatches.splice(i, 1);
  6224. i--;
  6225. }
  6226. }
  6227. }
  6228. }
  6229. return matches;
  6230. }
  6231. }, {
  6232. key: "isElementValuesEqual",
  6233. value: function isElementValuesEqual(elementValue1, elementValue2) {
  6234. if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
  6235. return elementValue1 === elementValue2;
  6236. }
  6237. if (elementValue1 instanceof tree.Attribute) {
  6238. if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
  6239. return false;
  6240. }
  6241. if (!elementValue1.value || !elementValue2.value) {
  6242. if (elementValue1.value || elementValue2.value) {
  6243. return false;
  6244. }
  6245. return true;
  6246. }
  6247. elementValue1 = elementValue1.value.value || elementValue1.value;
  6248. elementValue2 = elementValue2.value.value || elementValue2.value;
  6249. return elementValue1 === elementValue2;
  6250. }
  6251. elementValue1 = elementValue1.value;
  6252. elementValue2 = elementValue2.value;
  6253. if (elementValue1 instanceof tree.Selector) {
  6254. if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
  6255. return false;
  6256. }
  6257. for (var i = 0; i < elementValue1.elements.length; i++) {
  6258. if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
  6259. if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
  6260. return false;
  6261. }
  6262. }
  6263. if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
  6264. return false;
  6265. }
  6266. }
  6267. return true;
  6268. }
  6269. return false;
  6270. }
  6271. }, {
  6272. key: "extendSelector",
  6273. value: function extendSelector(matches, selectorPath, replacementSelector, isVisible) {
  6274. // for a set of matches, replace each match with the replacement selector
  6275. var currentSelectorPathIndex = 0;
  6276. var currentSelectorPathElementIndex = 0;
  6277. var path = [];
  6278. var matchIndex;
  6279. var selector;
  6280. var firstElement;
  6281. var match;
  6282. var newElements;
  6283. for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
  6284. match = matches[matchIndex];
  6285. selector = selectorPath[match.pathIndex];
  6286. firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
  6287. if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
  6288. path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  6289. currentSelectorPathElementIndex = 0;
  6290. currentSelectorPathIndex++;
  6291. }
  6292. newElements = selector.elements.slice(currentSelectorPathElementIndex, match.index).concat([firstElement]).concat(replacementSelector.elements.slice(1));
  6293. if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
  6294. path[path.length - 1].elements = path[path.length - 1].elements.concat(newElements);
  6295. } else {
  6296. path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
  6297. path.push(new tree.Selector(newElements));
  6298. }
  6299. currentSelectorPathIndex = match.endPathIndex;
  6300. currentSelectorPathElementIndex = match.endPathElementIndex;
  6301. if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
  6302. currentSelectorPathElementIndex = 0;
  6303. currentSelectorPathIndex++;
  6304. }
  6305. }
  6306. if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
  6307. path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  6308. currentSelectorPathIndex++;
  6309. }
  6310. path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
  6311. path = path.map(function (currentValue) {
  6312. // we can re-use elements here, because the visibility property matters only for selectors
  6313. var derived = currentValue.createDerived(currentValue.elements);
  6314. if (isVisible) {
  6315. derived.ensureVisibility();
  6316. } else {
  6317. derived.ensureInvisibility();
  6318. }
  6319. return derived;
  6320. });
  6321. return path;
  6322. }
  6323. }, {
  6324. key: "visitMedia",
  6325. value: function visitMedia(mediaNode, visitArgs) {
  6326. var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  6327. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
  6328. this.allExtendsStack.push(newAllExtends);
  6329. }
  6330. }, {
  6331. key: "visitMediaOut",
  6332. value: function visitMediaOut(mediaNode) {
  6333. var lastIndex = this.allExtendsStack.length - 1;
  6334. this.allExtendsStack.length = lastIndex;
  6335. }
  6336. }, {
  6337. key: "visitAtRule",
  6338. value: function visitAtRule(atRuleNode, visitArgs) {
  6339. var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  6340. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
  6341. this.allExtendsStack.push(newAllExtends);
  6342. }
  6343. }, {
  6344. key: "visitAtRuleOut",
  6345. value: function visitAtRuleOut(atRuleNode) {
  6346. var lastIndex = this.allExtendsStack.length - 1;
  6347. this.allExtendsStack.length = lastIndex;
  6348. }
  6349. }]);
  6350. return ProcessExtendsVisitor;
  6351. }();
  6352. var JoinSelectorVisitor =
  6353. /*#__PURE__*/
  6354. function () {
  6355. function JoinSelectorVisitor() {
  6356. _classCallCheck(this, JoinSelectorVisitor);
  6357. this.contexts = [[]];
  6358. this._visitor = new Visitor(this);
  6359. }
  6360. _createClass(JoinSelectorVisitor, [{
  6361. key: "run",
  6362. value: function run(root) {
  6363. return this._visitor.visit(root);
  6364. }
  6365. }, {
  6366. key: "visitDeclaration",
  6367. value: function visitDeclaration(declNode, visitArgs) {
  6368. visitArgs.visitDeeper = false;
  6369. }
  6370. }, {
  6371. key: "visitMixinDefinition",
  6372. value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  6373. visitArgs.visitDeeper = false;
  6374. }
  6375. }, {
  6376. key: "visitRuleset",
  6377. value: function visitRuleset(rulesetNode, visitArgs) {
  6378. var context = this.contexts[this.contexts.length - 1];
  6379. var paths = [];
  6380. var selectors;
  6381. this.contexts.push(paths);
  6382. if (!rulesetNode.root) {
  6383. selectors = rulesetNode.selectors;
  6384. if (selectors) {
  6385. selectors = selectors.filter(function (selector) {
  6386. return selector.getIsOutput();
  6387. });
  6388. rulesetNode.selectors = selectors.length ? selectors : selectors = null;
  6389. if (selectors) {
  6390. rulesetNode.joinSelectors(paths, context, selectors);
  6391. }
  6392. }
  6393. if (!selectors) {
  6394. rulesetNode.rules = null;
  6395. }
  6396. rulesetNode.paths = paths;
  6397. }
  6398. }
  6399. }, {
  6400. key: "visitRulesetOut",
  6401. value: function visitRulesetOut(rulesetNode) {
  6402. this.contexts.length = this.contexts.length - 1;
  6403. }
  6404. }, {
  6405. key: "visitMedia",
  6406. value: function visitMedia(mediaNode, visitArgs) {
  6407. var context = this.contexts[this.contexts.length - 1];
  6408. mediaNode.rules[0].root = context.length === 0 || context[0].multiMedia;
  6409. }
  6410. }, {
  6411. key: "visitAtRule",
  6412. value: function visitAtRule(atRuleNode, visitArgs) {
  6413. var context = this.contexts[this.contexts.length - 1];
  6414. if (atRuleNode.rules && atRuleNode.rules.length) {
  6415. atRuleNode.rules[0].root = atRuleNode.isRooted || context.length === 0 || null;
  6416. }
  6417. }
  6418. }]);
  6419. return JoinSelectorVisitor;
  6420. }();
  6421. var CSSVisitorUtils =
  6422. /*#__PURE__*/
  6423. function () {
  6424. function CSSVisitorUtils(context) {
  6425. _classCallCheck(this, CSSVisitorUtils);
  6426. this._visitor = new Visitor(this);
  6427. this._context = context;
  6428. }
  6429. _createClass(CSSVisitorUtils, [{
  6430. key: "containsSilentNonBlockedChild",
  6431. value: function containsSilentNonBlockedChild(bodyRules) {
  6432. var rule;
  6433. if (!bodyRules) {
  6434. return false;
  6435. }
  6436. for (var r = 0; r < bodyRules.length; r++) {
  6437. rule = bodyRules[r];
  6438. if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
  6439. // the atrule contains something that was referenced (likely by extend)
  6440. // therefore it needs to be shown in output too
  6441. return true;
  6442. }
  6443. }
  6444. return false;
  6445. }
  6446. }, {
  6447. key: "keepOnlyVisibleChilds",
  6448. value: function keepOnlyVisibleChilds(owner) {
  6449. if (owner && owner.rules) {
  6450. owner.rules = owner.rules.filter(function (thing) {
  6451. return thing.isVisible();
  6452. });
  6453. }
  6454. }
  6455. }, {
  6456. key: "isEmpty",
  6457. value: function isEmpty(owner) {
  6458. return owner && owner.rules ? owner.rules.length === 0 : true;
  6459. }
  6460. }, {
  6461. key: "hasVisibleSelector",
  6462. value: function hasVisibleSelector(rulesetNode) {
  6463. return rulesetNode && rulesetNode.paths ? rulesetNode.paths.length > 0 : false;
  6464. }
  6465. }, {
  6466. key: "resolveVisibility",
  6467. value: function resolveVisibility(node, originalRules) {
  6468. if (!node.blocksVisibility()) {
  6469. if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
  6470. return;
  6471. }
  6472. return node;
  6473. }
  6474. var compiledRulesBody = node.rules[0];
  6475. this.keepOnlyVisibleChilds(compiledRulesBody);
  6476. if (this.isEmpty(compiledRulesBody)) {
  6477. return;
  6478. }
  6479. node.ensureVisibility();
  6480. node.removeVisibilityBlock();
  6481. return node;
  6482. }
  6483. }, {
  6484. key: "isVisibleRuleset",
  6485. value: function isVisibleRuleset(rulesetNode) {
  6486. if (rulesetNode.firstRoot) {
  6487. return true;
  6488. }
  6489. if (this.isEmpty(rulesetNode)) {
  6490. return false;
  6491. }
  6492. if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
  6493. return false;
  6494. }
  6495. return true;
  6496. }
  6497. }]);
  6498. return CSSVisitorUtils;
  6499. }();
  6500. var ToCSSVisitor = function ToCSSVisitor(context) {
  6501. this._visitor = new Visitor(this);
  6502. this._context = context;
  6503. this.utils = new CSSVisitorUtils(context);
  6504. };
  6505. ToCSSVisitor.prototype = {
  6506. isReplacing: true,
  6507. run: function run(root) {
  6508. return this._visitor.visit(root);
  6509. },
  6510. visitDeclaration: function visitDeclaration(declNode, visitArgs) {
  6511. if (declNode.blocksVisibility() || declNode.variable) {
  6512. return;
  6513. }
  6514. return declNode;
  6515. },
  6516. visitMixinDefinition: function visitMixinDefinition(mixinNode, visitArgs) {
  6517. // mixin definitions do not get eval'd - this means they keep state
  6518. // so we have to clear that state here so it isn't used if toCSS is called twice
  6519. mixinNode.frames = [];
  6520. },
  6521. visitExtend: function visitExtend(extendNode, visitArgs) {},
  6522. visitComment: function visitComment(commentNode, visitArgs) {
  6523. if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
  6524. return;
  6525. }
  6526. return commentNode;
  6527. },
  6528. visitMedia: function visitMedia(mediaNode, visitArgs) {
  6529. var originalRules = mediaNode.rules[0].rules;
  6530. mediaNode.accept(this._visitor);
  6531. visitArgs.visitDeeper = false;
  6532. return this.utils.resolveVisibility(mediaNode, originalRules);
  6533. },
  6534. visitImport: function visitImport(importNode, visitArgs) {
  6535. if (importNode.blocksVisibility()) {
  6536. return;
  6537. }
  6538. return importNode;
  6539. },
  6540. visitAtRule: function visitAtRule(atRuleNode, visitArgs) {
  6541. if (atRuleNode.rules && atRuleNode.rules.length) {
  6542. return this.visitAtRuleWithBody(atRuleNode, visitArgs);
  6543. } else {
  6544. return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
  6545. }
  6546. },
  6547. visitAnonymous: function visitAnonymous(anonymousNode, visitArgs) {
  6548. if (!anonymousNode.blocksVisibility()) {
  6549. anonymousNode.accept(this._visitor);
  6550. return anonymousNode;
  6551. }
  6552. },
  6553. visitAtRuleWithBody: function visitAtRuleWithBody(atRuleNode, visitArgs) {
  6554. // if there is only one nested ruleset and that one has no path, then it is
  6555. // just fake ruleset
  6556. function hasFakeRuleset(atRuleNode) {
  6557. var bodyRules = atRuleNode.rules;
  6558. return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
  6559. }
  6560. function getBodyRules(atRuleNode) {
  6561. var nodeRules = atRuleNode.rules;
  6562. if (hasFakeRuleset(atRuleNode)) {
  6563. return nodeRules[0].rules;
  6564. }
  6565. return nodeRules;
  6566. } // it is still true that it is only one ruleset in array
  6567. // this is last such moment
  6568. // process childs
  6569. var originalRules = getBodyRules(atRuleNode);
  6570. atRuleNode.accept(this._visitor);
  6571. visitArgs.visitDeeper = false;
  6572. if (!this.utils.isEmpty(atRuleNode)) {
  6573. this._mergeRules(atRuleNode.rules[0].rules);
  6574. }
  6575. return this.utils.resolveVisibility(atRuleNode, originalRules);
  6576. },
  6577. visitAtRuleWithoutBody: function visitAtRuleWithoutBody(atRuleNode, visitArgs) {
  6578. if (atRuleNode.blocksVisibility()) {
  6579. return;
  6580. }
  6581. if (atRuleNode.name === '@charset') {
  6582. // Only output the debug info together with subsequent @charset definitions
  6583. // a comment (or @media statement) before the actual @charset atrule would
  6584. // be considered illegal css as it has to be on the first line
  6585. if (this.charset) {
  6586. if (atRuleNode.debugInfo) {
  6587. var comment = new tree.Comment(`/* ${atRuleNode.toCSS(this._context).replace(/\n/g, '')} */\n`);
  6588. comment.debugInfo = atRuleNode.debugInfo;
  6589. return this._visitor.visit(comment);
  6590. }
  6591. return;
  6592. }
  6593. this.charset = true;
  6594. }
  6595. return atRuleNode;
  6596. },
  6597. checkValidNodes: function checkValidNodes(rules, isRoot) {
  6598. if (!rules) {
  6599. return;
  6600. }
  6601. for (var i = 0; i < rules.length; i++) {
  6602. var ruleNode = rules[i];
  6603. if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
  6604. throw {
  6605. message: 'Properties must be inside selector blocks. They cannot be in the root',
  6606. index: ruleNode.getIndex(),
  6607. filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
  6608. };
  6609. }
  6610. if (ruleNode instanceof tree.Call) {
  6611. throw {
  6612. message: `Function '${ruleNode.name}' is undefined`,
  6613. index: ruleNode.getIndex(),
  6614. filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
  6615. };
  6616. }
  6617. if (ruleNode.type && !ruleNode.allowRoot) {
  6618. throw {
  6619. message: `${ruleNode.type} node returned by a function is not valid here`,
  6620. index: ruleNode.getIndex(),
  6621. filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
  6622. };
  6623. }
  6624. }
  6625. },
  6626. visitRuleset: function visitRuleset(rulesetNode, visitArgs) {
  6627. // at this point rulesets are nested into each other
  6628. var rule;
  6629. var rulesets = [];
  6630. this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
  6631. if (!rulesetNode.root) {
  6632. // remove invisible paths
  6633. this._compileRulesetPaths(rulesetNode); // remove rulesets from this ruleset body and compile them separately
  6634. var nodeRules = rulesetNode.rules;
  6635. var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
  6636. for (var i = 0; i < nodeRuleCnt;) {
  6637. rule = nodeRules[i];
  6638. if (rule && rule.rules) {
  6639. // visit because we are moving them out from being a child
  6640. rulesets.push(this._visitor.visit(rule));
  6641. nodeRules.splice(i, 1);
  6642. nodeRuleCnt--;
  6643. continue;
  6644. }
  6645. i++;
  6646. } // accept the visitor to remove rules and refactor itself
  6647. // then we can decide nogw whether we want it or not
  6648. // compile body
  6649. if (nodeRuleCnt > 0) {
  6650. rulesetNode.accept(this._visitor);
  6651. } else {
  6652. rulesetNode.rules = null;
  6653. }
  6654. visitArgs.visitDeeper = false;
  6655. } else {
  6656. // if (! rulesetNode.root) {
  6657. rulesetNode.accept(this._visitor);
  6658. visitArgs.visitDeeper = false;
  6659. }
  6660. if (rulesetNode.rules) {
  6661. this._mergeRules(rulesetNode.rules);
  6662. this._removeDuplicateRules(rulesetNode.rules);
  6663. } // now decide whether we keep the ruleset
  6664. if (this.utils.isVisibleRuleset(rulesetNode)) {
  6665. rulesetNode.ensureVisibility();
  6666. rulesets.splice(0, 0, rulesetNode);
  6667. }
  6668. if (rulesets.length === 1) {
  6669. return rulesets[0];
  6670. }
  6671. return rulesets;
  6672. },
  6673. _compileRulesetPaths: function _compileRulesetPaths(rulesetNode) {
  6674. if (rulesetNode.paths) {
  6675. rulesetNode.paths = rulesetNode.paths.filter(function (p) {
  6676. var i;
  6677. if (p[0].elements[0].combinator.value === ' ') {
  6678. p[0].elements[0].combinator = new tree.Combinator('');
  6679. }
  6680. for (i = 0; i < p.length; i++) {
  6681. if (p[i].isVisible() && p[i].getIsOutput()) {
  6682. return true;
  6683. }
  6684. }
  6685. return false;
  6686. });
  6687. }
  6688. },
  6689. _removeDuplicateRules: function _removeDuplicateRules(rules) {
  6690. if (!rules) {
  6691. return;
  6692. } // remove duplicates
  6693. var ruleCache = {};
  6694. var ruleList;
  6695. var rule;
  6696. var i;
  6697. for (i = rules.length - 1; i >= 0; i--) {
  6698. rule = rules[i];
  6699. if (rule instanceof tree.Declaration) {
  6700. if (!ruleCache[rule.name]) {
  6701. ruleCache[rule.name] = rule;
  6702. } else {
  6703. ruleList = ruleCache[rule.name];
  6704. if (ruleList instanceof tree.Declaration) {
  6705. ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
  6706. }
  6707. var ruleCSS = rule.toCSS(this._context);
  6708. if (ruleList.indexOf(ruleCSS) !== -1) {
  6709. rules.splice(i, 1);
  6710. } else {
  6711. ruleList.push(ruleCSS);
  6712. }
  6713. }
  6714. }
  6715. }
  6716. },
  6717. _mergeRules: function _mergeRules(rules) {
  6718. if (!rules) {
  6719. return;
  6720. }
  6721. var groups = {};
  6722. var groupsArr = [];
  6723. for (var i = 0; i < rules.length; i++) {
  6724. var rule = rules[i];
  6725. if (rule.merge) {
  6726. var key = rule.name;
  6727. groups[key] ? rules.splice(i--, 1) : groupsArr.push(groups[key] = []);
  6728. groups[key].push(rule);
  6729. }
  6730. }
  6731. groupsArr.forEach(function (group) {
  6732. if (group.length > 0) {
  6733. var result = group[0];
  6734. var space = [];
  6735. var comma = [new tree.Expression(space)];
  6736. group.forEach(function (rule) {
  6737. if (rule.merge === '+' && space.length > 0) {
  6738. comma.push(new tree.Expression(space = []));
  6739. }
  6740. space.push(rule.value);
  6741. result.important = result.important || rule.important;
  6742. });
  6743. result.value = new tree.Value(comma);
  6744. }
  6745. });
  6746. }
  6747. };
  6748. var visitors = {
  6749. Visitor,
  6750. ImportVisitor,
  6751. MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
  6752. ExtendVisitor: ProcessExtendsVisitor,
  6753. JoinSelectorVisitor,
  6754. ToCSSVisitor
  6755. };
  6756. // Split the input into chunks.
  6757. var chunker = (function (input, fail) {
  6758. var len = input.length;
  6759. var level = 0;
  6760. var parenLevel = 0;
  6761. var lastOpening;
  6762. var lastOpeningParen;
  6763. var lastMultiComment;
  6764. var lastMultiCommentEndBrace;
  6765. var chunks = [];
  6766. var emitFrom = 0;
  6767. var chunkerCurrentIndex;
  6768. var currentChunkStartIndex;
  6769. var cc;
  6770. var cc2;
  6771. var matched;
  6772. function emitChunk(force) {
  6773. var len = chunkerCurrentIndex - emitFrom;
  6774. if (len < 512 && !force || !len) {
  6775. return;
  6776. }
  6777. chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
  6778. emitFrom = chunkerCurrentIndex + 1;
  6779. }
  6780. for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6781. cc = input.charCodeAt(chunkerCurrentIndex);
  6782. if (cc >= 97 && cc <= 122 || cc < 34) {
  6783. // a-z or whitespace
  6784. continue;
  6785. }
  6786. switch (cc) {
  6787. case 40:
  6788. // (
  6789. parenLevel++;
  6790. lastOpeningParen = chunkerCurrentIndex;
  6791. continue;
  6792. case 41:
  6793. // )
  6794. if (--parenLevel < 0) {
  6795. return fail('missing opening `(`', chunkerCurrentIndex);
  6796. }
  6797. continue;
  6798. case 59:
  6799. // ;
  6800. if (!parenLevel) {
  6801. emitChunk();
  6802. }
  6803. continue;
  6804. case 123:
  6805. // {
  6806. level++;
  6807. lastOpening = chunkerCurrentIndex;
  6808. continue;
  6809. case 125:
  6810. // }
  6811. if (--level < 0) {
  6812. return fail('missing opening `{`', chunkerCurrentIndex);
  6813. }
  6814. if (!level && !parenLevel) {
  6815. emitChunk();
  6816. }
  6817. continue;
  6818. case 92:
  6819. // \
  6820. if (chunkerCurrentIndex < len - 1) {
  6821. chunkerCurrentIndex++;
  6822. continue;
  6823. }
  6824. return fail('unescaped `\\`', chunkerCurrentIndex);
  6825. case 34:
  6826. case 39:
  6827. case 96:
  6828. // ", ' and `
  6829. matched = 0;
  6830. currentChunkStartIndex = chunkerCurrentIndex;
  6831. for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6832. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6833. if (cc2 > 96) {
  6834. continue;
  6835. }
  6836. if (cc2 == cc) {
  6837. matched = 1;
  6838. break;
  6839. }
  6840. if (cc2 == 92) {
  6841. // \
  6842. if (chunkerCurrentIndex == len - 1) {
  6843. return fail('unescaped `\\`', chunkerCurrentIndex);
  6844. }
  6845. chunkerCurrentIndex++;
  6846. }
  6847. }
  6848. if (matched) {
  6849. continue;
  6850. }
  6851. return fail(`unmatched \`${String.fromCharCode(cc)}\``, currentChunkStartIndex);
  6852. case 47:
  6853. // /, check for comment
  6854. if (parenLevel || chunkerCurrentIndex == len - 1) {
  6855. continue;
  6856. }
  6857. cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
  6858. if (cc2 == 47) {
  6859. // //, find lnfeed
  6860. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6861. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6862. if (cc2 <= 13 && (cc2 == 10 || cc2 == 13)) {
  6863. break;
  6864. }
  6865. }
  6866. } else if (cc2 == 42) {
  6867. // /*, find */
  6868. lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
  6869. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
  6870. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6871. if (cc2 == 125) {
  6872. lastMultiCommentEndBrace = chunkerCurrentIndex;
  6873. }
  6874. if (cc2 != 42) {
  6875. continue;
  6876. }
  6877. if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
  6878. break;
  6879. }
  6880. }
  6881. if (chunkerCurrentIndex == len - 1) {
  6882. return fail('missing closing `*/`', currentChunkStartIndex);
  6883. }
  6884. chunkerCurrentIndex++;
  6885. }
  6886. continue;
  6887. case 42:
  6888. // *, check for unmatched */
  6889. if (chunkerCurrentIndex < len - 1 && input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
  6890. return fail('unmatched `/*`', chunkerCurrentIndex);
  6891. }
  6892. continue;
  6893. }
  6894. }
  6895. if (level !== 0) {
  6896. if (lastMultiComment > lastOpening && lastMultiCommentEndBrace > lastMultiComment) {
  6897. return fail('missing closing `}` or `*/`', lastOpening);
  6898. } else {
  6899. return fail('missing closing `}`', lastOpening);
  6900. }
  6901. } else if (parenLevel !== 0) {
  6902. return fail('missing closing `)`', lastOpeningParen);
  6903. }
  6904. emitChunk(true);
  6905. return chunks;
  6906. });
  6907. var getParserInput = (function () {
  6908. var // Less input string
  6909. input;
  6910. var // current chunk
  6911. j;
  6912. var // holds state for backtracking
  6913. saveStack = [];
  6914. var // furthest index the parser has gone to
  6915. furthest;
  6916. var // if this is furthest we got to, this is the probably cause
  6917. furthestPossibleErrorMessage;
  6918. var // chunkified input
  6919. chunks;
  6920. var // current chunk
  6921. current;
  6922. var // index of current chunk, in `input`
  6923. currentPos;
  6924. var parserInput = {};
  6925. var CHARCODE_SPACE = 32;
  6926. var CHARCODE_TAB = 9;
  6927. var CHARCODE_LF = 10;
  6928. var CHARCODE_CR = 13;
  6929. var CHARCODE_PLUS = 43;
  6930. var CHARCODE_COMMA = 44;
  6931. var CHARCODE_FORWARD_SLASH = 47;
  6932. var CHARCODE_9 = 57;
  6933. function skipWhitespace(length) {
  6934. var oldi = parserInput.i;
  6935. var oldj = j;
  6936. var curr = parserInput.i - currentPos;
  6937. var endIndex = parserInput.i + current.length - curr;
  6938. var mem = parserInput.i += length;
  6939. var inp = input;
  6940. var c;
  6941. var nextChar;
  6942. var comment;
  6943. for (; parserInput.i < endIndex; parserInput.i++) {
  6944. c = inp.charCodeAt(parserInput.i);
  6945. if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
  6946. nextChar = inp.charAt(parserInput.i + 1);
  6947. if (nextChar === '/') {
  6948. comment = {
  6949. index: parserInput.i,
  6950. isLineComment: true
  6951. };
  6952. var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
  6953. if (nextNewLine < 0) {
  6954. nextNewLine = endIndex;
  6955. }
  6956. parserInput.i = nextNewLine;
  6957. comment.text = inp.substr(comment.index, parserInput.i - comment.index);
  6958. parserInput.commentStore.push(comment);
  6959. continue;
  6960. } else if (nextChar === '*') {
  6961. var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
  6962. if (nextStarSlash >= 0) {
  6963. comment = {
  6964. index: parserInput.i,
  6965. text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
  6966. isLineComment: false
  6967. };
  6968. parserInput.i += comment.text.length - 1;
  6969. parserInput.commentStore.push(comment);
  6970. continue;
  6971. }
  6972. }
  6973. break;
  6974. }
  6975. if (c !== CHARCODE_SPACE && c !== CHARCODE_LF && c !== CHARCODE_TAB && c !== CHARCODE_CR) {
  6976. break;
  6977. }
  6978. }
  6979. current = current.slice(length + parserInput.i - mem + curr);
  6980. currentPos = parserInput.i;
  6981. if (!current.length) {
  6982. if (j < chunks.length - 1) {
  6983. current = chunks[++j];
  6984. skipWhitespace(0); // skip space at the beginning of a chunk
  6985. return true; // things changed
  6986. }
  6987. parserInput.finished = true;
  6988. }
  6989. return oldi !== parserInput.i || oldj !== j;
  6990. }
  6991. parserInput.save = function () {
  6992. currentPos = parserInput.i;
  6993. saveStack.push({
  6994. current,
  6995. i: parserInput.i,
  6996. j
  6997. });
  6998. };
  6999. parserInput.restore = function (possibleErrorMessage) {
  7000. if (parserInput.i > furthest || parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage) {
  7001. furthest = parserInput.i;
  7002. furthestPossibleErrorMessage = possibleErrorMessage;
  7003. }
  7004. var state = saveStack.pop();
  7005. current = state.current;
  7006. currentPos = parserInput.i = state.i;
  7007. j = state.j;
  7008. };
  7009. parserInput.forget = function () {
  7010. saveStack.pop();
  7011. };
  7012. parserInput.isWhitespace = function (offset) {
  7013. var pos = parserInput.i + (offset || 0);
  7014. var code = input.charCodeAt(pos);
  7015. return code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF;
  7016. }; // Specialization of $(tok)
  7017. parserInput.$re = function (tok) {
  7018. if (parserInput.i > currentPos) {
  7019. current = current.slice(parserInput.i - currentPos);
  7020. currentPos = parserInput.i;
  7021. }
  7022. var m = tok.exec(current);
  7023. if (!m) {
  7024. return null;
  7025. }
  7026. skipWhitespace(m[0].length);
  7027. if (typeof m === 'string') {
  7028. return m;
  7029. }
  7030. return m.length === 1 ? m[0] : m;
  7031. };
  7032. parserInput.$char = function (tok) {
  7033. if (input.charAt(parserInput.i) !== tok) {
  7034. return null;
  7035. }
  7036. skipWhitespace(1);
  7037. return tok;
  7038. };
  7039. parserInput.$str = function (tok) {
  7040. var tokLength = tok.length; // https://jsperf.com/string-startswith/21
  7041. for (var i = 0; i < tokLength; i++) {
  7042. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  7043. return null;
  7044. }
  7045. }
  7046. skipWhitespace(tokLength);
  7047. return tok;
  7048. };
  7049. parserInput.$quoted = function (loc) {
  7050. var pos = loc || parserInput.i;
  7051. var startChar = input.charAt(pos);
  7052. if (startChar !== '\'' && startChar !== '"') {
  7053. return;
  7054. }
  7055. var length = input.length;
  7056. var currentPosition = pos;
  7057. for (var i = 1; i + currentPosition < length; i++) {
  7058. var nextChar = input.charAt(i + currentPosition);
  7059. switch (nextChar) {
  7060. case '\\':
  7061. i++;
  7062. continue;
  7063. case '\r':
  7064. case '\n':
  7065. break;
  7066. case startChar:
  7067. var str = input.substr(currentPosition, i + 1);
  7068. if (!loc && loc !== 0) {
  7069. skipWhitespace(i + 1);
  7070. return str;
  7071. }
  7072. return [startChar, str];
  7073. default:
  7074. }
  7075. }
  7076. return null;
  7077. };
  7078. /**
  7079. * Permissive parsing. Ignores everything except matching {} [] () and quotes
  7080. * until matching token (outside of blocks)
  7081. */
  7082. parserInput.$parseUntil = function (tok) {
  7083. var quote = '';
  7084. var returnVal = null;
  7085. var inComment = false;
  7086. var blockDepth = 0;
  7087. var blockStack = [];
  7088. var parseGroups = [];
  7089. var length = input.length;
  7090. var startPos = parserInput.i;
  7091. var lastPos = parserInput.i;
  7092. var i = parserInput.i;
  7093. var loop = true;
  7094. var testChar;
  7095. if (typeof tok === 'string') {
  7096. testChar = function testChar(char) {
  7097. return char === tok;
  7098. };
  7099. } else {
  7100. testChar = function testChar(char) {
  7101. return tok.test(char);
  7102. };
  7103. }
  7104. do {
  7105. var nextChar = input.charAt(i);
  7106. if (blockDepth === 0 && testChar(nextChar)) {
  7107. returnVal = input.substr(lastPos, i - lastPos);
  7108. if (returnVal) {
  7109. parseGroups.push(returnVal);
  7110. } else {
  7111. parseGroups.push(' ');
  7112. }
  7113. returnVal = parseGroups;
  7114. skipWhitespace(i - startPos);
  7115. loop = false;
  7116. } else {
  7117. if (inComment) {
  7118. if (nextChar === '*' && input.charAt(i + 1) === '/') {
  7119. i++;
  7120. blockDepth--;
  7121. inComment = false;
  7122. }
  7123. i++;
  7124. continue;
  7125. }
  7126. switch (nextChar) {
  7127. case '\\':
  7128. i++;
  7129. nextChar = input.charAt(i);
  7130. parseGroups.push(input.substr(lastPos, i - lastPos + 1));
  7131. lastPos = i + 1;
  7132. break;
  7133. case '/':
  7134. if (input.charAt(i + 1) === '*') {
  7135. i++;
  7136. inComment = true;
  7137. blockDepth++;
  7138. }
  7139. break;
  7140. case '\'':
  7141. case '"':
  7142. quote = parserInput.$quoted(i);
  7143. if (quote) {
  7144. parseGroups.push(input.substr(lastPos, i - lastPos), quote);
  7145. i += quote[1].length - 1;
  7146. lastPos = i + 1;
  7147. } else {
  7148. skipWhitespace(i - startPos);
  7149. returnVal = nextChar;
  7150. loop = false;
  7151. }
  7152. break;
  7153. case '{':
  7154. blockStack.push('}');
  7155. blockDepth++;
  7156. break;
  7157. case '(':
  7158. blockStack.push(')');
  7159. blockDepth++;
  7160. break;
  7161. case '[':
  7162. blockStack.push(']');
  7163. blockDepth++;
  7164. break;
  7165. case '}':
  7166. case ')':
  7167. case ']':
  7168. var expected = blockStack.pop();
  7169. if (nextChar === expected) {
  7170. blockDepth--;
  7171. } else {
  7172. // move the parser to the error and return expected
  7173. skipWhitespace(i - startPos);
  7174. returnVal = expected;
  7175. loop = false;
  7176. }
  7177. }
  7178. i++;
  7179. if (i > length) {
  7180. loop = false;
  7181. }
  7182. }
  7183. } while (loop);
  7184. return returnVal ? returnVal : null;
  7185. };
  7186. parserInput.autoCommentAbsorb = true;
  7187. parserInput.commentStore = [];
  7188. parserInput.finished = false; // Same as $(), but don't change the state of the parser,
  7189. // just return the match.
  7190. parserInput.peek = function (tok) {
  7191. if (typeof tok === 'string') {
  7192. // https://jsperf.com/string-startswith/21
  7193. for (var i = 0; i < tok.length; i++) {
  7194. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  7195. return false;
  7196. }
  7197. }
  7198. return true;
  7199. } else {
  7200. return tok.test(current);
  7201. }
  7202. }; // Specialization of peek()
  7203. // TODO remove or change some currentChar calls to peekChar
  7204. parserInput.peekChar = function (tok) {
  7205. return input.charAt(parserInput.i) === tok;
  7206. };
  7207. parserInput.currentChar = function () {
  7208. return input.charAt(parserInput.i);
  7209. };
  7210. parserInput.prevChar = function () {
  7211. return input.charAt(parserInput.i - 1);
  7212. };
  7213. parserInput.getInput = function () {
  7214. return input;
  7215. };
  7216. parserInput.peekNotNumeric = function () {
  7217. var c = input.charCodeAt(parserInput.i); // Is the first char of the dimension 0-9, '.', '+' or '-'
  7218. return c > CHARCODE_9 || c < CHARCODE_PLUS || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
  7219. };
  7220. parserInput.start = function (str, chunkInput, failFunction) {
  7221. input = str;
  7222. parserInput.i = j = currentPos = furthest = 0; // chunking apparently makes things quicker (but my tests indicate
  7223. // it might actually make things slower in node at least)
  7224. // and it is a non-perfect parse - it can't recognise
  7225. // unquoted urls, meaning it can't distinguish comments
  7226. // meaning comments with quotes or {}() in them get 'counted'
  7227. // and then lead to parse errors.
  7228. // In addition if the chunking chunks in the wrong place we might
  7229. // not be able to parse a parser statement in one go
  7230. // this is officially deprecated but can be switched on via an option
  7231. // in the case it causes too much performance issues.
  7232. if (chunkInput) {
  7233. chunks = chunker(str, failFunction);
  7234. } else {
  7235. chunks = [str];
  7236. }
  7237. current = chunks[0];
  7238. skipWhitespace(0);
  7239. };
  7240. parserInput.end = function () {
  7241. var message;
  7242. var isFinished = parserInput.i >= input.length;
  7243. if (parserInput.i < furthest) {
  7244. message = furthestPossibleErrorMessage;
  7245. parserInput.i = furthest;
  7246. }
  7247. return {
  7248. isFinished,
  7249. furthest: parserInput.i,
  7250. furthestPossibleErrorMessage: message,
  7251. furthestReachedEnd: parserInput.i >= input.length - 1,
  7252. furthestChar: input[parserInput.i]
  7253. };
  7254. };
  7255. return parserInput;
  7256. });
  7257. // less.js - parser
  7258. //
  7259. // A relatively straight-forward predictive parser.
  7260. // There is no tokenization/lexing stage, the input is parsed
  7261. // in one sweep.
  7262. //
  7263. // To make the parser fast enough to run in the browser, several
  7264. // optimization had to be made:
  7265. //
  7266. // - Matching and slicing on a huge input is often cause of slowdowns.
  7267. // The solution is to chunkify the input into smaller strings.
  7268. // The chunks are stored in the `chunks` var,
  7269. // `j` holds the current chunk index, and `currentPos` holds
  7270. // the index of the current chunk in relation to `input`.
  7271. // This gives us an almost 4x speed-up.
  7272. //
  7273. // - In many cases, we don't need to match individual tokens;
  7274. // for example, if a value doesn't hold any variables, operations
  7275. // or dynamic references, the parser can effectively 'skip' it,
  7276. // treating it as a literal.
  7277. // An example would be '1px solid #000' - which evaluates to itself,
  7278. // we don't need to know what the individual components are.
  7279. // The drawback, of course is that you don't get the benefits of
  7280. // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
  7281. // and a smaller speed-up in the code-gen.
  7282. //
  7283. //
  7284. // Token matching is done with the `$` function, which either takes
  7285. // a terminal string or regexp, or a non-terminal function to call.
  7286. // It also takes care of moving all the indices forwards.
  7287. //
  7288. var Parser = function Parser(context, imports, fileInfo) {
  7289. var parsers;
  7290. var parserInput = getParserInput();
  7291. function error(msg, type) {
  7292. throw new LessError({
  7293. index: parserInput.i,
  7294. filename: fileInfo.filename,
  7295. type: type || 'Syntax',
  7296. message: msg
  7297. }, imports);
  7298. }
  7299. function expect(arg, msg) {
  7300. // some older browsers return typeof 'function' for RegExp
  7301. var result = arg instanceof Function ? arg.call(parsers) : parserInput.$re(arg);
  7302. if (result) {
  7303. return result;
  7304. }
  7305. error(msg || (typeof arg === 'string' ? `expected '${arg}' got '${parserInput.currentChar()}'` : 'unexpected token'));
  7306. } // Specialization of expect()
  7307. function expectChar(arg, msg) {
  7308. if (parserInput.$char(arg)) {
  7309. return arg;
  7310. }
  7311. error(msg || `expected '${arg}' got '${parserInput.currentChar()}'`);
  7312. }
  7313. function getDebugInfo(index) {
  7314. var filename = fileInfo.filename;
  7315. return {
  7316. lineNumber: getLocation(index, parserInput.getInput()).line + 1,
  7317. fileName: filename
  7318. };
  7319. }
  7320. /**
  7321. * Used after initial parsing to create nodes on the fly
  7322. *
  7323. * @param {String} str - string to parse
  7324. * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
  7325. * @param {Number} currentIndex - start number to begin indexing
  7326. * @param {Object} fileInfo - fileInfo to attach to created nodes
  7327. */
  7328. function parseNode(str, parseList, currentIndex, fileInfo, callback) {
  7329. var result;
  7330. var returnNodes = [];
  7331. var parser = parserInput;
  7332. try {
  7333. parser.start(str, false, function fail(msg, index) {
  7334. callback({
  7335. message: msg,
  7336. index: index + currentIndex
  7337. });
  7338. });
  7339. for (var x = 0, p, i; p = parseList[x]; x++) {
  7340. i = parser.i;
  7341. result = parsers[p]();
  7342. if (result) {
  7343. try {
  7344. result._index = i + currentIndex;
  7345. result._fileInfo = fileInfo;
  7346. } catch (e) {}
  7347. returnNodes.push(result);
  7348. } else {
  7349. returnNodes.push(null);
  7350. }
  7351. }
  7352. var endInfo = parser.end();
  7353. if (endInfo.isFinished) {
  7354. callback(null, returnNodes);
  7355. } else {
  7356. callback(true, null);
  7357. }
  7358. } catch (e) {
  7359. throw new LessError({
  7360. index: e.index + currentIndex,
  7361. message: e.message
  7362. }, imports, fileInfo.filename);
  7363. }
  7364. } //
  7365. // The Parser
  7366. //
  7367. return {
  7368. parserInput,
  7369. imports,
  7370. fileInfo,
  7371. parseNode,
  7372. //
  7373. // Parse an input string into an abstract syntax tree,
  7374. // @param str A string containing 'less' markup
  7375. // @param callback call `callback` when done.
  7376. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
  7377. //
  7378. parse: function parse(str, callback, additionalData) {
  7379. var root;
  7380. var error = null;
  7381. var globalVars;
  7382. var modifyVars;
  7383. var ignored;
  7384. var preText = '';
  7385. globalVars = additionalData && additionalData.globalVars ? `${Parser.serializeVars(additionalData.globalVars)}\n` : '';
  7386. modifyVars = additionalData && additionalData.modifyVars ? `\n${Parser.serializeVars(additionalData.modifyVars)}` : '';
  7387. if (context.pluginManager) {
  7388. var preProcessors = context.pluginManager.getPreProcessors();
  7389. for (var i = 0; i < preProcessors.length; i++) {
  7390. str = preProcessors[i].process(str, {
  7391. context,
  7392. imports,
  7393. fileInfo
  7394. });
  7395. }
  7396. }
  7397. if (globalVars || additionalData && additionalData.banner) {
  7398. preText = (additionalData && additionalData.banner ? additionalData.banner : '') + globalVars;
  7399. ignored = imports.contentsIgnoredChars;
  7400. ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
  7401. ignored[fileInfo.filename] += preText.length;
  7402. }
  7403. str = str.replace(/\r\n?/g, '\n'); // Remove potential UTF Byte Order Mark
  7404. str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
  7405. imports.contents[fileInfo.filename] = str; // Start with the primary rule.
  7406. // The whole syntax tree is held under a Ruleset node,
  7407. // with the `root` property set to true, so no `{}` are
  7408. // output. The callback is called when the input is parsed.
  7409. try {
  7410. parserInput.start(str, context.chunkInput, function fail(msg, index) {
  7411. throw new LessError({
  7412. index,
  7413. type: 'Parse',
  7414. message: msg,
  7415. filename: fileInfo.filename
  7416. }, imports);
  7417. });
  7418. tree.Node.prototype.parse = this;
  7419. root = new tree.Ruleset(null, this.parsers.primary());
  7420. tree.Node.prototype.rootNode = root;
  7421. root.root = true;
  7422. root.firstRoot = true;
  7423. root.functionRegistry = functionRegistry.inherit();
  7424. } catch (e) {
  7425. return callback(new LessError(e, imports, fileInfo.filename));
  7426. } // If `i` is smaller than the `input.length - 1`,
  7427. // it means the parser wasn't able to parse the whole
  7428. // string, so we've got a parsing error.
  7429. //
  7430. // We try to extract a \n delimited string,
  7431. // showing the line where the parse error occurred.
  7432. // We split it up into two parts (the part which parsed,
  7433. // and the part which didn't), so we can color them differently.
  7434. var endInfo = parserInput.end();
  7435. if (!endInfo.isFinished) {
  7436. var message = endInfo.furthestPossibleErrorMessage;
  7437. if (!message) {
  7438. message = 'Unrecognised input';
  7439. if (endInfo.furthestChar === '}') {
  7440. message += '. Possibly missing opening \'{\'';
  7441. } else if (endInfo.furthestChar === ')') {
  7442. message += '. Possibly missing opening \'(\'';
  7443. } else if (endInfo.furthestReachedEnd) {
  7444. message += '. Possibly missing something';
  7445. }
  7446. }
  7447. error = new LessError({
  7448. type: 'Parse',
  7449. message,
  7450. index: endInfo.furthest,
  7451. filename: fileInfo.filename
  7452. }, imports);
  7453. }
  7454. var finish = function finish(e) {
  7455. e = error || e || imports.error;
  7456. if (e) {
  7457. if (!(e instanceof LessError)) {
  7458. e = new LessError(e, imports, fileInfo.filename);
  7459. }
  7460. return callback(e);
  7461. } else {
  7462. return callback(null, root);
  7463. }
  7464. };
  7465. if (context.processImports !== false) {
  7466. new visitors.ImportVisitor(imports, finish).run(root);
  7467. } else {
  7468. return finish();
  7469. }
  7470. },
  7471. //
  7472. // Here in, the parsing rules/functions
  7473. //
  7474. // The basic structure of the syntax tree generated is as follows:
  7475. //
  7476. // Ruleset -> Declaration -> Value -> Expression -> Entity
  7477. //
  7478. // Here's some Less code:
  7479. //
  7480. // .class {
  7481. // color: #fff;
  7482. // border: 1px solid #000;
  7483. // width: @w + 4px;
  7484. // > .child {...}
  7485. // }
  7486. //
  7487. // And here's what the parse tree might look like:
  7488. //
  7489. // Ruleset (Selector '.class', [
  7490. // Declaration ("color", Value ([Expression [Color #fff]]))
  7491. // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
  7492. // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
  7493. // Ruleset (Selector [Element '>', '.child'], [...])
  7494. // ])
  7495. //
  7496. // In general, most rules will try to parse a token with the `$re()` function, and if the return
  7497. // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
  7498. // first, before parsing, that's when we use `peek()`.
  7499. //
  7500. parsers: parsers = {
  7501. //
  7502. // The `primary` rule is the *entry* and *exit* point of the parser.
  7503. // The rules here can appear at any level of the parse tree.
  7504. //
  7505. // The recursive nature of the grammar is an interplay between the `block`
  7506. // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
  7507. // as represented by this simplified grammar:
  7508. //
  7509. // primary → (ruleset | declaration)+
  7510. // ruleset → selector+ block
  7511. // block → '{' primary '}'
  7512. //
  7513. // Only at one point is the primary rule not called from the
  7514. // block rule: at the root level.
  7515. //
  7516. primary: function primary() {
  7517. var mixin = this.mixin;
  7518. var root = [];
  7519. var node;
  7520. while (true) {
  7521. while (true) {
  7522. node = this.comment();
  7523. if (!node) {
  7524. break;
  7525. }
  7526. root.push(node);
  7527. } // always process comments before deciding if finished
  7528. if (parserInput.finished) {
  7529. break;
  7530. }
  7531. if (parserInput.peek('}')) {
  7532. break;
  7533. }
  7534. node = this.extendRule();
  7535. if (node) {
  7536. root = root.concat(node);
  7537. continue;
  7538. }
  7539. node = mixin.definition() || this.declaration() || this.ruleset() || mixin.call(false, false) || this.variableCall() || this.entities.call() || this.atrule();
  7540. if (node) {
  7541. root.push(node);
  7542. } else {
  7543. var foundSemiColon = false;
  7544. while (parserInput.$char(';')) {
  7545. foundSemiColon = true;
  7546. }
  7547. if (!foundSemiColon) {
  7548. break;
  7549. }
  7550. }
  7551. }
  7552. return root;
  7553. },
  7554. // comments are collected by the main parsing mechanism and then assigned to nodes
  7555. // where the current structure allows it
  7556. comment: function comment() {
  7557. if (parserInput.commentStore.length) {
  7558. var comment = parserInput.commentStore.shift();
  7559. return new tree.Comment(comment.text, comment.isLineComment, comment.index, fileInfo);
  7560. }
  7561. },
  7562. //
  7563. // Entities are tokens which can be found inside an Expression
  7564. //
  7565. entities: {
  7566. mixinLookup: function mixinLookup() {
  7567. return parsers.mixin.call(true, true);
  7568. },
  7569. //
  7570. // A string, which supports escaping " and '
  7571. //
  7572. // "milky way" 'he\'s the one!'
  7573. //
  7574. quoted: function quoted(forceEscaped) {
  7575. var str;
  7576. var index = parserInput.i;
  7577. var isEscaped = false;
  7578. parserInput.save();
  7579. if (parserInput.$char('~')) {
  7580. isEscaped = true;
  7581. } else if (forceEscaped) {
  7582. parserInput.restore();
  7583. return;
  7584. }
  7585. str = parserInput.$quoted();
  7586. if (!str) {
  7587. parserInput.restore();
  7588. return;
  7589. }
  7590. parserInput.forget();
  7591. return new tree.Quoted(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
  7592. },
  7593. //
  7594. // A catch-all word, such as:
  7595. //
  7596. // black border-collapse
  7597. //
  7598. keyword: function keyword() {
  7599. var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
  7600. if (k) {
  7601. return tree.Color.fromKeyword(k) || new tree.Keyword(k);
  7602. }
  7603. },
  7604. //
  7605. // A function call
  7606. //
  7607. // rgb(255, 0, 255)
  7608. //
  7609. // The arguments are parsed with the `entities.arguments` parser.
  7610. //
  7611. call: function call() {
  7612. var name;
  7613. var args;
  7614. var func;
  7615. var index = parserInput.i; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  7616. if (parserInput.peek(/^url\(/i)) {
  7617. return;
  7618. }
  7619. parserInput.save();
  7620. name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/);
  7621. if (!name) {
  7622. parserInput.forget();
  7623. return;
  7624. }
  7625. name = name[1];
  7626. func = this.customFuncCall(name);
  7627. if (func) {
  7628. args = func.parse();
  7629. if (args && func.stop) {
  7630. parserInput.forget();
  7631. return args;
  7632. }
  7633. }
  7634. args = this.arguments(args);
  7635. if (!parserInput.$char(')')) {
  7636. parserInput.restore('Could not parse call arguments or missing \')\'');
  7637. return;
  7638. }
  7639. parserInput.forget();
  7640. return new tree.Call(name, args, index, fileInfo);
  7641. },
  7642. //
  7643. // Parsing rules for functions with non-standard args, e.g.:
  7644. //
  7645. // boolean(not(2 > 1))
  7646. //
  7647. // This is a quick prototype, to be modified/improved when
  7648. // more custom-parsed funcs come (e.g. `selector(...)`)
  7649. //
  7650. customFuncCall: function customFuncCall(name) {
  7651. /* Ideally the table is to be moved out of here for faster perf.,
  7652. but it's quite tricky since it relies on all these `parsers`
  7653. and `expect` available only here */
  7654. return {
  7655. alpha: f(parsers.ieAlpha, true),
  7656. boolean: f(condition),
  7657. 'if': f(condition)
  7658. }[name.toLowerCase()];
  7659. function f(parse, stop) {
  7660. return {
  7661. parse,
  7662. // parsing function
  7663. stop // when true - stop after parse() and return its result,
  7664. // otherwise continue for plain args
  7665. };
  7666. }
  7667. function condition() {
  7668. return [expect(parsers.condition, 'expected condition')];
  7669. }
  7670. },
  7671. arguments: function _arguments(prevArgs) {
  7672. var argsComma = prevArgs || [];
  7673. var argsSemiColon = [];
  7674. var isSemiColonSeparated;
  7675. var value;
  7676. parserInput.save();
  7677. while (true) {
  7678. if (prevArgs) {
  7679. prevArgs = false;
  7680. } else {
  7681. value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
  7682. if (!value) {
  7683. break;
  7684. }
  7685. if (value.value && value.value.length == 1) {
  7686. value = value.value[0];
  7687. }
  7688. argsComma.push(value);
  7689. }
  7690. if (parserInput.$char(',')) {
  7691. continue;
  7692. }
  7693. if (parserInput.$char(';') || isSemiColonSeparated) {
  7694. isSemiColonSeparated = true;
  7695. value = argsComma.length < 1 ? argsComma[0] : new tree.Value(argsComma);
  7696. argsSemiColon.push(value);
  7697. argsComma = [];
  7698. }
  7699. }
  7700. parserInput.forget();
  7701. return isSemiColonSeparated ? argsSemiColon : argsComma;
  7702. },
  7703. literal: function literal() {
  7704. return this.dimension() || this.color() || this.quoted() || this.unicodeDescriptor();
  7705. },
  7706. // Assignments are argument entities for calls.
  7707. // They are present in ie filter properties as shown below.
  7708. //
  7709. // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
  7710. //
  7711. assignment: function assignment() {
  7712. var key;
  7713. var value;
  7714. parserInput.save();
  7715. key = parserInput.$re(/^\w+(?=\s?=)/i);
  7716. if (!key) {
  7717. parserInput.restore();
  7718. return;
  7719. }
  7720. if (!parserInput.$char('=')) {
  7721. parserInput.restore();
  7722. return;
  7723. }
  7724. value = parsers.entity();
  7725. if (value) {
  7726. parserInput.forget();
  7727. return new tree.Assignment(key, value);
  7728. } else {
  7729. parserInput.restore();
  7730. }
  7731. },
  7732. //
  7733. // Parse url() tokens
  7734. //
  7735. // We use a specific rule for urls, because they don't really behave like
  7736. // standard function calls. The difference is that the argument doesn't have
  7737. // to be enclosed within a string, so it can't be parsed as an Expression.
  7738. //
  7739. url: function url() {
  7740. var value;
  7741. var index = parserInput.i;
  7742. parserInput.autoCommentAbsorb = false;
  7743. if (!parserInput.$str('url(')) {
  7744. parserInput.autoCommentAbsorb = true;
  7745. return;
  7746. }
  7747. value = this.quoted() || this.variable() || this.property() || parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
  7748. parserInput.autoCommentAbsorb = true;
  7749. expectChar(')');
  7750. return new tree.URL(value.value != null || value instanceof tree.Variable || value instanceof tree.Property ? value : new tree.Anonymous(value, index), index, fileInfo);
  7751. },
  7752. //
  7753. // A Variable entity, such as `@fink`, in
  7754. //
  7755. // width: @fink + 2px
  7756. //
  7757. // We use a different parser for variable definitions,
  7758. // see `parsers.variable`.
  7759. //
  7760. variable: function variable() {
  7761. var ch;
  7762. var name;
  7763. var index = parserInput.i;
  7764. parserInput.save();
  7765. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
  7766. ch = parserInput.currentChar();
  7767. if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
  7768. // this may be a VariableCall lookup
  7769. var result = parsers.variableCall(name);
  7770. if (result) {
  7771. parserInput.forget();
  7772. return result;
  7773. }
  7774. }
  7775. parserInput.forget();
  7776. return new tree.Variable(name, index, fileInfo);
  7777. }
  7778. parserInput.restore();
  7779. },
  7780. // A variable entity using the protective {} e.g. @{var}
  7781. variableCurly: function variableCurly() {
  7782. var curly;
  7783. var index = parserInput.i;
  7784. if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
  7785. return new tree.Variable(`@${curly[1]}`, index, fileInfo);
  7786. }
  7787. },
  7788. //
  7789. // A Property accessor, such as `$color`, in
  7790. //
  7791. // background-color: $color
  7792. //
  7793. property: function property() {
  7794. var name;
  7795. var index = parserInput.i;
  7796. if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
  7797. return new tree.Property(name, index, fileInfo);
  7798. }
  7799. },
  7800. // A property entity useing the protective {} e.g. ${prop}
  7801. propertyCurly: function propertyCurly() {
  7802. var curly;
  7803. var index = parserInput.i;
  7804. if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
  7805. return new tree.Property(`$${curly[1]}`, index, fileInfo);
  7806. }
  7807. },
  7808. //
  7809. // A Hexadecimal color
  7810. //
  7811. // #4F3C2F
  7812. //
  7813. // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
  7814. //
  7815. color: function color() {
  7816. var rgb;
  7817. parserInput.save();
  7818. if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/))) {
  7819. if (!rgb[2]) {
  7820. parserInput.forget();
  7821. return new tree.Color(rgb[1], undefined, rgb[0]);
  7822. }
  7823. }
  7824. parserInput.restore();
  7825. },
  7826. colorKeyword: function colorKeyword() {
  7827. parserInput.save();
  7828. var autoCommentAbsorb = parserInput.autoCommentAbsorb;
  7829. parserInput.autoCommentAbsorb = false;
  7830. var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
  7831. parserInput.autoCommentAbsorb = autoCommentAbsorb;
  7832. if (!k) {
  7833. parserInput.forget();
  7834. return;
  7835. }
  7836. parserInput.restore();
  7837. var color = tree.Color.fromKeyword(k);
  7838. if (color) {
  7839. parserInput.$str(k);
  7840. return color;
  7841. }
  7842. },
  7843. //
  7844. // A Dimension, that is, a number and a unit
  7845. //
  7846. // 0.5em 95%
  7847. //
  7848. dimension: function dimension() {
  7849. if (parserInput.peekNotNumeric()) {
  7850. return;
  7851. }
  7852. var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
  7853. if (value) {
  7854. return new tree.Dimension(value[1], value[2]);
  7855. }
  7856. },
  7857. //
  7858. // A unicode descriptor, as is used in unicode-range
  7859. //
  7860. // U+0?? or U+00A1-00A9
  7861. //
  7862. unicodeDescriptor: function unicodeDescriptor() {
  7863. var ud;
  7864. ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
  7865. if (ud) {
  7866. return new tree.UnicodeDescriptor(ud[0]);
  7867. }
  7868. },
  7869. //
  7870. // JavaScript code to be evaluated
  7871. //
  7872. // `window.location.href`
  7873. //
  7874. javascript: function javascript() {
  7875. var js;
  7876. var index = parserInput.i;
  7877. parserInput.save();
  7878. var escape = parserInput.$char('~');
  7879. var jsQuote = parserInput.$char('`');
  7880. if (!jsQuote) {
  7881. parserInput.restore();
  7882. return;
  7883. }
  7884. js = parserInput.$re(/^[^`]*`/);
  7885. if (js) {
  7886. parserInput.forget();
  7887. return new tree.JavaScript(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
  7888. }
  7889. parserInput.restore('invalid javascript definition');
  7890. }
  7891. },
  7892. //
  7893. // The variable part of a variable definition. Used in the `rule` parser
  7894. //
  7895. // @fink:
  7896. //
  7897. variable: function variable() {
  7898. var name;
  7899. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
  7900. return name[1];
  7901. }
  7902. },
  7903. //
  7904. // Call a variable value to retrieve a detached ruleset
  7905. // or a value from a detached ruleset's rules.
  7906. //
  7907. // @fink();
  7908. // @fink;
  7909. // color: @fink[@color];
  7910. //
  7911. variableCall: function variableCall(parsedName) {
  7912. var lookups;
  7913. var important;
  7914. var i = parserInput.i;
  7915. var inValue = !!parsedName;
  7916. var name = parsedName;
  7917. parserInput.save();
  7918. if (name || parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/))) {
  7919. lookups = this.mixin.ruleLookups();
  7920. if (!lookups && (inValue && parserInput.$str('()') !== '()' || name[2] !== '()')) {
  7921. parserInput.restore('Missing \'[...]\' lookup in variable call');
  7922. return;
  7923. }
  7924. if (!inValue) {
  7925. name = name[1];
  7926. }
  7927. if (lookups && parsers.important()) {
  7928. important = true;
  7929. }
  7930. var call = new tree.VariableCall(name, i, fileInfo);
  7931. if (!inValue && parsers.end()) {
  7932. parserInput.forget();
  7933. return call;
  7934. } else {
  7935. parserInput.forget();
  7936. return new tree.NamespaceValue(call, lookups, important, i, fileInfo);
  7937. }
  7938. }
  7939. parserInput.restore();
  7940. },
  7941. //
  7942. // extend syntax - used to extend selectors
  7943. //
  7944. extend: function extend(isRule) {
  7945. var elements;
  7946. var e;
  7947. var index = parserInput.i;
  7948. var option;
  7949. var extendList;
  7950. var extend;
  7951. if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
  7952. return;
  7953. }
  7954. do {
  7955. option = null;
  7956. elements = null;
  7957. while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
  7958. e = this.element();
  7959. if (!e) {
  7960. break;
  7961. }
  7962. if (elements) {
  7963. elements.push(e);
  7964. } else {
  7965. elements = [e];
  7966. }
  7967. }
  7968. option = option && option[1];
  7969. if (!elements) {
  7970. error('Missing target selector for :extend().');
  7971. }
  7972. extend = new tree.Extend(new tree.Selector(elements), option, index, fileInfo);
  7973. if (extendList) {
  7974. extendList.push(extend);
  7975. } else {
  7976. extendList = [extend];
  7977. }
  7978. } while (parserInput.$char(','));
  7979. expect(/^\)/);
  7980. if (isRule) {
  7981. expect(/^;/);
  7982. }
  7983. return extendList;
  7984. },
  7985. //
  7986. // extendRule - used in a rule to extend all the parent selectors
  7987. //
  7988. extendRule: function extendRule() {
  7989. return this.extend(true);
  7990. },
  7991. //
  7992. // Mixins
  7993. //
  7994. mixin: {
  7995. //
  7996. // A Mixin call, with an optional argument list
  7997. //
  7998. // #mixins > .square(#fff);
  7999. // #mixins.square(#fff);
  8000. // .rounded(4px, black);
  8001. // .button;
  8002. //
  8003. // We can lookup / return a value using the lookup syntax:
  8004. //
  8005. // color: #mixin.square(#fff)[@color];
  8006. //
  8007. // The `while` loop is there because mixins can be
  8008. // namespaced, but we only support the child and descendant
  8009. // selector for now.
  8010. //
  8011. call: function call(inValue, getLookup) {
  8012. var s = parserInput.currentChar();
  8013. var important = false;
  8014. var lookups;
  8015. var index = parserInput.i;
  8016. var elements;
  8017. var args;
  8018. var hasParens;
  8019. if (s !== '.' && s !== '#') {
  8020. return;
  8021. }
  8022. parserInput.save(); // stop us absorbing part of an invalid selector
  8023. elements = this.elements();
  8024. if (elements) {
  8025. if (parserInput.$char('(')) {
  8026. args = this.args(true).args;
  8027. expectChar(')');
  8028. hasParens = true;
  8029. }
  8030. if (getLookup !== false) {
  8031. lookups = this.ruleLookups();
  8032. }
  8033. if (getLookup === true && !lookups) {
  8034. parserInput.restore();
  8035. return;
  8036. }
  8037. if (inValue && !lookups && !hasParens) {
  8038. // This isn't a valid in-value mixin call
  8039. parserInput.restore();
  8040. return;
  8041. }
  8042. if (!inValue && parsers.important()) {
  8043. important = true;
  8044. }
  8045. if (inValue || parsers.end()) {
  8046. parserInput.forget();
  8047. var mixin = new tree.mixin.Call(elements, args, index, fileInfo, !lookups && important);
  8048. if (lookups) {
  8049. return new tree.NamespaceValue(mixin, lookups, important);
  8050. } else {
  8051. return mixin;
  8052. }
  8053. }
  8054. }
  8055. parserInput.restore();
  8056. },
  8057. /**
  8058. * Matching elements for mixins
  8059. * (Start with . or # and can have > )
  8060. */
  8061. elements: function elements() {
  8062. var elements;
  8063. var e;
  8064. var c;
  8065. var elem;
  8066. var elemIndex;
  8067. var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
  8068. while (true) {
  8069. elemIndex = parserInput.i;
  8070. e = parserInput.$re(re);
  8071. if (!e) {
  8072. break;
  8073. }
  8074. elem = new tree.Element(c, e, false, elemIndex, fileInfo);
  8075. if (elements) {
  8076. elements.push(elem);
  8077. } else {
  8078. elements = [elem];
  8079. }
  8080. c = parserInput.$char('>');
  8081. }
  8082. return elements;
  8083. },
  8084. args: function args(isCall) {
  8085. var entities = parsers.entities;
  8086. var returner = {
  8087. args: null,
  8088. variadic: false
  8089. };
  8090. var expressions = [];
  8091. var argsSemiColon = [];
  8092. var argsComma = [];
  8093. var isSemiColonSeparated;
  8094. var expressionContainsNamed;
  8095. var name;
  8096. var nameLoop;
  8097. var value;
  8098. var arg;
  8099. var expand;
  8100. var hasSep = true;
  8101. parserInput.save();
  8102. while (true) {
  8103. if (isCall) {
  8104. arg = parsers.detachedRuleset() || parsers.expression();
  8105. } else {
  8106. parserInput.commentStore.length = 0;
  8107. if (parserInput.$str('...')) {
  8108. returner.variadic = true;
  8109. if (parserInput.$char(';') && !isSemiColonSeparated) {
  8110. isSemiColonSeparated = true;
  8111. }
  8112. (isSemiColonSeparated ? argsSemiColon : argsComma).push({
  8113. variadic: true
  8114. });
  8115. break;
  8116. }
  8117. arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
  8118. }
  8119. if (!arg || !hasSep) {
  8120. break;
  8121. }
  8122. nameLoop = null;
  8123. if (arg.throwAwayComments) {
  8124. arg.throwAwayComments();
  8125. }
  8126. value = arg;
  8127. var val = null;
  8128. if (isCall) {
  8129. // Variable
  8130. if (arg.value && arg.value.length == 1) {
  8131. val = arg.value[0];
  8132. }
  8133. } else {
  8134. val = arg;
  8135. }
  8136. if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
  8137. if (parserInput.$char(':')) {
  8138. if (expressions.length > 0) {
  8139. if (isSemiColonSeparated) {
  8140. error('Cannot mix ; and , as delimiter types');
  8141. }
  8142. expressionContainsNamed = true;
  8143. }
  8144. value = parsers.detachedRuleset() || parsers.expression();
  8145. if (!value) {
  8146. if (isCall) {
  8147. error('could not understand value for named argument');
  8148. } else {
  8149. parserInput.restore();
  8150. returner.args = [];
  8151. return returner;
  8152. }
  8153. }
  8154. nameLoop = name = val.name;
  8155. } else if (parserInput.$str('...')) {
  8156. if (!isCall) {
  8157. returner.variadic = true;
  8158. if (parserInput.$char(';') && !isSemiColonSeparated) {
  8159. isSemiColonSeparated = true;
  8160. }
  8161. (isSemiColonSeparated ? argsSemiColon : argsComma).push({
  8162. name: arg.name,
  8163. variadic: true
  8164. });
  8165. break;
  8166. } else {
  8167. expand = true;
  8168. }
  8169. } else if (!isCall) {
  8170. name = nameLoop = val.name;
  8171. value = null;
  8172. }
  8173. }
  8174. if (value) {
  8175. expressions.push(value);
  8176. }
  8177. argsComma.push({
  8178. name: nameLoop,
  8179. value,
  8180. expand
  8181. });
  8182. if (parserInput.$char(',')) {
  8183. hasSep = true;
  8184. continue;
  8185. }
  8186. hasSep = parserInput.$char(';') === ';';
  8187. if (hasSep || isSemiColonSeparated) {
  8188. if (expressionContainsNamed) {
  8189. error('Cannot mix ; and , as delimiter types');
  8190. }
  8191. isSemiColonSeparated = true;
  8192. if (expressions.length > 1) {
  8193. value = new tree.Value(expressions);
  8194. }
  8195. argsSemiColon.push({
  8196. name,
  8197. value,
  8198. expand
  8199. });
  8200. name = null;
  8201. expressions = [];
  8202. expressionContainsNamed = false;
  8203. }
  8204. }
  8205. parserInput.forget();
  8206. returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
  8207. return returner;
  8208. },
  8209. //
  8210. // A Mixin definition, with a list of parameters
  8211. //
  8212. // .rounded (@radius: 2px, @color) {
  8213. // ...
  8214. // }
  8215. //
  8216. // Until we have a finer grained state-machine, we have to
  8217. // do a look-ahead, to make sure we don't have a mixin call.
  8218. // See the `rule` function for more information.
  8219. //
  8220. // We start by matching `.rounded (`, and then proceed on to
  8221. // the argument list, which has optional default values.
  8222. // We store the parameters in `params`, with a `value` key,
  8223. // if there is a value, such as in the case of `@radius`.
  8224. //
  8225. // Once we've got our params list, and a closing `)`, we parse
  8226. // the `{...}` block.
  8227. //
  8228. definition: function definition() {
  8229. var name;
  8230. var params = [];
  8231. var match;
  8232. var ruleset;
  8233. var cond;
  8234. var variadic = false;
  8235. if (parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#' || parserInput.peek(/^[^{]*\}/)) {
  8236. return;
  8237. }
  8238. parserInput.save();
  8239. match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
  8240. if (match) {
  8241. name = match[1];
  8242. var argInfo = this.args(false);
  8243. params = argInfo.args;
  8244. variadic = argInfo.variadic; // .mixincall("@{a}");
  8245. // looks a bit like a mixin definition..
  8246. // also
  8247. // .mixincall(@a: {rule: set;});
  8248. // so we have to be nice and restore
  8249. if (!parserInput.$char(')')) {
  8250. parserInput.restore('Missing closing \')\'');
  8251. return;
  8252. }
  8253. parserInput.commentStore.length = 0;
  8254. if (parserInput.$str('when')) {
  8255. // Guard
  8256. cond = expect(parsers.conditions, 'expected condition');
  8257. }
  8258. ruleset = parsers.block();
  8259. if (ruleset) {
  8260. parserInput.forget();
  8261. return new tree.mixin.Definition(name, params, ruleset, cond, variadic);
  8262. } else {
  8263. parserInput.restore();
  8264. }
  8265. } else {
  8266. parserInput.forget();
  8267. }
  8268. },
  8269. ruleLookups: function ruleLookups() {
  8270. var rule;
  8271. var lookups = [];
  8272. if (parserInput.currentChar() !== '[') {
  8273. return;
  8274. }
  8275. while (true) {
  8276. parserInput.save();
  8277. rule = this.lookupValue();
  8278. if (!rule && rule !== '') {
  8279. parserInput.restore();
  8280. break;
  8281. }
  8282. lookups.push(rule);
  8283. parserInput.forget();
  8284. }
  8285. if (lookups.length > 0) {
  8286. return lookups;
  8287. }
  8288. },
  8289. lookupValue: function lookupValue() {
  8290. parserInput.save();
  8291. if (!parserInput.$char('[')) {
  8292. parserInput.restore();
  8293. return;
  8294. }
  8295. var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
  8296. if (!parserInput.$char(']')) {
  8297. parserInput.restore();
  8298. return;
  8299. }
  8300. if (name || name === '') {
  8301. parserInput.forget();
  8302. return name;
  8303. }
  8304. parserInput.restore();
  8305. }
  8306. },
  8307. //
  8308. // Entities are the smallest recognized token,
  8309. // and can be found inside a rule's value.
  8310. //
  8311. entity: function entity() {
  8312. var entities = this.entities;
  8313. return this.comment() || entities.literal() || entities.variable() || entities.url() || entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) || entities.javascript();
  8314. },
  8315. //
  8316. // A Declaration terminator. Note that we use `peek()` to check for '}',
  8317. // because the `block` rule will be expecting it, but we still need to make sure
  8318. // it's there, if ';' was omitted.
  8319. //
  8320. end: function end() {
  8321. return parserInput.$char(';') || parserInput.peek('}');
  8322. },
  8323. //
  8324. // IE's alpha function
  8325. //
  8326. // alpha(opacity=88)
  8327. //
  8328. ieAlpha: function ieAlpha() {
  8329. var value; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  8330. if (!parserInput.$re(/^opacity=/i)) {
  8331. return;
  8332. }
  8333. value = parserInput.$re(/^\d+/);
  8334. if (!value) {
  8335. value = expect(parsers.entities.variable, 'Could not parse alpha');
  8336. value = `@{${value.name.slice(1)}}`;
  8337. }
  8338. expectChar(')');
  8339. return new tree.Quoted('', `alpha(opacity=${value})`);
  8340. },
  8341. //
  8342. // A Selector Element
  8343. //
  8344. // div
  8345. // + h1
  8346. // #socks
  8347. // input[type="text"]
  8348. //
  8349. // Elements are the building blocks for Selectors,
  8350. // they are made out of a `Combinator` (see combinator rule),
  8351. // and an element name, such as a tag a class, or `*`.
  8352. //
  8353. element: function element() {
  8354. var e;
  8355. var c;
  8356. var v;
  8357. var index = parserInput.i;
  8358. c = this.combinator();
  8359. e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) || parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || parserInput.$char('*') || parserInput.$char('&') || this.attribute() || parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) || this.entities.variableCurly();
  8360. if (!e) {
  8361. parserInput.save();
  8362. if (parserInput.$char('(')) {
  8363. if ((v = this.selector(false)) && parserInput.$char(')')) {
  8364. e = new tree.Paren(v);
  8365. parserInput.forget();
  8366. } else {
  8367. parserInput.restore('Missing closing \')\'');
  8368. }
  8369. } else {
  8370. parserInput.forget();
  8371. }
  8372. }
  8373. if (e) {
  8374. return new tree.Element(c, e, e instanceof tree.Variable, index, fileInfo);
  8375. }
  8376. },
  8377. //
  8378. // Combinators combine elements together, in a Selector.
  8379. //
  8380. // Because our parser isn't white-space sensitive, special care
  8381. // has to be taken, when parsing the descendant combinator, ` `,
  8382. // as it's an empty space. We have to check the previous character
  8383. // in the input, to see if it's a ` ` character. More info on how
  8384. // we deal with this in *combinator.js*.
  8385. //
  8386. combinator: function combinator() {
  8387. var c = parserInput.currentChar();
  8388. if (c === '/') {
  8389. parserInput.save();
  8390. var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
  8391. if (slashedCombinator) {
  8392. parserInput.forget();
  8393. return new tree.Combinator(slashedCombinator);
  8394. }
  8395. parserInput.restore();
  8396. }
  8397. if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
  8398. parserInput.i++;
  8399. if (c === '^' && parserInput.currentChar() === '^') {
  8400. c = '^^';
  8401. parserInput.i++;
  8402. }
  8403. while (parserInput.isWhitespace()) {
  8404. parserInput.i++;
  8405. }
  8406. return new tree.Combinator(c);
  8407. } else if (parserInput.isWhitespace(-1)) {
  8408. return new tree.Combinator(' ');
  8409. } else {
  8410. return new tree.Combinator(null);
  8411. }
  8412. },
  8413. //
  8414. // A CSS Selector
  8415. // with less extensions e.g. the ability to extend and guard
  8416. //
  8417. // .class > div + h1
  8418. // li a:hover
  8419. //
  8420. // Selectors are made out of one or more Elements, see above.
  8421. //
  8422. selector: function selector(isLess) {
  8423. var index = parserInput.i;
  8424. var elements;
  8425. var extendList;
  8426. var c;
  8427. var e;
  8428. var allExtends;
  8429. var when;
  8430. var condition;
  8431. isLess = isLess !== false;
  8432. while (isLess && (extendList = this.extend()) || isLess && (when = parserInput.$str('when')) || (e = this.element())) {
  8433. if (when) {
  8434. condition = expect(this.conditions, 'expected condition');
  8435. } else if (condition) {
  8436. error('CSS guard can only be used at the end of selector');
  8437. } else if (extendList) {
  8438. if (allExtends) {
  8439. allExtends = allExtends.concat(extendList);
  8440. } else {
  8441. allExtends = extendList;
  8442. }
  8443. } else {
  8444. if (allExtends) {
  8445. error('Extend can only be used at the end of selector');
  8446. }
  8447. c = parserInput.currentChar();
  8448. if (elements) {
  8449. elements.push(e);
  8450. } else {
  8451. elements = [e];
  8452. }
  8453. e = null;
  8454. }
  8455. if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
  8456. break;
  8457. }
  8458. }
  8459. if (elements) {
  8460. return new tree.Selector(elements, allExtends, condition, index, fileInfo);
  8461. }
  8462. if (allExtends) {
  8463. error('Extend must be used to extend a selector, it cannot be used on its own');
  8464. }
  8465. },
  8466. selectors: function selectors() {
  8467. var s;
  8468. var selectors;
  8469. while (true) {
  8470. s = this.selector();
  8471. if (!s) {
  8472. break;
  8473. }
  8474. if (selectors) {
  8475. selectors.push(s);
  8476. } else {
  8477. selectors = [s];
  8478. }
  8479. parserInput.commentStore.length = 0;
  8480. if (s.condition && selectors.length > 1) {
  8481. error("Guards are only currently allowed on a single selector.");
  8482. }
  8483. if (!parserInput.$char(',')) {
  8484. break;
  8485. }
  8486. if (s.condition) {
  8487. error("Guards are only currently allowed on a single selector.");
  8488. }
  8489. parserInput.commentStore.length = 0;
  8490. }
  8491. return selectors;
  8492. },
  8493. attribute: function attribute() {
  8494. if (!parserInput.$char('[')) {
  8495. return;
  8496. }
  8497. var entities = this.entities;
  8498. var key;
  8499. var val;
  8500. var op;
  8501. if (!(key = entities.variableCurly())) {
  8502. key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
  8503. }
  8504. op = parserInput.$re(/^[|~*$^]?=/);
  8505. if (op) {
  8506. val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
  8507. }
  8508. expectChar(']');
  8509. return new tree.Attribute(key, op, val);
  8510. },
  8511. //
  8512. // The `block` rule is used by `ruleset` and `mixin.definition`.
  8513. // It's a wrapper around the `primary` rule, with added `{}`.
  8514. //
  8515. block: function block() {
  8516. var content;
  8517. if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
  8518. return content;
  8519. }
  8520. },
  8521. blockRuleset: function blockRuleset() {
  8522. var block = this.block();
  8523. if (block) {
  8524. block = new tree.Ruleset(null, block);
  8525. }
  8526. return block;
  8527. },
  8528. detachedRuleset: function detachedRuleset() {
  8529. var argInfo;
  8530. var params;
  8531. var variadic;
  8532. parserInput.save();
  8533. if (parserInput.$re(/^[.#]\(/)) {
  8534. /**
  8535. * DR args currently only implemented for each() function, and not
  8536. * yet settable as `@dr: #(@arg) {}`
  8537. * This should be done when DRs are merged with mixins.
  8538. * See: https://github.com/less/less-meta/issues/16
  8539. */
  8540. argInfo = this.mixin.args(false);
  8541. params = argInfo.args;
  8542. variadic = argInfo.variadic;
  8543. if (!parserInput.$char(')')) {
  8544. parserInput.restore();
  8545. return;
  8546. }
  8547. }
  8548. var blockRuleset = this.blockRuleset();
  8549. if (blockRuleset) {
  8550. parserInput.forget();
  8551. if (params) {
  8552. return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
  8553. }
  8554. return new tree.DetachedRuleset(blockRuleset);
  8555. }
  8556. parserInput.restore();
  8557. },
  8558. //
  8559. // div, .class, body > p {...}
  8560. //
  8561. ruleset: function ruleset() {
  8562. var selectors;
  8563. var rules;
  8564. var debugInfo;
  8565. parserInput.save();
  8566. if (context.dumpLineNumbers) {
  8567. debugInfo = getDebugInfo(parserInput.i);
  8568. }
  8569. selectors = this.selectors();
  8570. if (selectors && (rules = this.block())) {
  8571. parserInput.forget();
  8572. var ruleset = new tree.Ruleset(selectors, rules, context.strictImports);
  8573. if (context.dumpLineNumbers) {
  8574. ruleset.debugInfo = debugInfo;
  8575. }
  8576. return ruleset;
  8577. } else {
  8578. parserInput.restore();
  8579. }
  8580. },
  8581. declaration: function declaration() {
  8582. var name;
  8583. var value;
  8584. var index = parserInput.i;
  8585. var hasDR;
  8586. var c = parserInput.currentChar();
  8587. var important;
  8588. var merge;
  8589. var isVariable;
  8590. if (c === '.' || c === '#' || c === '&' || c === ':') {
  8591. return;
  8592. }
  8593. parserInput.save();
  8594. name = this.variable() || this.ruleProperty();
  8595. if (name) {
  8596. isVariable = typeof name === 'string';
  8597. if (isVariable) {
  8598. value = this.detachedRuleset();
  8599. if (value) {
  8600. hasDR = true;
  8601. }
  8602. }
  8603. parserInput.commentStore.length = 0;
  8604. if (!value) {
  8605. // a name returned by this.ruleProperty() is always an array of the form:
  8606. // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
  8607. // where each item is a tree.Keyword or tree.Variable
  8608. merge = !isVariable && name.length > 1 && name.pop().value; // Custom property values get permissive parsing
  8609. if (name[0].value && name[0].value.slice(0, 2) === '--') {
  8610. value = this.permissiveValue();
  8611. } // Try to store values as anonymous
  8612. // If we need the value later we'll re-parse it in ruleset.parseValue
  8613. else {
  8614. value = this.anonymousValue();
  8615. }
  8616. if (value) {
  8617. parserInput.forget(); // anonymous values absorb the end ';' which is required for them to work
  8618. return new tree.Declaration(name, value, false, merge, index, fileInfo);
  8619. }
  8620. if (!value) {
  8621. value = this.value();
  8622. }
  8623. if (value) {
  8624. important = this.important();
  8625. } else if (isVariable) {
  8626. // As a last resort, try permissiveValue
  8627. value = this.permissiveValue();
  8628. }
  8629. }
  8630. if (value && (this.end() || hasDR)) {
  8631. parserInput.forget();
  8632. return new tree.Declaration(name, value, important, merge, index, fileInfo);
  8633. } else {
  8634. parserInput.restore();
  8635. }
  8636. } else {
  8637. parserInput.restore();
  8638. }
  8639. },
  8640. anonymousValue: function anonymousValue() {
  8641. var index = parserInput.i;
  8642. var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
  8643. if (match) {
  8644. return new tree.Anonymous(match[1], index);
  8645. }
  8646. },
  8647. /**
  8648. * Used for custom properties, at-rules, and variables (as fallback)
  8649. * Parses almost anything inside of {} [] () "" blocks
  8650. * until it reaches outer-most tokens.
  8651. *
  8652. * First, it will try to parse comments and entities to reach
  8653. * the end. This is mostly like the Expression parser except no
  8654. * math is allowed.
  8655. */
  8656. permissiveValue: function permissiveValue(untilTokens) {
  8657. var i;
  8658. var e;
  8659. var done;
  8660. var value;
  8661. var tok = untilTokens || ';';
  8662. var index = parserInput.i;
  8663. var result = [];
  8664. function testCurrentChar() {
  8665. var char = parserInput.currentChar();
  8666. if (typeof tok === 'string') {
  8667. return char === tok;
  8668. } else {
  8669. return tok.test(char);
  8670. }
  8671. }
  8672. if (testCurrentChar()) {
  8673. return;
  8674. }
  8675. value = [];
  8676. do {
  8677. e = this.comment();
  8678. if (e) {
  8679. value.push(e);
  8680. continue;
  8681. }
  8682. e = this.entity();
  8683. if (e) {
  8684. value.push(e);
  8685. }
  8686. } while (e);
  8687. done = testCurrentChar();
  8688. if (value.length > 0) {
  8689. value = new tree.Expression(value);
  8690. if (done) {
  8691. return value;
  8692. } else {
  8693. result.push(value);
  8694. } // Preserve space before $parseUntil as it will not
  8695. if (parserInput.prevChar() === ' ') {
  8696. result.push(new tree.Anonymous(' ', index));
  8697. }
  8698. }
  8699. parserInput.save();
  8700. value = parserInput.$parseUntil(tok);
  8701. if (value) {
  8702. if (typeof value === 'string') {
  8703. error(`Expected '${value}'`, 'Parse');
  8704. }
  8705. if (value.length === 1 && value[0] === ' ') {
  8706. parserInput.forget();
  8707. return new tree.Anonymous('', index);
  8708. }
  8709. var item;
  8710. for (i = 0; i < value.length; i++) {
  8711. item = value[i];
  8712. if (Array.isArray(item)) {
  8713. // Treat actual quotes as normal quoted values
  8714. result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
  8715. } else {
  8716. if (i === value.length - 1) {
  8717. item = item.trim();
  8718. } // Treat like quoted values, but replace vars like unquoted expressions
  8719. var quote = new tree.Quoted('\'', item, true, index, fileInfo);
  8720. quote.variableRegex = /@([\w-]+)/g;
  8721. quote.propRegex = /\$([\w-]+)/g;
  8722. result.push(quote);
  8723. }
  8724. }
  8725. parserInput.forget();
  8726. return new tree.Expression(result, true);
  8727. }
  8728. parserInput.restore();
  8729. },
  8730. //
  8731. // An @import atrule
  8732. //
  8733. // @import "lib";
  8734. //
  8735. // Depending on our environment, importing is done differently:
  8736. // In the browser, it's an XHR request, in Node, it would be a
  8737. // file-system operation. The function used for importing is
  8738. // stored in `import`, which we pass to the Import constructor.
  8739. //
  8740. 'import': function _import() {
  8741. var path;
  8742. var features;
  8743. var index = parserInput.i;
  8744. var dir = parserInput.$re(/^@import?\s+/);
  8745. if (dir) {
  8746. var options = (dir ? this.importOptions() : null) || {};
  8747. if (path = this.entities.quoted() || this.entities.url()) {
  8748. features = this.mediaFeatures();
  8749. if (!parserInput.$char(';')) {
  8750. parserInput.i = index;
  8751. error('missing semi-colon or unrecognised media features on import');
  8752. }
  8753. features = features && new tree.Value(features);
  8754. return new tree.Import(path, features, options, index, fileInfo);
  8755. } else {
  8756. parserInput.i = index;
  8757. error('malformed import statement');
  8758. }
  8759. }
  8760. },
  8761. importOptions: function importOptions() {
  8762. var o;
  8763. var options = {};
  8764. var optionName;
  8765. var value; // list of options, surrounded by parens
  8766. if (!parserInput.$char('(')) {
  8767. return null;
  8768. }
  8769. do {
  8770. o = this.importOption();
  8771. if (o) {
  8772. optionName = o;
  8773. value = true;
  8774. switch (optionName) {
  8775. case 'css':
  8776. optionName = 'less';
  8777. value = false;
  8778. break;
  8779. case 'once':
  8780. optionName = 'multiple';
  8781. value = false;
  8782. break;
  8783. }
  8784. options[optionName] = value;
  8785. if (!parserInput.$char(',')) {
  8786. break;
  8787. }
  8788. }
  8789. } while (o);
  8790. expectChar(')');
  8791. return options;
  8792. },
  8793. importOption: function importOption() {
  8794. var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
  8795. if (opt) {
  8796. return opt[1];
  8797. }
  8798. },
  8799. mediaFeature: function mediaFeature() {
  8800. var entities = this.entities;
  8801. var nodes = [];
  8802. var e;
  8803. var p;
  8804. parserInput.save();
  8805. do {
  8806. e = entities.keyword() || entities.variable() || entities.mixinLookup();
  8807. if (e) {
  8808. nodes.push(e);
  8809. } else if (parserInput.$char('(')) {
  8810. p = this.property();
  8811. e = this.value();
  8812. if (parserInput.$char(')')) {
  8813. if (p && e) {
  8814. nodes.push(new tree.Paren(new tree.Declaration(p, e, null, null, parserInput.i, fileInfo, true)));
  8815. } else if (e) {
  8816. nodes.push(new tree.Paren(e));
  8817. } else {
  8818. error('badly formed media feature definition');
  8819. }
  8820. } else {
  8821. error('Missing closing \')\'', 'Parse');
  8822. }
  8823. }
  8824. } while (e);
  8825. parserInput.forget();
  8826. if (nodes.length > 0) {
  8827. return new tree.Expression(nodes);
  8828. }
  8829. },
  8830. mediaFeatures: function mediaFeatures() {
  8831. var entities = this.entities;
  8832. var features = [];
  8833. var e;
  8834. do {
  8835. e = this.mediaFeature();
  8836. if (e) {
  8837. features.push(e);
  8838. if (!parserInput.$char(',')) {
  8839. break;
  8840. }
  8841. } else {
  8842. e = entities.variable() || entities.mixinLookup();
  8843. if (e) {
  8844. features.push(e);
  8845. if (!parserInput.$char(',')) {
  8846. break;
  8847. }
  8848. }
  8849. }
  8850. } while (e);
  8851. return features.length > 0 ? features : null;
  8852. },
  8853. media: function media() {
  8854. var features;
  8855. var rules;
  8856. var media;
  8857. var debugInfo;
  8858. var index = parserInput.i;
  8859. if (context.dumpLineNumbers) {
  8860. debugInfo = getDebugInfo(index);
  8861. }
  8862. parserInput.save();
  8863. if (parserInput.$str('@media')) {
  8864. features = this.mediaFeatures();
  8865. rules = this.block();
  8866. if (!rules) {
  8867. error('media definitions require block statements after any features');
  8868. }
  8869. parserInput.forget();
  8870. media = new tree.Media(rules, features, index, fileInfo);
  8871. if (context.dumpLineNumbers) {
  8872. media.debugInfo = debugInfo;
  8873. }
  8874. return media;
  8875. }
  8876. parserInput.restore();
  8877. },
  8878. //
  8879. // A @plugin directive, used to import plugins dynamically.
  8880. //
  8881. // @plugin (args) "lib";
  8882. //
  8883. plugin: function plugin() {
  8884. var path;
  8885. var args;
  8886. var options;
  8887. var index = parserInput.i;
  8888. var dir = parserInput.$re(/^@plugin?\s+/);
  8889. if (dir) {
  8890. args = this.pluginArgs();
  8891. if (args) {
  8892. options = {
  8893. pluginArgs: args,
  8894. isPlugin: true
  8895. };
  8896. } else {
  8897. options = {
  8898. isPlugin: true
  8899. };
  8900. }
  8901. if (path = this.entities.quoted() || this.entities.url()) {
  8902. if (!parserInput.$char(';')) {
  8903. parserInput.i = index;
  8904. error('missing semi-colon on @plugin');
  8905. }
  8906. return new tree.Import(path, null, options, index, fileInfo);
  8907. } else {
  8908. parserInput.i = index;
  8909. error('malformed @plugin statement');
  8910. }
  8911. }
  8912. },
  8913. pluginArgs: function pluginArgs() {
  8914. // list of options, surrounded by parens
  8915. parserInput.save();
  8916. if (!parserInput.$char('(')) {
  8917. parserInput.restore();
  8918. return null;
  8919. }
  8920. var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
  8921. if (args[1]) {
  8922. parserInput.forget();
  8923. return args[1].trim();
  8924. } else {
  8925. parserInput.restore();
  8926. return null;
  8927. }
  8928. },
  8929. //
  8930. // A CSS AtRule
  8931. //
  8932. // @charset "utf-8";
  8933. //
  8934. atrule: function atrule() {
  8935. var index = parserInput.i;
  8936. var name;
  8937. var value;
  8938. var rules;
  8939. var nonVendorSpecificName;
  8940. var hasIdentifier;
  8941. var hasExpression;
  8942. var hasUnknown;
  8943. var hasBlock = true;
  8944. var isRooted = true;
  8945. if (parserInput.currentChar() !== '@') {
  8946. return;
  8947. }
  8948. value = this['import']() || this.plugin() || this.media();
  8949. if (value) {
  8950. return value;
  8951. }
  8952. parserInput.save();
  8953. name = parserInput.$re(/^@[a-z-]+/);
  8954. if (!name) {
  8955. return;
  8956. }
  8957. nonVendorSpecificName = name;
  8958. if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
  8959. nonVendorSpecificName = `@${name.slice(name.indexOf('-', 2) + 1)}`;
  8960. }
  8961. switch (nonVendorSpecificName) {
  8962. case '@charset':
  8963. hasIdentifier = true;
  8964. hasBlock = false;
  8965. break;
  8966. case '@namespace':
  8967. hasExpression = true;
  8968. hasBlock = false;
  8969. break;
  8970. case '@keyframes':
  8971. case '@counter-style':
  8972. hasIdentifier = true;
  8973. break;
  8974. case '@document':
  8975. case '@supports':
  8976. hasUnknown = true;
  8977. isRooted = false;
  8978. break;
  8979. default:
  8980. hasUnknown = true;
  8981. break;
  8982. }
  8983. parserInput.commentStore.length = 0;
  8984. if (hasIdentifier) {
  8985. value = this.entity();
  8986. if (!value) {
  8987. error(`expected ${name} identifier`);
  8988. }
  8989. } else if (hasExpression) {
  8990. value = this.expression();
  8991. if (!value) {
  8992. error(`expected ${name} expression`);
  8993. }
  8994. } else if (hasUnknown) {
  8995. value = this.permissiveValue(/^[{;]/);
  8996. hasBlock = parserInput.currentChar() === '{';
  8997. if (!value) {
  8998. if (!hasBlock && parserInput.currentChar() !== ';') {
  8999. error(`${name} rule is missing block or ending semi-colon`);
  9000. }
  9001. } else if (!value.value) {
  9002. value = null;
  9003. }
  9004. }
  9005. if (hasBlock) {
  9006. rules = this.blockRuleset();
  9007. }
  9008. if (rules || !hasBlock && value && parserInput.$char(';')) {
  9009. parserInput.forget();
  9010. return new tree.AtRule(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
  9011. }
  9012. parserInput.restore('at-rule options not recognised');
  9013. },
  9014. //
  9015. // A Value is a comma-delimited list of Expressions
  9016. //
  9017. // font-family: Baskerville, Georgia, serif;
  9018. //
  9019. // In a Rule, a Value represents everything after the `:`,
  9020. // and before the `;`.
  9021. //
  9022. value: function value() {
  9023. var e;
  9024. var expressions = [];
  9025. var index = parserInput.i;
  9026. do {
  9027. e = this.expression();
  9028. if (e) {
  9029. expressions.push(e);
  9030. if (!parserInput.$char(',')) {
  9031. break;
  9032. }
  9033. }
  9034. } while (e);
  9035. if (expressions.length > 0) {
  9036. return new tree.Value(expressions, index);
  9037. }
  9038. },
  9039. important: function important() {
  9040. if (parserInput.currentChar() === '!') {
  9041. return parserInput.$re(/^! *important/);
  9042. }
  9043. },
  9044. sub: function sub() {
  9045. var a;
  9046. var e;
  9047. parserInput.save();
  9048. if (parserInput.$char('(')) {
  9049. a = this.addition();
  9050. if (a && parserInput.$char(')')) {
  9051. parserInput.forget();
  9052. e = new tree.Expression([a]);
  9053. e.parens = true;
  9054. return e;
  9055. }
  9056. parserInput.restore('Expected \')\'');
  9057. return;
  9058. }
  9059. parserInput.restore();
  9060. },
  9061. multiplication: function multiplication() {
  9062. var m;
  9063. var a;
  9064. var op;
  9065. var operation;
  9066. var isSpaced;
  9067. m = this.operand();
  9068. if (m) {
  9069. isSpaced = parserInput.isWhitespace(-1);
  9070. while (true) {
  9071. if (parserInput.peek(/^\/[*\/]/)) {
  9072. break;
  9073. }
  9074. parserInput.save();
  9075. op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
  9076. if (!op) {
  9077. parserInput.forget();
  9078. break;
  9079. }
  9080. a = this.operand();
  9081. if (!a) {
  9082. parserInput.restore();
  9083. break;
  9084. }
  9085. parserInput.forget();
  9086. m.parensInOp = true;
  9087. a.parensInOp = true;
  9088. operation = new tree.Operation(op, [operation || m, a], isSpaced);
  9089. isSpaced = parserInput.isWhitespace(-1);
  9090. }
  9091. return operation || m;
  9092. }
  9093. },
  9094. addition: function addition() {
  9095. var m;
  9096. var a;
  9097. var op;
  9098. var operation;
  9099. var isSpaced;
  9100. m = this.multiplication();
  9101. if (m) {
  9102. isSpaced = parserInput.isWhitespace(-1);
  9103. while (true) {
  9104. op = parserInput.$re(/^[-+]\s+/) || !isSpaced && (parserInput.$char('+') || parserInput.$char('-'));
  9105. if (!op) {
  9106. break;
  9107. }
  9108. a = this.multiplication();
  9109. if (!a) {
  9110. break;
  9111. }
  9112. m.parensInOp = true;
  9113. a.parensInOp = true;
  9114. operation = new tree.Operation(op, [operation || m, a], isSpaced);
  9115. isSpaced = parserInput.isWhitespace(-1);
  9116. }
  9117. return operation || m;
  9118. }
  9119. },
  9120. conditions: function conditions() {
  9121. var a;
  9122. var b;
  9123. var index = parserInput.i;
  9124. var condition;
  9125. a = this.condition(true);
  9126. if (a) {
  9127. while (true) {
  9128. if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
  9129. break;
  9130. }
  9131. b = this.condition(true);
  9132. if (!b) {
  9133. break;
  9134. }
  9135. condition = new tree.Condition('or', condition || a, b, index);
  9136. }
  9137. return condition || a;
  9138. }
  9139. },
  9140. condition: function condition(needsParens) {
  9141. var result;
  9142. var logical;
  9143. var next;
  9144. function or() {
  9145. return parserInput.$str('or');
  9146. }
  9147. result = this.conditionAnd(needsParens);
  9148. if (!result) {
  9149. return;
  9150. }
  9151. logical = or();
  9152. if (logical) {
  9153. next = this.condition(needsParens);
  9154. if (next) {
  9155. result = new tree.Condition(logical, result, next);
  9156. } else {
  9157. return;
  9158. }
  9159. }
  9160. return result;
  9161. },
  9162. conditionAnd: function conditionAnd(needsParens) {
  9163. var result;
  9164. var logical;
  9165. var next;
  9166. var self = this;
  9167. function insideCondition() {
  9168. var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
  9169. if (!cond && !needsParens) {
  9170. return self.atomicCondition(needsParens);
  9171. }
  9172. return cond;
  9173. }
  9174. function and() {
  9175. return parserInput.$str('and');
  9176. }
  9177. result = insideCondition();
  9178. if (!result) {
  9179. return;
  9180. }
  9181. logical = and();
  9182. if (logical) {
  9183. next = this.conditionAnd(needsParens);
  9184. if (next) {
  9185. result = new tree.Condition(logical, result, next);
  9186. } else {
  9187. return;
  9188. }
  9189. }
  9190. return result;
  9191. },
  9192. negatedCondition: function negatedCondition(needsParens) {
  9193. if (parserInput.$str('not')) {
  9194. var result = this.parenthesisCondition(needsParens);
  9195. if (result) {
  9196. result.negate = !result.negate;
  9197. }
  9198. return result;
  9199. }
  9200. },
  9201. parenthesisCondition: function parenthesisCondition(needsParens) {
  9202. function tryConditionFollowedByParenthesis(me) {
  9203. var body;
  9204. parserInput.save();
  9205. body = me.condition(needsParens);
  9206. if (!body) {
  9207. parserInput.restore();
  9208. return;
  9209. }
  9210. if (!parserInput.$char(')')) {
  9211. parserInput.restore();
  9212. return;
  9213. }
  9214. parserInput.forget();
  9215. return body;
  9216. }
  9217. var body;
  9218. parserInput.save();
  9219. if (!parserInput.$str('(')) {
  9220. parserInput.restore();
  9221. return;
  9222. }
  9223. body = tryConditionFollowedByParenthesis(this);
  9224. if (body) {
  9225. parserInput.forget();
  9226. return body;
  9227. }
  9228. body = this.atomicCondition(needsParens);
  9229. if (!body) {
  9230. parserInput.restore();
  9231. return;
  9232. }
  9233. if (!parserInput.$char(')')) {
  9234. parserInput.restore(`expected ')' got '${parserInput.currentChar()}'`);
  9235. return;
  9236. }
  9237. parserInput.forget();
  9238. return body;
  9239. },
  9240. atomicCondition: function atomicCondition(needsParens) {
  9241. var entities = this.entities;
  9242. var index = parserInput.i;
  9243. var a;
  9244. var b;
  9245. var c;
  9246. var op;
  9247. function cond() {
  9248. return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
  9249. }
  9250. cond = cond.bind(this);
  9251. a = cond();
  9252. if (a) {
  9253. if (parserInput.$char('>')) {
  9254. if (parserInput.$char('=')) {
  9255. op = '>=';
  9256. } else {
  9257. op = '>';
  9258. }
  9259. } else if (parserInput.$char('<')) {
  9260. if (parserInput.$char('=')) {
  9261. op = '<=';
  9262. } else {
  9263. op = '<';
  9264. }
  9265. } else if (parserInput.$char('=')) {
  9266. if (parserInput.$char('>')) {
  9267. op = '=>';
  9268. } else if (parserInput.$char('<')) {
  9269. op = '=<';
  9270. } else {
  9271. op = '=';
  9272. }
  9273. }
  9274. if (op) {
  9275. b = cond();
  9276. if (b) {
  9277. c = new tree.Condition(op, a, b, index, false);
  9278. } else {
  9279. error('expected expression');
  9280. }
  9281. } else {
  9282. c = new tree.Condition('=', a, new tree.Keyword('true'), index, false);
  9283. }
  9284. return c;
  9285. }
  9286. },
  9287. //
  9288. // An operand is anything that can be part of an operation,
  9289. // such as a Color, or a Variable
  9290. //
  9291. operand: function operand() {
  9292. var entities = this.entities;
  9293. var negate;
  9294. if (parserInput.peek(/^-[@\$\(]/)) {
  9295. negate = parserInput.$char('-');
  9296. }
  9297. var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.property() || entities.call() || entities.quoted(true) || entities.colorKeyword() || entities.mixinLookup();
  9298. if (negate) {
  9299. o.parensInOp = true;
  9300. o = new tree.Negative(o);
  9301. }
  9302. return o;
  9303. },
  9304. //
  9305. // Expressions either represent mathematical operations,
  9306. // or white-space delimited Entities.
  9307. //
  9308. // 1px solid black
  9309. // @var * 2
  9310. //
  9311. expression: function expression() {
  9312. var entities = [];
  9313. var e;
  9314. var delim;
  9315. var index = parserInput.i;
  9316. do {
  9317. e = this.comment();
  9318. if (e) {
  9319. entities.push(e);
  9320. continue;
  9321. }
  9322. e = this.addition() || this.entity();
  9323. if (e) {
  9324. entities.push(e); // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
  9325. if (!parserInput.peek(/^\/[\/*]/)) {
  9326. delim = parserInput.$char('/');
  9327. if (delim) {
  9328. entities.push(new tree.Anonymous(delim, index));
  9329. }
  9330. }
  9331. }
  9332. } while (e);
  9333. if (entities.length > 0) {
  9334. return new tree.Expression(entities);
  9335. }
  9336. },
  9337. property: function property() {
  9338. var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
  9339. if (name) {
  9340. return name[1];
  9341. }
  9342. },
  9343. ruleProperty: function ruleProperty() {
  9344. var name = [];
  9345. var index = [];
  9346. var s;
  9347. var k;
  9348. parserInput.save();
  9349. var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
  9350. if (simpleProperty) {
  9351. name = [new tree.Keyword(simpleProperty[1])];
  9352. parserInput.forget();
  9353. return name;
  9354. }
  9355. function match(re) {
  9356. var i = parserInput.i;
  9357. var chunk = parserInput.$re(re);
  9358. if (chunk) {
  9359. index.push(i);
  9360. return name.push(chunk[1]);
  9361. }
  9362. }
  9363. match(/^(\*?)/);
  9364. while (true) {
  9365. if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
  9366. break;
  9367. }
  9368. }
  9369. if (name.length > 1 && match(/^((?:\+_|\+)?)\s*:/)) {
  9370. parserInput.forget(); // at last, we have the complete match now. move forward,
  9371. // convert name particles to tree objects and return:
  9372. if (name[0] === '') {
  9373. name.shift();
  9374. index.shift();
  9375. }
  9376. for (k = 0; k < name.length; k++) {
  9377. s = name[k];
  9378. name[k] = s.charAt(0) !== '@' && s.charAt(0) !== '$' ? new tree.Keyword(s) : s.charAt(0) === '@' ? new tree.Variable(`@${s.slice(2, -1)}`, index[k], fileInfo) : new tree.Property(`$${s.slice(2, -1)}`, index[k], fileInfo);
  9379. }
  9380. return name;
  9381. }
  9382. parserInput.restore();
  9383. }
  9384. }
  9385. };
  9386. };
  9387. Parser.serializeVars = function (vars) {
  9388. var s = '';
  9389. for (var name in vars) {
  9390. if (Object.hasOwnProperty.call(vars, name)) {
  9391. var value = vars[name];
  9392. s += `${(name[0] === '@' ? '' : '@') + name}: ${value}${String(value).slice(-1) === ';' ? '' : ';'}`;
  9393. }
  9394. }
  9395. return s;
  9396. };
  9397. function boolean(condition) {
  9398. return condition ? Keyword.True : Keyword.False;
  9399. }
  9400. function If(condition, trueValue, falseValue) {
  9401. return condition ? trueValue : falseValue || new Anonymous();
  9402. }
  9403. var boolean$1 = {
  9404. boolean,
  9405. 'if': If
  9406. };
  9407. var colorFunctions;
  9408. function clamp$1(val) {
  9409. return Math.min(1, Math.max(0, val));
  9410. }
  9411. function hsla(origColor, hsl) {
  9412. var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
  9413. if (color) {
  9414. if (origColor.value && /^(rgb|hsl)/.test(origColor.value)) {
  9415. color.value = origColor.value;
  9416. } else {
  9417. color.value = 'rgb';
  9418. }
  9419. return color;
  9420. }
  9421. }
  9422. function toHSL(color) {
  9423. if (color.toHSL) {
  9424. return color.toHSL();
  9425. } else {
  9426. throw new Error('Argument cannot be evaluated to a color');
  9427. }
  9428. }
  9429. function toHSV(color) {
  9430. if (color.toHSV) {
  9431. return color.toHSV();
  9432. } else {
  9433. throw new Error('Argument cannot be evaluated to a color');
  9434. }
  9435. }
  9436. function number(n) {
  9437. if (n instanceof Dimension) {
  9438. return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
  9439. } else if (typeof n === 'number') {
  9440. return n;
  9441. } else {
  9442. throw {
  9443. type: 'Argument',
  9444. message: 'color functions take numbers as parameters'
  9445. };
  9446. }
  9447. }
  9448. function scaled(n, size) {
  9449. if (n instanceof Dimension && n.unit.is('%')) {
  9450. return parseFloat(n.value * size / 100);
  9451. } else {
  9452. return number(n);
  9453. }
  9454. }
  9455. colorFunctions = {
  9456. rgb: function rgb(r, g, b) {
  9457. var color = colorFunctions.rgba(r, g, b, 1.0);
  9458. if (color) {
  9459. color.value = 'rgb';
  9460. return color;
  9461. }
  9462. },
  9463. rgba: function rgba(r, g, b, a) {
  9464. try {
  9465. if (r instanceof Color) {
  9466. if (g) {
  9467. a = number(g);
  9468. } else {
  9469. a = r.alpha;
  9470. }
  9471. return new Color(r.rgb, a, 'rgba');
  9472. }
  9473. var rgb = [r, g, b].map(function (c) {
  9474. return scaled(c, 255);
  9475. });
  9476. a = number(a);
  9477. return new Color(rgb, a, 'rgba');
  9478. } catch (e) {}
  9479. },
  9480. hsl: function hsl(h, s, l) {
  9481. var color = colorFunctions.hsla(h, s, l, 1.0);
  9482. if (color) {
  9483. color.value = 'hsl';
  9484. return color;
  9485. }
  9486. },
  9487. hsla: function hsla(h, s, l, a) {
  9488. try {
  9489. if (h instanceof Color) {
  9490. if (s) {
  9491. a = number(s);
  9492. } else {
  9493. a = h.alpha;
  9494. }
  9495. return new Color(h.rgb, a, 'hsla');
  9496. }
  9497. var m1;
  9498. var m2;
  9499. function hue(h) {
  9500. h = h < 0 ? h + 1 : h > 1 ? h - 1 : h;
  9501. if (h * 6 < 1) {
  9502. return m1 + (m2 - m1) * h * 6;
  9503. } else if (h * 2 < 1) {
  9504. return m2;
  9505. } else if (h * 3 < 2) {
  9506. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  9507. } else {
  9508. return m1;
  9509. }
  9510. }
  9511. h = number(h) % 360 / 360;
  9512. s = clamp$1(number(s));
  9513. l = clamp$1(number(l));
  9514. a = clamp$1(number(a));
  9515. m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  9516. m1 = l * 2 - m2;
  9517. var rgb = [hue(h + 1 / 3) * 255, hue(h) * 255, hue(h - 1 / 3) * 255];
  9518. a = number(a);
  9519. return new Color(rgb, a, 'hsla');
  9520. } catch (e) {}
  9521. },
  9522. hsv: function hsv(h, s, v) {
  9523. return colorFunctions.hsva(h, s, v, 1.0);
  9524. },
  9525. hsva: function hsva(h, s, v, a) {
  9526. h = number(h) % 360 / 360 * 360;
  9527. s = number(s);
  9528. v = number(v);
  9529. a = number(a);
  9530. var i;
  9531. var f;
  9532. i = Math.floor(h / 60 % 6);
  9533. f = h / 60 - i;
  9534. var vs = [v, v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)];
  9535. var perm = [[0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2]];
  9536. return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
  9537. },
  9538. hue: function hue(color) {
  9539. return new Dimension(toHSL(color).h);
  9540. },
  9541. saturation: function saturation(color) {
  9542. return new Dimension(toHSL(color).s * 100, '%');
  9543. },
  9544. lightness: function lightness(color) {
  9545. return new Dimension(toHSL(color).l * 100, '%');
  9546. },
  9547. hsvhue: function hsvhue(color) {
  9548. return new Dimension(toHSV(color).h);
  9549. },
  9550. hsvsaturation: function hsvsaturation(color) {
  9551. return new Dimension(toHSV(color).s * 100, '%');
  9552. },
  9553. hsvvalue: function hsvvalue(color) {
  9554. return new Dimension(toHSV(color).v * 100, '%');
  9555. },
  9556. red: function red(color) {
  9557. return new Dimension(color.rgb[0]);
  9558. },
  9559. green: function green(color) {
  9560. return new Dimension(color.rgb[1]);
  9561. },
  9562. blue: function blue(color) {
  9563. return new Dimension(color.rgb[2]);
  9564. },
  9565. alpha: function alpha(color) {
  9566. return new Dimension(toHSL(color).a);
  9567. },
  9568. luma: function luma(color) {
  9569. return new Dimension(color.luma() * color.alpha * 100, '%');
  9570. },
  9571. luminance: function luminance(color) {
  9572. var luminance = 0.2126 * color.rgb[0] / 255 + 0.7152 * color.rgb[1] / 255 + 0.0722 * color.rgb[2] / 255;
  9573. return new Dimension(luminance * color.alpha * 100, '%');
  9574. },
  9575. saturate: function saturate(color, amount, method) {
  9576. // filter: saturate(3.2);
  9577. // should be kept as is, so check for color
  9578. if (!color.rgb) {
  9579. return null;
  9580. }
  9581. var hsl = toHSL(color);
  9582. if (typeof method !== 'undefined' && method.value === 'relative') {
  9583. hsl.s += hsl.s * amount.value / 100;
  9584. } else {
  9585. hsl.s += amount.value / 100;
  9586. }
  9587. hsl.s = clamp$1(hsl.s);
  9588. return hsla(color, hsl);
  9589. },
  9590. desaturate: function desaturate(color, amount, method) {
  9591. var hsl = toHSL(color);
  9592. if (typeof method !== 'undefined' && method.value === 'relative') {
  9593. hsl.s -= hsl.s * amount.value / 100;
  9594. } else {
  9595. hsl.s -= amount.value / 100;
  9596. }
  9597. hsl.s = clamp$1(hsl.s);
  9598. return hsla(color, hsl);
  9599. },
  9600. lighten: function lighten(color, amount, method) {
  9601. var hsl = toHSL(color);
  9602. if (typeof method !== 'undefined' && method.value === 'relative') {
  9603. hsl.l += hsl.l * amount.value / 100;
  9604. } else {
  9605. hsl.l += amount.value / 100;
  9606. }
  9607. hsl.l = clamp$1(hsl.l);
  9608. return hsla(color, hsl);
  9609. },
  9610. darken: function darken(color, amount, method) {
  9611. var hsl = toHSL(color);
  9612. if (typeof method !== 'undefined' && method.value === 'relative') {
  9613. hsl.l -= hsl.l * amount.value / 100;
  9614. } else {
  9615. hsl.l -= amount.value / 100;
  9616. }
  9617. hsl.l = clamp$1(hsl.l);
  9618. return hsla(color, hsl);
  9619. },
  9620. fadein: function fadein(color, amount, method) {
  9621. var hsl = toHSL(color);
  9622. if (typeof method !== 'undefined' && method.value === 'relative') {
  9623. hsl.a += hsl.a * amount.value / 100;
  9624. } else {
  9625. hsl.a += amount.value / 100;
  9626. }
  9627. hsl.a = clamp$1(hsl.a);
  9628. return hsla(color, hsl);
  9629. },
  9630. fadeout: function fadeout(color, amount, method) {
  9631. var hsl = toHSL(color);
  9632. if (typeof method !== 'undefined' && method.value === 'relative') {
  9633. hsl.a -= hsl.a * amount.value / 100;
  9634. } else {
  9635. hsl.a -= amount.value / 100;
  9636. }
  9637. hsl.a = clamp$1(hsl.a);
  9638. return hsla(color, hsl);
  9639. },
  9640. fade: function fade(color, amount) {
  9641. var hsl = toHSL(color);
  9642. hsl.a = amount.value / 100;
  9643. hsl.a = clamp$1(hsl.a);
  9644. return hsla(color, hsl);
  9645. },
  9646. spin: function spin(color, amount) {
  9647. var hsl = toHSL(color);
  9648. var hue = (hsl.h + amount.value) % 360;
  9649. hsl.h = hue < 0 ? 360 + hue : hue;
  9650. return hsla(color, hsl);
  9651. },
  9652. //
  9653. // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
  9654. // http://sass-lang.com
  9655. //
  9656. mix: function mix(color1, color2, weight) {
  9657. if (!weight) {
  9658. weight = new Dimension(50);
  9659. }
  9660. var p = weight.value / 100.0;
  9661. var w = p * 2 - 1;
  9662. var a = toHSL(color1).a - toHSL(color2).a;
  9663. var w1 = ((w * a == -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  9664. var w2 = 1 - w1;
  9665. var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2];
  9666. var alpha = color1.alpha * p + color2.alpha * (1 - p);
  9667. return new Color(rgb, alpha);
  9668. },
  9669. greyscale: function greyscale(color) {
  9670. return colorFunctions.desaturate(color, new Dimension(100));
  9671. },
  9672. contrast: function contrast(color, dark, light, threshold) {
  9673. // filter: contrast(3.2);
  9674. // should be kept as is, so check for color
  9675. if (!color.rgb) {
  9676. return null;
  9677. }
  9678. if (typeof light === 'undefined') {
  9679. light = colorFunctions.rgba(255, 255, 255, 1.0);
  9680. }
  9681. if (typeof dark === 'undefined') {
  9682. dark = colorFunctions.rgba(0, 0, 0, 1.0);
  9683. } // Figure out which is actually light and dark:
  9684. if (dark.luma() > light.luma()) {
  9685. var t = light;
  9686. light = dark;
  9687. dark = t;
  9688. }
  9689. if (typeof threshold === 'undefined') {
  9690. threshold = 0.43;
  9691. } else {
  9692. threshold = number(threshold);
  9693. }
  9694. if (color.luma() < threshold) {
  9695. return light;
  9696. } else {
  9697. return dark;
  9698. }
  9699. },
  9700. // Changes made in 2.7.0 - Reverted in 3.0.0
  9701. // contrast: function (color, color1, color2, threshold) {
  9702. // // Return which of `color1` and `color2` has the greatest contrast with `color`
  9703. // // according to the standard WCAG contrast ratio calculation.
  9704. // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  9705. // // The threshold param is no longer used, in line with SASS.
  9706. // // filter: contrast(3.2);
  9707. // // should be kept as is, so check for color
  9708. // if (!color.rgb) {
  9709. // return null;
  9710. // }
  9711. // if (typeof color1 === 'undefined') {
  9712. // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
  9713. // }
  9714. // if (typeof color2 === 'undefined') {
  9715. // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
  9716. // }
  9717. // var contrast1, contrast2;
  9718. // var luma = color.luma();
  9719. // var luma1 = color1.luma();
  9720. // var luma2 = color2.luma();
  9721. // // Calculate contrast ratios for each color
  9722. // if (luma > luma1) {
  9723. // contrast1 = (luma + 0.05) / (luma1 + 0.05);
  9724. // } else {
  9725. // contrast1 = (luma1 + 0.05) / (luma + 0.05);
  9726. // }
  9727. // if (luma > luma2) {
  9728. // contrast2 = (luma + 0.05) / (luma2 + 0.05);
  9729. // } else {
  9730. // contrast2 = (luma2 + 0.05) / (luma + 0.05);
  9731. // }
  9732. // if (contrast1 > contrast2) {
  9733. // return color1;
  9734. // } else {
  9735. // return color2;
  9736. // }
  9737. // },
  9738. argb: function argb(color) {
  9739. return new Anonymous(color.toARGB());
  9740. },
  9741. color: function color(c) {
  9742. if (c instanceof Quoted && /^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value)) {
  9743. var val = c.value.slice(1);
  9744. return new Color(val, undefined, `#${val}`);
  9745. }
  9746. if (c instanceof Color || (c = Color.fromKeyword(c.value))) {
  9747. c.value = undefined;
  9748. return c;
  9749. }
  9750. throw {
  9751. type: 'Argument',
  9752. message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
  9753. };
  9754. },
  9755. tint: function tint(color, amount) {
  9756. return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
  9757. },
  9758. shade: function shade(color, amount) {
  9759. return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
  9760. }
  9761. };
  9762. var color = colorFunctions;
  9763. // ref: http://www.w3.org/TR/compositing-1
  9764. function colorBlend(mode, color1, color2) {
  9765. var ab = color1.alpha; // result
  9766. var // backdrop
  9767. cb;
  9768. var as = color2.alpha;
  9769. var // source
  9770. cs;
  9771. var ar;
  9772. var cr;
  9773. var r = [];
  9774. ar = as + ab * (1 - as);
  9775. for (var i = 0; i < 3; i++) {
  9776. cb = color1.rgb[i] / 255;
  9777. cs = color2.rgb[i] / 255;
  9778. cr = mode(cb, cs);
  9779. if (ar) {
  9780. cr = (as * cs + ab * (cb - as * (cb + cs - cr))) / ar;
  9781. }
  9782. r[i] = cr * 255;
  9783. }
  9784. return new Color(r, ar);
  9785. }
  9786. var colorBlendModeFunctions = {
  9787. multiply: function multiply(cb, cs) {
  9788. return cb * cs;
  9789. },
  9790. screen: function screen(cb, cs) {
  9791. return cb + cs - cb * cs;
  9792. },
  9793. overlay: function overlay(cb, cs) {
  9794. cb *= 2;
  9795. return cb <= 1 ? colorBlendModeFunctions.multiply(cb, cs) : colorBlendModeFunctions.screen(cb - 1, cs);
  9796. },
  9797. softlight: function softlight(cb, cs) {
  9798. var d = 1;
  9799. var e = cb;
  9800. if (cs > 0.5) {
  9801. e = 1;
  9802. d = cb > 0.25 ? Math.sqrt(cb) : ((16 * cb - 12) * cb + 4) * cb;
  9803. }
  9804. return cb - (1 - 2 * cs) * e * (d - cb);
  9805. },
  9806. hardlight: function hardlight(cb, cs) {
  9807. return colorBlendModeFunctions.overlay(cs, cb);
  9808. },
  9809. difference: function difference(cb, cs) {
  9810. return Math.abs(cb - cs);
  9811. },
  9812. exclusion: function exclusion(cb, cs) {
  9813. return cb + cs - 2 * cb * cs;
  9814. },
  9815. // non-w3c functions:
  9816. average: function average(cb, cs) {
  9817. return (cb + cs) / 2;
  9818. },
  9819. negation: function negation(cb, cs) {
  9820. return 1 - Math.abs(cb + cs - 1);
  9821. }
  9822. };
  9823. for (var f in colorBlendModeFunctions) {
  9824. if (colorBlendModeFunctions.hasOwnProperty(f)) {
  9825. colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
  9826. }
  9827. }
  9828. var dataUri = (function (environment) {
  9829. var fallback = function fallback(functionThis, node) {
  9830. return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context);
  9831. };
  9832. return {
  9833. 'data-uri': function dataUri(mimetypeNode, filePathNode) {
  9834. if (!filePathNode) {
  9835. filePathNode = mimetypeNode;
  9836. mimetypeNode = null;
  9837. }
  9838. var mimetype = mimetypeNode && mimetypeNode.value;
  9839. var filePath = filePathNode.value;
  9840. var currentFileInfo = this.currentFileInfo;
  9841. var currentDirectory = currentFileInfo.rewriteUrls ? currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  9842. var fragmentStart = filePath.indexOf('#');
  9843. var fragment = '';
  9844. if (fragmentStart !== -1) {
  9845. fragment = filePath.slice(fragmentStart);
  9846. filePath = filePath.slice(0, fragmentStart);
  9847. }
  9848. var context = clone(this.context);
  9849. context.rawBuffer = true;
  9850. var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
  9851. if (!fileManager) {
  9852. return fallback(this, filePathNode);
  9853. }
  9854. var useBase64 = false; // detect the mimetype if not given
  9855. if (!mimetypeNode) {
  9856. mimetype = environment.mimeLookup(filePath);
  9857. if (mimetype === 'image/svg+xml') {
  9858. useBase64 = false;
  9859. } else {
  9860. // use base 64 unless it's an ASCII or UTF-8 format
  9861. var charset = environment.charsetLookup(mimetype);
  9862. useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
  9863. }
  9864. if (useBase64) {
  9865. mimetype += ';base64';
  9866. }
  9867. } else {
  9868. useBase64 = /;base64$/.test(mimetype);
  9869. }
  9870. var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
  9871. if (!fileSync.contents) {
  9872. logger.warn(`Skipped data-uri embedding of ${filePath} because file not found`);
  9873. return fallback(this, filePathNode || mimetypeNode);
  9874. }
  9875. var buf = fileSync.contents;
  9876. if (useBase64 && !environment.encodeBase64) {
  9877. return fallback(this, filePathNode);
  9878. }
  9879. buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
  9880. var uri = `data:${mimetype},${buf}${fragment}`;
  9881. return new URL(new Quoted(`"${uri}"`, uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  9882. }
  9883. };
  9884. });
  9885. var getItemsFromNode = function getItemsFromNode(node) {
  9886. // handle non-array values as an array of length 1
  9887. // return 'undefined' if index is invalid
  9888. var items = Array.isArray(node.value) ? node.value : Array(node);
  9889. return items;
  9890. };
  9891. var list = {
  9892. _SELF: function _SELF(n) {
  9893. return n;
  9894. },
  9895. extract: function extract(values, index) {
  9896. // (1-based index)
  9897. index = index.value - 1;
  9898. return getItemsFromNode(values)[index];
  9899. },
  9900. length: function length(values) {
  9901. return new Dimension(getItemsFromNode(values).length);
  9902. },
  9903. /**
  9904. * Creates a Less list of incremental values.
  9905. * Modeled after Lodash's range function, also exists natively in PHP
  9906. *
  9907. * @param {Dimension} [start=1]
  9908. * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
  9909. * @param {Dimension} [step=1]
  9910. */
  9911. range: function range(start, end, step) {
  9912. var from;
  9913. var to;
  9914. var stepValue = 1;
  9915. var list = [];
  9916. if (end) {
  9917. to = end;
  9918. from = start.value;
  9919. if (step) {
  9920. stepValue = step.value;
  9921. }
  9922. } else {
  9923. from = 1;
  9924. to = start;
  9925. }
  9926. for (var i = from; i <= to.value; i += stepValue) {
  9927. list.push(new Dimension(i, to.unit));
  9928. }
  9929. return new Expression(list);
  9930. },
  9931. each: function each(list, rs) {
  9932. var rules = [];
  9933. var newRules;
  9934. var iterator;
  9935. if (list.value && !(list instanceof Quoted)) {
  9936. if (Array.isArray(list.value)) {
  9937. iterator = list.value;
  9938. } else {
  9939. iterator = [list.value];
  9940. }
  9941. } else if (list.ruleset) {
  9942. iterator = list.ruleset.rules;
  9943. } else if (list.rules) {
  9944. iterator = list.rules;
  9945. } else if (Array.isArray(list)) {
  9946. iterator = list;
  9947. } else {
  9948. iterator = [list];
  9949. }
  9950. var valueName = '@value';
  9951. var keyName = '@key';
  9952. var indexName = '@index';
  9953. if (rs.params) {
  9954. valueName = rs.params[0] && rs.params[0].name;
  9955. keyName = rs.params[1] && rs.params[1].name;
  9956. indexName = rs.params[2] && rs.params[2].name;
  9957. rs = rs.rules;
  9958. } else {
  9959. rs = rs.ruleset;
  9960. }
  9961. for (var i = 0; i < iterator.length; i++) {
  9962. var key = void 0;
  9963. var value = void 0;
  9964. var item = iterator[i];
  9965. if (item instanceof Declaration) {
  9966. key = typeof item.name === 'string' ? item.name : item.name[0].value;
  9967. value = item.value;
  9968. } else {
  9969. key = new Dimension(i + 1);
  9970. value = item;
  9971. }
  9972. if (item instanceof Comment) {
  9973. continue;
  9974. }
  9975. newRules = rs.rules.slice(0);
  9976. if (valueName) {
  9977. newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
  9978. }
  9979. if (indexName) {
  9980. newRules.push(new Declaration(indexName, new Dimension(i + 1), false, false, this.index, this.currentFileInfo));
  9981. }
  9982. if (keyName) {
  9983. newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
  9984. }
  9985. rules.push(new Ruleset([new Selector([new Element("", '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
  9986. }
  9987. return new Ruleset([new Selector([new Element("", '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
  9988. }
  9989. };
  9990. var MathHelper = function MathHelper(fn, unit, n) {
  9991. if (!(n instanceof Dimension)) {
  9992. throw {
  9993. type: 'Argument',
  9994. message: 'argument must be a number'
  9995. };
  9996. }
  9997. if (unit == null) {
  9998. unit = n.unit;
  9999. } else {
  10000. n = n.unify();
  10001. }
  10002. return new Dimension(fn(parseFloat(n.value)), unit);
  10003. };
  10004. var mathFunctions = {
  10005. // name, unit
  10006. ceil: null,
  10007. floor: null,
  10008. sqrt: null,
  10009. abs: null,
  10010. tan: '',
  10011. sin: '',
  10012. cos: '',
  10013. atan: 'rad',
  10014. asin: 'rad',
  10015. acos: 'rad'
  10016. };
  10017. for (var f$1 in mathFunctions) {
  10018. if (mathFunctions.hasOwnProperty(f$1)) {
  10019. mathFunctions[f$1] = MathHelper.bind(null, Math[f$1], mathFunctions[f$1]);
  10020. }
  10021. }
  10022. mathFunctions.round = function (n, f) {
  10023. var fraction = typeof f === 'undefined' ? 0 : f.value;
  10024. return MathHelper(function (num) {
  10025. return num.toFixed(fraction);
  10026. }, null, n);
  10027. };
  10028. var minMax = function minMax(isMin, args) {
  10029. args = Array.prototype.slice.call(args);
  10030. switch (args.length) {
  10031. case 0:
  10032. throw {
  10033. type: 'Argument',
  10034. message: 'one or more arguments required'
  10035. };
  10036. }
  10037. var i; // key is the unit.toString() for unified Dimension values,
  10038. var j;
  10039. var current;
  10040. var currentUnified;
  10041. var referenceUnified;
  10042. var unit;
  10043. var unitStatic;
  10044. var unitClone;
  10045. var // elems only contains original argument values.
  10046. order = [];
  10047. var values = {}; // value is the index into the order array.
  10048. for (i = 0; i < args.length; i++) {
  10049. current = args[i];
  10050. if (!(current instanceof Dimension)) {
  10051. if (Array.isArray(args[i].value)) {
  10052. Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
  10053. }
  10054. continue;
  10055. }
  10056. currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
  10057. unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
  10058. unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
  10059. unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
  10060. j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
  10061. if (j === undefined) {
  10062. if (unitStatic !== undefined && unit !== unitStatic) {
  10063. throw {
  10064. type: 'Argument',
  10065. message: 'incompatible types'
  10066. };
  10067. }
  10068. values[unit] = order.length;
  10069. order.push(current);
  10070. continue;
  10071. }
  10072. referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
  10073. if (isMin && currentUnified.value < referenceUnified.value || !isMin && currentUnified.value > referenceUnified.value) {
  10074. order[j] = current;
  10075. }
  10076. }
  10077. if (order.length == 1) {
  10078. return order[0];
  10079. }
  10080. args = order.map(function (a) {
  10081. return a.toCSS(this.context);
  10082. }).join(this.context.compress ? ',' : ', ');
  10083. return new Anonymous(`${isMin ? 'min' : 'max'}(${args})`);
  10084. };
  10085. var number$1 = {
  10086. min: function min() {
  10087. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  10088. args[_key] = arguments[_key];
  10089. }
  10090. return minMax(true, args);
  10091. },
  10092. max: function max() {
  10093. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  10094. args[_key2] = arguments[_key2];
  10095. }
  10096. return minMax(false, args);
  10097. },
  10098. convert: function convert(val, unit) {
  10099. return val.convertTo(unit.value);
  10100. },
  10101. pi: function pi() {
  10102. return new Dimension(Math.PI);
  10103. },
  10104. mod: function mod(a, b) {
  10105. return new Dimension(a.value % b.value, a.unit);
  10106. },
  10107. pow: function pow(x, y) {
  10108. if (typeof x === 'number' && typeof y === 'number') {
  10109. x = new Dimension(x);
  10110. y = new Dimension(y);
  10111. } else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
  10112. throw {
  10113. type: 'Argument',
  10114. message: 'arguments must be numbers'
  10115. };
  10116. }
  10117. return new Dimension(Math.pow(x.value, y.value), x.unit);
  10118. },
  10119. percentage: function percentage(n) {
  10120. var result = MathHelper(function (num) {
  10121. return num * 100;
  10122. }, '%', n);
  10123. return result;
  10124. }
  10125. };
  10126. var string = {
  10127. e: function e(str) {
  10128. return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
  10129. },
  10130. escape: function escape(str) {
  10131. return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B').replace(/\(/g, '%28').replace(/\)/g, '%29'));
  10132. },
  10133. replace: function replace(string, pattern, replacement, flags) {
  10134. var result = string.value;
  10135. replacement = replacement.type === 'Quoted' ? replacement.value : replacement.toCSS();
  10136. result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
  10137. return new Quoted(string.quote || '', result, string.escaped);
  10138. },
  10139. '%': function _(string
  10140. /* arg, arg, ... */
  10141. ) {
  10142. var args = Array.prototype.slice.call(arguments, 1);
  10143. var result = string.value;
  10144. var _loop = function _loop(i) {
  10145. /* jshint loopfunc:true */
  10146. result = result.replace(/%[sda]/i, function (token) {
  10147. var value = args[i].type === 'Quoted' && token.match(/s/i) ? args[i].value : args[i].toCSS();
  10148. return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
  10149. });
  10150. };
  10151. for (var i = 0; i < args.length; i++) {
  10152. _loop(i);
  10153. }
  10154. result = result.replace(/%%/g, '%');
  10155. return new Quoted(string.quote || '', result, string.escaped);
  10156. }
  10157. };
  10158. var svg = (function (environment) {
  10159. return {
  10160. 'svg-gradient': function svgGradient(direction) {
  10161. var stops;
  10162. var gradientDirectionSvg;
  10163. var gradientType = 'linear';
  10164. var rectangleDimension = 'x="0" y="0" width="1" height="1"';
  10165. var renderEnv = {
  10166. compress: false
  10167. };
  10168. var returner;
  10169. var directionValue = direction.toCSS(renderEnv);
  10170. var i;
  10171. var color;
  10172. var position;
  10173. var positionValue;
  10174. var alpha;
  10175. function throwArgumentDescriptor() {
  10176. throw {
  10177. type: 'Argument',
  10178. message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' + ' end_color [end_position] or direction, color list'
  10179. };
  10180. }
  10181. if (arguments.length == 2) {
  10182. if (arguments[1].value.length < 2) {
  10183. throwArgumentDescriptor();
  10184. }
  10185. stops = arguments[1].value;
  10186. } else if (arguments.length < 3) {
  10187. throwArgumentDescriptor();
  10188. } else {
  10189. stops = Array.prototype.slice.call(arguments, 1);
  10190. }
  10191. switch (directionValue) {
  10192. case 'to bottom':
  10193. gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
  10194. break;
  10195. case 'to right':
  10196. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
  10197. break;
  10198. case 'to bottom right':
  10199. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
  10200. break;
  10201. case 'to top right':
  10202. gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
  10203. break;
  10204. case 'ellipse':
  10205. case 'ellipse at center':
  10206. gradientType = 'radial';
  10207. gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
  10208. rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
  10209. break;
  10210. default:
  10211. throw {
  10212. type: 'Argument',
  10213. message: 'svg-gradient direction must be \'to bottom\', \'to right\',' + ' \'to bottom right\', \'to top right\' or \'ellipse at center\''
  10214. };
  10215. }
  10216. returner = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><${gradientType}Gradient id="g" ${gradientDirectionSvg}>`;
  10217. for (i = 0; i < stops.length; i += 1) {
  10218. if (stops[i] instanceof Expression) {
  10219. color = stops[i].value[0];
  10220. position = stops[i].value[1];
  10221. } else {
  10222. color = stops[i];
  10223. position = undefined;
  10224. }
  10225. if (!(color instanceof Color) || !((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension)) {
  10226. throwArgumentDescriptor();
  10227. }
  10228. positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
  10229. alpha = color.alpha;
  10230. returner += `<stop offset="${positionValue}" stop-color="${color.toRGB()}"${alpha < 1 ? ` stop-opacity="${alpha}"` : ''}/>`;
  10231. }
  10232. returner += `</${gradientType}Gradient><rect ${rectangleDimension} fill="url(#g)" /></svg>`;
  10233. returner = encodeURIComponent(returner);
  10234. returner = `data:image/svg+xml,${returner}`;
  10235. return new URL(new Quoted(`'${returner}'`, returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  10236. }
  10237. };
  10238. });
  10239. var isa = function isa(n, Type) {
  10240. return n instanceof Type ? Keyword.True : Keyword.False;
  10241. };
  10242. var isunit = function isunit(n, unit) {
  10243. if (unit === undefined) {
  10244. throw {
  10245. type: 'Argument',
  10246. message: 'missing the required second argument to isunit.'
  10247. };
  10248. }
  10249. unit = typeof unit.value === 'string' ? unit.value : unit;
  10250. if (typeof unit !== 'string') {
  10251. throw {
  10252. type: 'Argument',
  10253. message: 'Second argument to isunit should be a unit or a string.'
  10254. };
  10255. }
  10256. return n instanceof Dimension && n.unit.is(unit) ? Keyword.True : Keyword.False;
  10257. };
  10258. var types = {
  10259. isruleset: function isruleset(n) {
  10260. return isa(n, DetachedRuleset);
  10261. },
  10262. iscolor: function iscolor(n) {
  10263. return isa(n, Color);
  10264. },
  10265. isnumber: function isnumber(n) {
  10266. return isa(n, Dimension);
  10267. },
  10268. isstring: function isstring(n) {
  10269. return isa(n, Quoted);
  10270. },
  10271. iskeyword: function iskeyword(n) {
  10272. return isa(n, Keyword);
  10273. },
  10274. isurl: function isurl(n) {
  10275. return isa(n, URL);
  10276. },
  10277. ispixel: function ispixel(n) {
  10278. return isunit(n, 'px');
  10279. },
  10280. ispercentage: function ispercentage(n) {
  10281. return isunit(n, '%');
  10282. },
  10283. isem: function isem(n) {
  10284. return isunit(n, 'em');
  10285. },
  10286. isunit,
  10287. unit: function unit(val, _unit) {
  10288. if (!(val instanceof Dimension)) {
  10289. throw {
  10290. type: 'Argument',
  10291. message: `the first argument to unit must be a number${val instanceof Operation ? '. Have you forgotten parenthesis?' : ''}`
  10292. };
  10293. }
  10294. if (_unit) {
  10295. if (_unit instanceof Keyword) {
  10296. _unit = _unit.value;
  10297. } else {
  10298. _unit = _unit.toCSS();
  10299. }
  10300. } else {
  10301. _unit = '';
  10302. }
  10303. return new Dimension(val.value, _unit);
  10304. },
  10305. 'get-unit': function getUnit(n) {
  10306. return new Anonymous(n.unit);
  10307. }
  10308. };
  10309. var Functions = (function (environment) {
  10310. var functions = {
  10311. functionRegistry,
  10312. functionCaller
  10313. }; // register functions
  10314. functionRegistry.addMultiple(boolean$1);
  10315. functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
  10316. functionRegistry.addMultiple(color);
  10317. functionRegistry.addMultiple(colorBlend);
  10318. functionRegistry.addMultiple(dataUri(environment));
  10319. functionRegistry.addMultiple(list);
  10320. functionRegistry.addMultiple(mathFunctions);
  10321. functionRegistry.addMultiple(number$1);
  10322. functionRegistry.addMultiple(string);
  10323. functionRegistry.addMultiple(svg());
  10324. functionRegistry.addMultiple(types);
  10325. return functions;
  10326. });
  10327. var sourceMapOutput = (function (environment) {
  10328. var SourceMapOutput =
  10329. /*#__PURE__*/
  10330. function () {
  10331. function SourceMapOutput(options) {
  10332. _classCallCheck(this, SourceMapOutput);
  10333. this._css = [];
  10334. this._rootNode = options.rootNode;
  10335. this._contentsMap = options.contentsMap;
  10336. this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
  10337. if (options.sourceMapFilename) {
  10338. this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
  10339. }
  10340. this._outputFilename = options.outputFilename;
  10341. this.sourceMapURL = options.sourceMapURL;
  10342. if (options.sourceMapBasepath) {
  10343. this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
  10344. }
  10345. if (options.sourceMapRootpath) {
  10346. this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
  10347. if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
  10348. this._sourceMapRootpath += '/';
  10349. }
  10350. } else {
  10351. this._sourceMapRootpath = '';
  10352. }
  10353. this._outputSourceFiles = options.outputSourceFiles;
  10354. this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
  10355. this._lineNumber = 0;
  10356. this._column = 0;
  10357. }
  10358. _createClass(SourceMapOutput, [{
  10359. key: "removeBasepath",
  10360. value: function removeBasepath(path) {
  10361. if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
  10362. path = path.substring(this._sourceMapBasepath.length);
  10363. if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
  10364. path = path.substring(1);
  10365. }
  10366. }
  10367. return path;
  10368. }
  10369. }, {
  10370. key: "normalizeFilename",
  10371. value: function normalizeFilename(filename) {
  10372. filename = filename.replace(/\\/g, '/');
  10373. filename = this.removeBasepath(filename);
  10374. return (this._sourceMapRootpath || '') + filename;
  10375. }
  10376. }, {
  10377. key: "add",
  10378. value: function add(chunk, fileInfo, index, mapLines) {
  10379. // ignore adding empty strings
  10380. if (!chunk) {
  10381. return;
  10382. }
  10383. var lines;
  10384. var sourceLines;
  10385. var columns;
  10386. var sourceColumns;
  10387. var i;
  10388. if (fileInfo && fileInfo.filename) {
  10389. var inputSource = this._contentsMap[fileInfo.filename]; // remove vars/banner added to the top of the file
  10390. if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
  10391. // adjust the index
  10392. index -= this._contentsIgnoredCharsMap[fileInfo.filename];
  10393. if (index < 0) {
  10394. index = 0;
  10395. } // adjust the source
  10396. inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
  10397. } // ignore empty content
  10398. if (inputSource === undefined) {
  10399. return;
  10400. }
  10401. inputSource = inputSource.substring(0, index);
  10402. sourceLines = inputSource.split('\n');
  10403. sourceColumns = sourceLines[sourceLines.length - 1];
  10404. }
  10405. lines = chunk.split('\n');
  10406. columns = lines[lines.length - 1];
  10407. if (fileInfo && fileInfo.filename) {
  10408. if (!mapLines) {
  10409. this._sourceMapGenerator.addMapping({
  10410. generated: {
  10411. line: this._lineNumber + 1,
  10412. column: this._column
  10413. },
  10414. original: {
  10415. line: sourceLines.length,
  10416. column: sourceColumns.length
  10417. },
  10418. source: this.normalizeFilename(fileInfo.filename)
  10419. });
  10420. } else {
  10421. for (i = 0; i < lines.length; i++) {
  10422. this._sourceMapGenerator.addMapping({
  10423. generated: {
  10424. line: this._lineNumber + i + 1,
  10425. column: i === 0 ? this._column : 0
  10426. },
  10427. original: {
  10428. line: sourceLines.length + i,
  10429. column: i === 0 ? sourceColumns.length : 0
  10430. },
  10431. source: this.normalizeFilename(fileInfo.filename)
  10432. });
  10433. }
  10434. }
  10435. }
  10436. if (lines.length === 1) {
  10437. this._column += columns.length;
  10438. } else {
  10439. this._lineNumber += lines.length - 1;
  10440. this._column = columns.length;
  10441. }
  10442. this._css.push(chunk);
  10443. }
  10444. }, {
  10445. key: "isEmpty",
  10446. value: function isEmpty() {
  10447. return this._css.length === 0;
  10448. }
  10449. }, {
  10450. key: "toCSS",
  10451. value: function toCSS(context) {
  10452. this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({
  10453. file: this._outputFilename,
  10454. sourceRoot: null
  10455. });
  10456. if (this._outputSourceFiles) {
  10457. for (var filename in this._contentsMap) {
  10458. if (this._contentsMap.hasOwnProperty(filename)) {
  10459. var source = this._contentsMap[filename];
  10460. if (this._contentsIgnoredCharsMap[filename]) {
  10461. source = source.slice(this._contentsIgnoredCharsMap[filename]);
  10462. }
  10463. this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
  10464. }
  10465. }
  10466. }
  10467. this._rootNode.genCSS(context, this);
  10468. if (this._css.length > 0) {
  10469. var sourceMapURL;
  10470. var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
  10471. if (this.sourceMapURL) {
  10472. sourceMapURL = this.sourceMapURL;
  10473. } else if (this._sourceMapFilename) {
  10474. sourceMapURL = this._sourceMapFilename;
  10475. }
  10476. this.sourceMapURL = sourceMapURL;
  10477. this.sourceMap = sourceMapContent;
  10478. }
  10479. return this._css.join('');
  10480. }
  10481. }]);
  10482. return SourceMapOutput;
  10483. }();
  10484. return SourceMapOutput;
  10485. });
  10486. var sourceMapBuilder = (function (SourceMapOutput, environment) {
  10487. var SourceMapBuilder =
  10488. /*#__PURE__*/
  10489. function () {
  10490. function SourceMapBuilder(options) {
  10491. _classCallCheck(this, SourceMapBuilder);
  10492. this.options = options;
  10493. }
  10494. _createClass(SourceMapBuilder, [{
  10495. key: "toCSS",
  10496. value: function toCSS(rootNode, options, imports) {
  10497. var sourceMapOutput = new SourceMapOutput({
  10498. contentsIgnoredCharsMap: imports.contentsIgnoredChars,
  10499. rootNode,
  10500. contentsMap: imports.contents,
  10501. sourceMapFilename: this.options.sourceMapFilename,
  10502. sourceMapURL: this.options.sourceMapURL,
  10503. outputFilename: this.options.sourceMapOutputFilename,
  10504. sourceMapBasepath: this.options.sourceMapBasepath,
  10505. sourceMapRootpath: this.options.sourceMapRootpath,
  10506. outputSourceFiles: this.options.outputSourceFiles,
  10507. sourceMapGenerator: this.options.sourceMapGenerator,
  10508. sourceMapFileInline: this.options.sourceMapFileInline
  10509. });
  10510. var css = sourceMapOutput.toCSS(options);
  10511. this.sourceMap = sourceMapOutput.sourceMap;
  10512. this.sourceMapURL = sourceMapOutput.sourceMapURL;
  10513. if (this.options.sourceMapInputFilename) {
  10514. this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
  10515. }
  10516. if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
  10517. this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
  10518. }
  10519. return css + this.getCSSAppendage();
  10520. }
  10521. }, {
  10522. key: "getCSSAppendage",
  10523. value: function getCSSAppendage() {
  10524. var sourceMapURL = this.sourceMapURL;
  10525. if (this.options.sourceMapFileInline) {
  10526. if (this.sourceMap === undefined) {
  10527. return '';
  10528. }
  10529. sourceMapURL = `data:application/json;base64,${environment.encodeBase64(this.sourceMap)}`;
  10530. }
  10531. if (sourceMapURL) {
  10532. return `/*# sourceMappingURL=${sourceMapURL} */`;
  10533. }
  10534. return '';
  10535. }
  10536. }, {
  10537. key: "getExternalSourceMap",
  10538. value: function getExternalSourceMap() {
  10539. return this.sourceMap;
  10540. }
  10541. }, {
  10542. key: "setExternalSourceMap",
  10543. value: function setExternalSourceMap(sourceMap) {
  10544. this.sourceMap = sourceMap;
  10545. }
  10546. }, {
  10547. key: "isInline",
  10548. value: function isInline() {
  10549. return this.options.sourceMapFileInline;
  10550. }
  10551. }, {
  10552. key: "getSourceMapURL",
  10553. value: function getSourceMapURL() {
  10554. return this.sourceMapURL;
  10555. }
  10556. }, {
  10557. key: "getOutputFilename",
  10558. value: function getOutputFilename() {
  10559. return this.options.sourceMapOutputFilename;
  10560. }
  10561. }, {
  10562. key: "getInputFilename",
  10563. value: function getInputFilename() {
  10564. return this.sourceMapInputFilename;
  10565. }
  10566. }]);
  10567. return SourceMapBuilder;
  10568. }();
  10569. return SourceMapBuilder;
  10570. });
  10571. var transformTree = (function (root) {
  10572. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  10573. var evaldRoot;
  10574. var variables = options.variables;
  10575. var evalEnv = new contexts.Eval(options); //
  10576. // Allows setting variables with a hash, so:
  10577. //
  10578. // `{ color: new tree.Color('#f01') }` will become:
  10579. //
  10580. // new tree.Declaration('@color',
  10581. // new tree.Value([
  10582. // new tree.Expression([
  10583. // new tree.Color('#f01')
  10584. // ])
  10585. // ])
  10586. // )
  10587. //
  10588. if (typeof variables === 'object' && !Array.isArray(variables)) {
  10589. variables = Object.keys(variables).map(function (k) {
  10590. var value = variables[k];
  10591. if (!(value instanceof tree.Value)) {
  10592. if (!(value instanceof tree.Expression)) {
  10593. value = new tree.Expression([value]);
  10594. }
  10595. value = new tree.Value([value]);
  10596. }
  10597. return new tree.Declaration(`@${k}`, value, false, null, 0);
  10598. });
  10599. evalEnv.frames = [new tree.Ruleset(null, variables)];
  10600. }
  10601. var visitors$1 = [new visitors.JoinSelectorVisitor(), new visitors.MarkVisibleSelectorsVisitor(true), new visitors.ExtendVisitor(), new visitors.ToCSSVisitor({
  10602. compress: Boolean(options.compress)
  10603. })];
  10604. var preEvalVisitors = [];
  10605. var v;
  10606. var visitorIterator;
  10607. /**
  10608. * first() / get() allows visitors to be added while visiting
  10609. *
  10610. * @todo Add scoping for visitors just like functions for @plugin; right now they're global
  10611. */
  10612. if (options.pluginManager) {
  10613. visitorIterator = options.pluginManager.visitor();
  10614. for (var i = 0; i < 2; i++) {
  10615. visitorIterator.first();
  10616. while (v = visitorIterator.get()) {
  10617. if (v.isPreEvalVisitor) {
  10618. if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
  10619. preEvalVisitors.push(v);
  10620. v.run(root);
  10621. }
  10622. } else {
  10623. if (i === 0 || visitors$1.indexOf(v) === -1) {
  10624. if (v.isPreVisitor) {
  10625. visitors$1.unshift(v);
  10626. } else {
  10627. visitors$1.push(v);
  10628. }
  10629. }
  10630. }
  10631. }
  10632. }
  10633. }
  10634. evaldRoot = root.eval(evalEnv);
  10635. for (var i = 0; i < visitors$1.length; i++) {
  10636. visitors$1[i].run(evaldRoot);
  10637. } // Run any remaining visitors added after eval pass
  10638. if (options.pluginManager) {
  10639. visitorIterator.first();
  10640. while (v = visitorIterator.get()) {
  10641. if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
  10642. v.run(evaldRoot);
  10643. }
  10644. }
  10645. }
  10646. return evaldRoot;
  10647. });
  10648. var parseTree = (function (SourceMapBuilder) {
  10649. var ParseTree =
  10650. /*#__PURE__*/
  10651. function () {
  10652. function ParseTree(root, imports) {
  10653. _classCallCheck(this, ParseTree);
  10654. this.root = root;
  10655. this.imports = imports;
  10656. }
  10657. _createClass(ParseTree, [{
  10658. key: "toCSS",
  10659. value: function toCSS(options) {
  10660. var evaldRoot;
  10661. var result = {};
  10662. var sourceMapBuilder;
  10663. try {
  10664. evaldRoot = transformTree(this.root, options);
  10665. } catch (e) {
  10666. throw new LessError(e, this.imports);
  10667. }
  10668. try {
  10669. var compress = Boolean(options.compress);
  10670. if (compress) {
  10671. logger.warn('The compress option has been deprecated. ' + 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
  10672. }
  10673. var toCSSOptions = {
  10674. compress,
  10675. dumpLineNumbers: options.dumpLineNumbers,
  10676. strictUnits: Boolean(options.strictUnits),
  10677. numPrecision: 8
  10678. };
  10679. if (options.sourceMap) {
  10680. sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
  10681. result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
  10682. } else {
  10683. result.css = evaldRoot.toCSS(toCSSOptions);
  10684. }
  10685. } catch (e) {
  10686. throw new LessError(e, this.imports);
  10687. }
  10688. if (options.pluginManager) {
  10689. var postProcessors = options.pluginManager.getPostProcessors();
  10690. for (var i = 0; i < postProcessors.length; i++) {
  10691. result.css = postProcessors[i].process(result.css, {
  10692. sourceMap: sourceMapBuilder,
  10693. options,
  10694. imports: this.imports
  10695. });
  10696. }
  10697. }
  10698. if (options.sourceMap) {
  10699. result.map = sourceMapBuilder.getExternalSourceMap();
  10700. }
  10701. result.imports = [];
  10702. for (var file in this.imports.files) {
  10703. if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) {
  10704. result.imports.push(file);
  10705. }
  10706. }
  10707. return result;
  10708. }
  10709. }]);
  10710. return ParseTree;
  10711. }();
  10712. return ParseTree;
  10713. });
  10714. var importManager = (function (environment) {
  10715. // FileInfo = {
  10716. // 'rewriteUrls' - option - whether to adjust URL's to be relative
  10717. // 'filename' - full resolved filename of current file
  10718. // 'rootpath' - path to append to normal URLs for this node
  10719. // 'currentDirectory' - path to the current file, absolute
  10720. // 'rootFilename' - filename of the base file
  10721. // 'entryPath' - absolute path to the entry file
  10722. // 'reference' - whether the file should not be output and only output parts that are referenced
  10723. var ImportManager =
  10724. /*#__PURE__*/
  10725. function () {
  10726. function ImportManager(less, context, rootFileInfo) {
  10727. _classCallCheck(this, ImportManager);
  10728. this.less = less;
  10729. this.rootFilename = rootFileInfo.filename;
  10730. this.paths = context.paths || []; // Search paths, when importing
  10731. this.contents = {}; // map - filename to contents of all the files
  10732. this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
  10733. this.mime = context.mime;
  10734. this.error = null;
  10735. this.context = context; // Deprecated? Unused outside of here, could be useful.
  10736. this.queue = []; // Files which haven't been imported yet
  10737. this.files = {}; // Holds the imported parse trees.
  10738. }
  10739. /**
  10740. * Add an import to be imported
  10741. * @param path - the raw path
  10742. * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
  10743. * @param currentFileInfo - the current file info (used for instance to work out relative paths)
  10744. * @param importOptions - import options
  10745. * @param callback - callback for when it is imported
  10746. */
  10747. _createClass(ImportManager, [{
  10748. key: "push",
  10749. value: function push(path, tryAppendExtension, currentFileInfo, importOptions, callback) {
  10750. var importManager = this;
  10751. var pluginLoader = this.context.pluginManager.Loader;
  10752. this.queue.push(path);
  10753. var fileParsedFunc = function fileParsedFunc(e, root, fullPath) {
  10754. importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
  10755. var importedEqualsRoot = fullPath === importManager.rootFilename;
  10756. if (importOptions.optional && e) {
  10757. callback(null, {
  10758. rules: []
  10759. }, false, null);
  10760. logger.info(`The file ${fullPath} was skipped because it was not found and the import was marked optional.`);
  10761. } else {
  10762. // Inline imports aren't cached here.
  10763. // If we start to cache them, please make sure they won't conflict with non-inline imports of the
  10764. // same name as they used to do before this comment and the condition below have been added.
  10765. if (!importManager.files[fullPath] && !importOptions.inline) {
  10766. importManager.files[fullPath] = {
  10767. root,
  10768. options: importOptions
  10769. };
  10770. }
  10771. if (e && !importManager.error) {
  10772. importManager.error = e;
  10773. }
  10774. callback(e, root, importedEqualsRoot, fullPath);
  10775. }
  10776. };
  10777. var newFileInfo = {
  10778. rewriteUrls: this.context.rewriteUrls,
  10779. entryPath: currentFileInfo.entryPath,
  10780. rootpath: currentFileInfo.rootpath,
  10781. rootFilename: currentFileInfo.rootFilename
  10782. };
  10783. var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
  10784. if (!fileManager) {
  10785. fileParsedFunc({
  10786. message: `Could not find a file-manager for ${path}`
  10787. });
  10788. return;
  10789. }
  10790. var loadFileCallback = function loadFileCallback(loadedFile) {
  10791. var plugin;
  10792. var resolvedFilename = loadedFile.filename;
  10793. var contents = loadedFile.contents.replace(/^\uFEFF/, ''); // Pass on an updated rootpath if path of imported file is relative and file
  10794. // is in a (sub|sup) directory
  10795. //
  10796. // Examples:
  10797. // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
  10798. // then rootpath should become 'less/module/nav/'
  10799. // - If path of imported file is '../mixins.less' and rootpath is 'less/',
  10800. // then rootpath should become 'less/../'
  10801. newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
  10802. if (newFileInfo.rewriteUrls) {
  10803. newFileInfo.rootpath = fileManager.join(importManager.context.rootpath || '', fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
  10804. if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
  10805. newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
  10806. }
  10807. }
  10808. newFileInfo.filename = resolvedFilename;
  10809. var newEnv = new contexts.Parse(importManager.context);
  10810. newEnv.processImports = false;
  10811. importManager.contents[resolvedFilename] = contents;
  10812. if (currentFileInfo.reference || importOptions.reference) {
  10813. newFileInfo.reference = true;
  10814. }
  10815. if (importOptions.isPlugin) {
  10816. plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
  10817. if (plugin instanceof LessError) {
  10818. fileParsedFunc(plugin, null, resolvedFilename);
  10819. } else {
  10820. fileParsedFunc(null, plugin, resolvedFilename);
  10821. }
  10822. } else if (importOptions.inline) {
  10823. fileParsedFunc(null, contents, resolvedFilename);
  10824. } else {
  10825. // import (multiple) parse trees apparently get altered and can't be cached.
  10826. // TODO: investigate why this is
  10827. if (importManager.files[resolvedFilename] && !importManager.files[resolvedFilename].options.multiple && !importOptions.multiple) {
  10828. fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
  10829. } else {
  10830. new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
  10831. fileParsedFunc(e, root, resolvedFilename);
  10832. });
  10833. }
  10834. }
  10835. };
  10836. var promise;
  10837. var context = clone(this.context);
  10838. if (tryAppendExtension) {
  10839. context.ext = importOptions.isPlugin ? '.js' : '.less';
  10840. }
  10841. if (importOptions.isPlugin) {
  10842. context.mime = 'application/javascript';
  10843. promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  10844. } else {
  10845. promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
  10846. if (err) {
  10847. fileParsedFunc(err);
  10848. } else {
  10849. loadFileCallback(loadedFile);
  10850. }
  10851. });
  10852. }
  10853. if (promise) {
  10854. promise.then(loadFileCallback, fileParsedFunc);
  10855. }
  10856. }
  10857. }]);
  10858. return ImportManager;
  10859. }();
  10860. return ImportManager;
  10861. });
  10862. var Render = (function (environment, ParseTree, ImportManager) {
  10863. var render = function render(input, options, callback) {
  10864. if (typeof options === 'function') {
  10865. callback = options;
  10866. options = copyOptions(this.options, {});
  10867. } else {
  10868. options = copyOptions(this.options, options || {});
  10869. }
  10870. if (!callback) {
  10871. var self = this;
  10872. return new Promise(function (resolve, reject) {
  10873. render.call(self, input, options, function (err, output) {
  10874. if (err) {
  10875. reject(err);
  10876. } else {
  10877. resolve(output);
  10878. }
  10879. });
  10880. });
  10881. } else {
  10882. this.parse(input, options, function (err, root, imports, options) {
  10883. if (err) {
  10884. return callback(err);
  10885. }
  10886. var result;
  10887. try {
  10888. var parseTree = new ParseTree(root, imports);
  10889. result = parseTree.toCSS(options);
  10890. } catch (err) {
  10891. return callback(err);
  10892. }
  10893. callback(null, result);
  10894. });
  10895. }
  10896. };
  10897. return render;
  10898. });
  10899. /**
  10900. * Plugin Manager
  10901. */
  10902. var PluginManager =
  10903. /*#__PURE__*/
  10904. function () {
  10905. function PluginManager(less) {
  10906. _classCallCheck(this, PluginManager);
  10907. this.less = less;
  10908. this.visitors = [];
  10909. this.preProcessors = [];
  10910. this.postProcessors = [];
  10911. this.installedPlugins = [];
  10912. this.fileManagers = [];
  10913. this.iterator = -1;
  10914. this.pluginCache = {};
  10915. this.Loader = new less.PluginLoader(less);
  10916. }
  10917. /**
  10918. * Adds all the plugins in the array
  10919. * @param {Array} plugins
  10920. */
  10921. _createClass(PluginManager, [{
  10922. key: "addPlugins",
  10923. value: function addPlugins(plugins) {
  10924. if (plugins) {
  10925. for (var i = 0; i < plugins.length; i++) {
  10926. this.addPlugin(plugins[i]);
  10927. }
  10928. }
  10929. }
  10930. /**
  10931. *
  10932. * @param plugin
  10933. * @param {String} filename
  10934. */
  10935. }, {
  10936. key: "addPlugin",
  10937. value: function addPlugin(plugin, filename, functionRegistry) {
  10938. this.installedPlugins.push(plugin);
  10939. if (filename) {
  10940. this.pluginCache[filename] = plugin;
  10941. }
  10942. if (plugin.install) {
  10943. plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
  10944. }
  10945. }
  10946. /**
  10947. *
  10948. * @param filename
  10949. */
  10950. }, {
  10951. key: "get",
  10952. value: function get(filename) {
  10953. return this.pluginCache[filename];
  10954. }
  10955. /**
  10956. * Adds a visitor. The visitor object has options on itself to determine
  10957. * when it should run.
  10958. * @param visitor
  10959. */
  10960. }, {
  10961. key: "addVisitor",
  10962. value: function addVisitor(visitor) {
  10963. this.visitors.push(visitor);
  10964. }
  10965. /**
  10966. * Adds a pre processor object
  10967. * @param {object} preProcessor
  10968. * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
  10969. */
  10970. }, {
  10971. key: "addPreProcessor",
  10972. value: function addPreProcessor(preProcessor, priority) {
  10973. var indexToInsertAt;
  10974. for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
  10975. if (this.preProcessors[indexToInsertAt].priority >= priority) {
  10976. break;
  10977. }
  10978. }
  10979. this.preProcessors.splice(indexToInsertAt, 0, {
  10980. preProcessor,
  10981. priority
  10982. });
  10983. }
  10984. /**
  10985. * Adds a post processor object
  10986. * @param {object} postProcessor
  10987. * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
  10988. */
  10989. }, {
  10990. key: "addPostProcessor",
  10991. value: function addPostProcessor(postProcessor, priority) {
  10992. var indexToInsertAt;
  10993. for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
  10994. if (this.postProcessors[indexToInsertAt].priority >= priority) {
  10995. break;
  10996. }
  10997. }
  10998. this.postProcessors.splice(indexToInsertAt, 0, {
  10999. postProcessor,
  11000. priority
  11001. });
  11002. }
  11003. /**
  11004. *
  11005. * @param manager
  11006. */
  11007. }, {
  11008. key: "addFileManager",
  11009. value: function addFileManager(manager) {
  11010. this.fileManagers.push(manager);
  11011. }
  11012. /**
  11013. *
  11014. * @returns {Array}
  11015. * @private
  11016. */
  11017. }, {
  11018. key: "getPreProcessors",
  11019. value: function getPreProcessors() {
  11020. var preProcessors = [];
  11021. for (var i = 0; i < this.preProcessors.length; i++) {
  11022. preProcessors.push(this.preProcessors[i].preProcessor);
  11023. }
  11024. return preProcessors;
  11025. }
  11026. /**
  11027. *
  11028. * @returns {Array}
  11029. * @private
  11030. */
  11031. }, {
  11032. key: "getPostProcessors",
  11033. value: function getPostProcessors() {
  11034. var postProcessors = [];
  11035. for (var i = 0; i < this.postProcessors.length; i++) {
  11036. postProcessors.push(this.postProcessors[i].postProcessor);
  11037. }
  11038. return postProcessors;
  11039. }
  11040. /**
  11041. *
  11042. * @returns {Array}
  11043. * @private
  11044. */
  11045. }, {
  11046. key: "getVisitors",
  11047. value: function getVisitors() {
  11048. return this.visitors;
  11049. }
  11050. }, {
  11051. key: "visitor",
  11052. value: function visitor() {
  11053. var self = this;
  11054. return {
  11055. first: function first() {
  11056. self.iterator = -1;
  11057. return self.visitors[self.iterator];
  11058. },
  11059. get: function get() {
  11060. self.iterator += 1;
  11061. return self.visitors[self.iterator];
  11062. }
  11063. };
  11064. }
  11065. /**
  11066. *
  11067. * @returns {Array}
  11068. * @private
  11069. */
  11070. }, {
  11071. key: "getFileManagers",
  11072. value: function getFileManagers() {
  11073. return this.fileManagers;
  11074. }
  11075. }]);
  11076. return PluginManager;
  11077. }();
  11078. var pm;
  11079. function PluginManagerFactory(less, newFactory) {
  11080. if (newFactory || !pm) {
  11081. pm = new PluginManager(less);
  11082. }
  11083. return pm;
  11084. }
  11085. var Parse = (function (environment, ParseTree, ImportManager) {
  11086. var parse = function parse(input, options, callback) {
  11087. if (typeof options === 'function') {
  11088. callback = options;
  11089. options = copyOptions(this.options, {});
  11090. } else {
  11091. options = copyOptions(this.options, options || {});
  11092. }
  11093. if (!callback) {
  11094. var self = this;
  11095. return new Promise(function (resolve, reject) {
  11096. parse.call(self, input, options, function (err, output) {
  11097. if (err) {
  11098. reject(err);
  11099. } else {
  11100. resolve(output);
  11101. }
  11102. });
  11103. });
  11104. } else {
  11105. var context;
  11106. var rootFileInfo;
  11107. var pluginManager = new PluginManagerFactory(this, !options.reUsePluginManager);
  11108. options.pluginManager = pluginManager;
  11109. context = new contexts.Parse(options);
  11110. if (options.rootFileInfo) {
  11111. rootFileInfo = options.rootFileInfo;
  11112. } else {
  11113. var filename = options.filename || 'input';
  11114. var entryPath = filename.replace(/[^\/\\]*$/, '');
  11115. rootFileInfo = {
  11116. filename,
  11117. rewriteUrls: context.rewriteUrls,
  11118. rootpath: context.rootpath || '',
  11119. currentDirectory: entryPath,
  11120. entryPath,
  11121. rootFilename: filename
  11122. }; // add in a missing trailing slash
  11123. if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
  11124. rootFileInfo.rootpath += '/';
  11125. }
  11126. }
  11127. var imports = new ImportManager(this, context, rootFileInfo);
  11128. this.importManager = imports; // TODO: allow the plugins to be just a list of paths or names
  11129. // Do an async plugin queue like lessc
  11130. if (options.plugins) {
  11131. options.plugins.forEach(function (plugin) {
  11132. var evalResult;
  11133. var contents;
  11134. if (plugin.fileContent) {
  11135. contents = plugin.fileContent.replace(/^\uFEFF/, '');
  11136. evalResult = pluginManager.Loader.evalPlugin(contents, context, imports, plugin.options, plugin.filename);
  11137. if (evalResult instanceof LessError) {
  11138. return callback(evalResult);
  11139. }
  11140. } else {
  11141. pluginManager.addPlugin(plugin);
  11142. }
  11143. });
  11144. }
  11145. new Parser(context, imports, rootFileInfo).parse(input, function (e, root) {
  11146. if (e) {
  11147. return callback(e);
  11148. }
  11149. callback(null, root, imports, options);
  11150. }, options);
  11151. }
  11152. };
  11153. return parse;
  11154. });
  11155. var createFromEnvironment = (function (environment, fileManagers) {
  11156. /**
  11157. * @todo
  11158. * This original code could be improved quite a bit.
  11159. * Many classes / modules currently add side-effects / mutations to passed in objects,
  11160. * which makes it hard to refactor and reason about.
  11161. */
  11162. environment = new environment$1(environment, fileManagers);
  11163. var SourceMapOutput = sourceMapOutput(environment);
  11164. var SourceMapBuilder = sourceMapBuilder(SourceMapOutput, environment);
  11165. var ParseTree = parseTree(SourceMapBuilder);
  11166. var ImportManager = importManager(environment);
  11167. var render = Render(environment, ParseTree);
  11168. var parse = Parse(environment, ParseTree, ImportManager);
  11169. var functions = Functions(environment);
  11170. /**
  11171. * @todo
  11172. * This root properties / methods need to be organized.
  11173. * It's not clear what should / must be public and why.
  11174. */
  11175. var initial = {
  11176. version: [3, 10, 3],
  11177. data,
  11178. tree,
  11179. Environment: environment$1,
  11180. AbstractFileManager,
  11181. AbstractPluginLoader,
  11182. environment,
  11183. visitors,
  11184. Parser,
  11185. functions,
  11186. contexts,
  11187. SourceMapOutput,
  11188. SourceMapBuilder,
  11189. ParseTree,
  11190. ImportManager,
  11191. render,
  11192. parse,
  11193. LessError,
  11194. transformTree,
  11195. utils,
  11196. PluginManager: PluginManagerFactory,
  11197. logger
  11198. }; // Create a public API
  11199. var ctor = function ctor(t) {
  11200. return function () {
  11201. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  11202. args[_key] = arguments[_key];
  11203. }
  11204. return _construct(t, args);
  11205. };
  11206. };
  11207. var t;
  11208. var api = Object.create(initial);
  11209. for (var n in initial.tree) {
  11210. /* eslint guard-for-in: 0 */
  11211. t = initial.tree[n];
  11212. if (typeof t === 'function') {
  11213. api[n.toLowerCase()] = ctor(t);
  11214. } else {
  11215. api[n] = Object.create(null);
  11216. for (var o in t) {
  11217. /* eslint guard-for-in: 0 */
  11218. api[n][o.toLowerCase()] = ctor(t[o]);
  11219. }
  11220. }
  11221. }
  11222. return api;
  11223. });
  11224. function createCommonjsModule(fn, module) {
  11225. return module = { exports: {} }, fn(module, module.exports), module.exports;
  11226. }
  11227. var lesscHelper = createCommonjsModule(function (module, exports) {
  11228. // lessc_helper.js
  11229. //
  11230. // helper functions for lessc
  11231. var lessc_helper = {
  11232. // Stylize a string
  11233. stylize: function stylize(str, style) {
  11234. var styles = {
  11235. 'reset': [0, 0],
  11236. 'bold': [1, 22],
  11237. 'inverse': [7, 27],
  11238. 'underline': [4, 24],
  11239. 'yellow': [33, 39],
  11240. 'green': [32, 39],
  11241. 'red': [31, 39],
  11242. 'grey': [90, 39]
  11243. };
  11244. return `\x1b[${styles[style][0]}m${str}\x1b[${styles[style][1]}m`;
  11245. },
  11246. // Print command line options
  11247. printUsage: function printUsage() {
  11248. console.log('usage: lessc [option option=parameter ...] <source> [destination]');
  11249. console.log('');
  11250. console.log('If source is set to `-\' (dash or hyphen-minus), input is read from stdin.');
  11251. console.log('');
  11252. console.log('options:');
  11253. console.log(' -h, --help Prints help (this message) and exit.');
  11254. console.log(' --include-path=PATHS Sets include paths. Separated by `:\'. `;\' also supported on windows.');
  11255. console.log(' -M, --depends Outputs a makefile import dependency list to stdout.');
  11256. console.log(' --no-color Disables colorized output.');
  11257. console.log(' --ie-compat Enables IE8 compatibility checks.');
  11258. console.log(' --js Enables inline JavaScript in less files');
  11259. console.log(' -l, --lint Syntax check only (lint).');
  11260. console.log(' -s, --silent Suppresses output of error messages.');
  11261. console.log(' --strict-imports Forces evaluation of imports.');
  11262. console.log(' --insecure Allows imports from insecure https hosts.');
  11263. console.log(' -v, --version Prints version number and exit.');
  11264. console.log(' --verbose Be verbose.');
  11265. console.log(' --source-map[=FILENAME] Outputs a v3 sourcemap to the filename (or output filename.map).');
  11266. console.log(' --source-map-rootpath=X Adds this path onto the sourcemap filename and less file paths.');
  11267. console.log(' --source-map-basepath=X Sets sourcemap base path, defaults to current working directory.');
  11268. console.log(' --source-map-include-source Puts the less files into the map instead of referencing them.');
  11269. console.log(' --source-map-inline Puts the map (and any less files) as a base64 data uri into the output css file.');
  11270. console.log(' --source-map-url=URL Sets a custom URL to map file, for sourceMappingURL comment');
  11271. console.log(' in generated CSS file.');
  11272. console.log(' -rp, --rootpath=URL Sets rootpath for url rewriting in relative imports and urls');
  11273. console.log(' Works with or without the relative-urls option.');
  11274. console.log(' -ru=, --rewrite-urls= Rewrites URLs to make them relative to the base less file.');
  11275. console.log(' all|local|off \'all\' rewrites all URLs, \'local\' just those starting with a \'.\'');
  11276. console.log('');
  11277. console.log(' -m=, --math=');
  11278. console.log(' always Less will eagerly perform math operations always.');
  11279. console.log(' parens-division Math performed except for division (/) operator');
  11280. console.log(' parens | strict Math only performed inside parentheses');
  11281. console.log(' strict-legacy Parens required in very strict terms (legacy --strict-math)');
  11282. console.log('');
  11283. console.log(' -su=on|off Allows mixed units, e.g. 1px+1em or 1px*1px which have units');
  11284. console.log(' --strict-units=on|off that cannot be represented.');
  11285. console.log(' --global-var=\'VAR=VALUE\' Defines a variable that can be referenced by the file.');
  11286. console.log(' --modify-var=\'VAR=VALUE\' Modifies a variable already declared in the file.');
  11287. console.log(' --url-args=\'QUERYSTRING\' Adds params into url tokens (e.g. 42, cb=42 or \'a=1&b=2\')');
  11288. console.log(' --plugin=PLUGIN=OPTIONS Loads a plugin. You can also omit the --plugin= if the plugin begins');
  11289. console.log(' less-plugin. E.g. the clean css plugin is called less-plugin-clean-css');
  11290. console.log(' once installed (npm install less-plugin-clean-css), use either with');
  11291. console.log(' --plugin=less-plugin-clean-css or just --clean-css');
  11292. console.log(' specify options afterwards e.g. --plugin=less-plugin-clean-css="advanced"');
  11293. console.log(' or --clean-css="advanced"');
  11294. console.log('');
  11295. console.log('-------------------------- Deprecated ----------------');
  11296. console.log(' -sm=on|off Legacy parens-only math. Use --math');
  11297. console.log(' --strict-math=on|off ');
  11298. console.log('');
  11299. console.log(' --line-numbers=TYPE Outputs filename and line numbers.');
  11300. console.log(' TYPE can be either \'comments\', which will output');
  11301. console.log(' the debug info within comments, \'mediaquery\'');
  11302. console.log(' that will output the information within a fake');
  11303. console.log(' media query which is compatible with the SASS');
  11304. console.log(' format, and \'all\' which will do both.');
  11305. console.log(' -x, --compress Compresses output by removing some whitespaces.');
  11306. console.log(' We recommend you use a dedicated minifer like less-plugin-clean-css');
  11307. console.log('');
  11308. console.log('Report bugs to: http://github.com/less/less.js/issues');
  11309. console.log('Home page: <http://lesscss.org/>');
  11310. }
  11311. }; // Exports helper functions
  11312. for (var h in lessc_helper) {
  11313. if (lessc_helper.hasOwnProperty(h)) {
  11314. exports[h] = lessc_helper[h];
  11315. }
  11316. }
  11317. });
  11318. /**
  11319. * Node Plugin Loader
  11320. */
  11321. var PluginLoader =
  11322. /*#__PURE__*/
  11323. function (_AbstractPluginLoader) {
  11324. _inherits(PluginLoader, _AbstractPluginLoader);
  11325. function PluginLoader(less) {
  11326. var _this;
  11327. _classCallCheck(this, PluginLoader);
  11328. _this = _possibleConstructorReturn(this, _getPrototypeOf(PluginLoader).call(this));
  11329. _this.less = less;
  11330. _this.require = function (prefix) {
  11331. prefix = path.dirname(prefix);
  11332. return function (id) {
  11333. var str = id.substr(0, 2);
  11334. if (str === '..' || str === './') {
  11335. return require(path.join(prefix, id));
  11336. } else {
  11337. return require(id);
  11338. }
  11339. };
  11340. };
  11341. return _this;
  11342. }
  11343. _createClass(PluginLoader, [{
  11344. key: "loadPlugin",
  11345. value: function loadPlugin(filename, basePath, context, environment, fileManager) {
  11346. var prefix = filename.slice(0, 1);
  11347. var explicit = prefix === '.' || prefix === '/' || filename.slice(-3).toLowerCase() === '.js';
  11348. if (!explicit) {
  11349. context.prefixes = ['less-plugin-', ''];
  11350. }
  11351. return new Promise(function (fulfill, reject) {
  11352. fileManager.loadFile(filename, basePath, context, environment).then(function (data) {
  11353. try {
  11354. fulfill(data);
  11355. } catch (e) {
  11356. console.log(e);
  11357. reject(e);
  11358. }
  11359. }).catch(function (err) {
  11360. reject(err);
  11361. });
  11362. });
  11363. }
  11364. }]);
  11365. return PluginLoader;
  11366. }(AbstractPluginLoader);
  11367. // Export a new default each time
  11368. var defaultOptions = (function () {
  11369. return {
  11370. /* Inline Javascript - @plugin still allowed */
  11371. javascriptEnabled: false,
  11372. /* Outputs a makefile import dependency list to stdout. */
  11373. depends: false,
  11374. /* (DEPRECATED) Compress using less built-in compression.
  11375. * This does an okay job but does not utilise all the tricks of
  11376. * dedicated css compression. */
  11377. compress: false,
  11378. /* Runs the less parser and just reports errors without any output. */
  11379. lint: false,
  11380. /* Sets available include paths.
  11381. * If the file in an @import rule does not exist at that exact location,
  11382. * less will look for it at the location(s) passed to this option.
  11383. * You might use this for instance to specify a path to a library which
  11384. * you want to be referenced simply and relatively in the less files. */
  11385. paths: [],
  11386. /* color output in the terminal */
  11387. color: true,
  11388. /* The strictImports controls whether the compiler will allow an @import inside of either
  11389. * @media blocks or (a later addition) other selector blocks.
  11390. * See: https://github.com/less/less.js/issues/656 */
  11391. strictImports: false,
  11392. /* Allow Imports from Insecure HTTPS Hosts */
  11393. insecure: false,
  11394. /* Allows you to add a path to every generated import and url in your css.
  11395. * This does not affect less import statements that are processed, just ones
  11396. * that are left in the output css. */
  11397. rootpath: '',
  11398. /* By default URLs are kept as-is, so if you import a file in a sub-directory
  11399. * that references an image, exactly the same URL will be output in the css.
  11400. * This option allows you to re-write URL's in imported files so that the
  11401. * URL is always relative to the base imported file */
  11402. rewriteUrls: false,
  11403. /* How to process math
  11404. * 0 always - eagerly try to solve all operations
  11405. * 1 parens-division - require parens for division "/"
  11406. * 2 parens | strict - require parens for all operations
  11407. * 3 strict-legacy - legacy strict behavior (super-strict)
  11408. */
  11409. math: 0,
  11410. /* Without this option, less attempts to guess at the output unit when it does maths. */
  11411. strictUnits: false,
  11412. /* Effectively the declaration is put at the top of your base Less file,
  11413. * meaning it can be used but it also can be overridden if this variable
  11414. * is defined in the file. */
  11415. globalVars: null,
  11416. /* As opposed to the global variable option, this puts the declaration at the
  11417. * end of your base file, meaning it will override anything defined in your Less file. */
  11418. modifyVars: null,
  11419. /* This option allows you to specify a argument to go on to every URL. */
  11420. urlArgs: ''
  11421. };
  11422. });
  11423. var imageSize = (function (environment) {
  11424. function _imageSize(functionContext, filePathNode) {
  11425. var filePath = filePathNode.value;
  11426. var currentFileInfo = functionContext.currentFileInfo;
  11427. var currentDirectory = currentFileInfo.rewriteUrls ? currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  11428. var fragmentStart = filePath.indexOf('#');
  11429. var fragment = '';
  11430. if (fragmentStart !== -1) {
  11431. fragment = filePath.slice(fragmentStart);
  11432. filePath = filePath.slice(0, fragmentStart);
  11433. }
  11434. var fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);
  11435. if (!fileManager) {
  11436. throw {
  11437. type: 'File',
  11438. message: `Can not set up FileManager for ${filePathNode}`
  11439. };
  11440. }
  11441. var fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);
  11442. if (fileSync.error) {
  11443. throw fileSync.error;
  11444. }
  11445. var sizeOf = require('image-size');
  11446. return sizeOf(fileSync.filename);
  11447. }
  11448. var imageFunctions = {
  11449. 'image-size': function imageSize(filePathNode) {
  11450. var size = _imageSize(this, filePathNode);
  11451. return new Expression([new Dimension(size.width, 'px'), new Dimension(size.height, 'px')]);
  11452. },
  11453. 'image-width': function imageWidth(filePathNode) {
  11454. var size = _imageSize(this, filePathNode);
  11455. return new Dimension(size.width, 'px');
  11456. },
  11457. 'image-height': function imageHeight(filePathNode) {
  11458. var size = _imageSize(this, filePathNode);
  11459. return new Dimension(size.height, 'px');
  11460. }
  11461. };
  11462. functionRegistry.addMultiple(imageFunctions);
  11463. });
  11464. var less = createFromEnvironment(environment, [new FileManager(), new UrlFileManager()]); // allow people to create less with their own environment
  11465. less.createFromEnvironment = createFromEnvironment;
  11466. less.lesscHelper = lesscHelper;
  11467. less.PluginLoader = PluginLoader;
  11468. less.fs = fs$1;
  11469. less.FileManager = FileManager;
  11470. less.UrlFileManager = UrlFileManager; // Set up options
  11471. less.options = defaultOptions(); // provide image-size functionality
  11472. imageSize(less.environment);
  11473. module.exports = less;