less.js 476 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360
  1. /**
  2. * Less - Leaner CSS v4.1.3
  3. * http://lesscss.org
  4. *
  5. * Copyright (c) 2009-2022, Alexis Sellier <self@cloudhead.net>
  6. * Licensed under the Apache-2.0 License.
  7. *
  8. * @license Apache-2.0
  9. */
  10. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  12. typeof define === 'function' && define.amd ? define(factory) :
  13. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.less = factory());
  14. }(this, (function () { 'use strict';
  15. // Export a new default each time
  16. function defaultOptions () {
  17. return {
  18. /* Inline Javascript - @plugin still allowed */
  19. javascriptEnabled: false,
  20. /* Outputs a makefile import dependency list to stdout. */
  21. depends: false,
  22. /* (DEPRECATED) Compress using less built-in compression.
  23. * This does an okay job but does not utilise all the tricks of
  24. * dedicated css compression. */
  25. compress: false,
  26. /* Runs the less parser and just reports errors without any output. */
  27. lint: false,
  28. /* Sets available include paths.
  29. * If the file in an @import rule does not exist at that exact location,
  30. * less will look for it at the location(s) passed to this option.
  31. * You might use this for instance to specify a path to a library which
  32. * you want to be referenced simply and relatively in the less files. */
  33. paths: [],
  34. /* color output in the terminal */
  35. color: true,
  36. /* The strictImports controls whether the compiler will allow an @import inside of either
  37. * @media blocks or (a later addition) other selector blocks.
  38. * See: https://github.com/less/less.js/issues/656 */
  39. strictImports: false,
  40. /* Allow Imports from Insecure HTTPS Hosts */
  41. insecure: false,
  42. /* Allows you to add a path to every generated import and url in your css.
  43. * This does not affect less import statements that are processed, just ones
  44. * that are left in the output css. */
  45. rootpath: '',
  46. /* By default URLs are kept as-is, so if you import a file in a sub-directory
  47. * that references an image, exactly the same URL will be output in the css.
  48. * This option allows you to re-write URL's in imported files so that the
  49. * URL is always relative to the base imported file */
  50. rewriteUrls: false,
  51. /* How to process math
  52. * 0 always - eagerly try to solve all operations
  53. * 1 parens-division - require parens for division "/"
  54. * 2 parens | strict - require parens for all operations
  55. * 3 strict-legacy - legacy strict behavior (super-strict)
  56. */
  57. math: 1,
  58. /* Without this option, less attempts to guess at the output unit when it does maths. */
  59. strictUnits: false,
  60. /* Effectively the declaration is put at the top of your base Less file,
  61. * meaning it can be used but it also can be overridden if this variable
  62. * is defined in the file. */
  63. globalVars: null,
  64. /* As opposed to the global variable option, this puts the declaration at the
  65. * end of your base file, meaning it will override anything defined in your Less file. */
  66. modifyVars: null,
  67. /* This option allows you to specify a argument to go on to every URL. */
  68. urlArgs: ''
  69. };
  70. }
  71. function extractId(href) {
  72. return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain
  73. .replace(/[\?\&]livereload=\w+/, '') // Remove LiveReload cachebuster
  74. .replace(/^\//, '') // Remove root /
  75. .replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
  76. .replace(/[^\.\w-]+/g, '-') // Replace illegal characters
  77. .replace(/\./g, ':'); // Replace dots with colons(for valid id)
  78. }
  79. function addDataAttr(options, tag) {
  80. if (!tag) {
  81. return;
  82. } // in case of tag is null or undefined
  83. for (var opt in tag.dataset) {
  84. if (tag.dataset.hasOwnProperty(opt)) {
  85. if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') {
  86. options[opt] = tag.dataset[opt];
  87. }
  88. else {
  89. try {
  90. options[opt] = JSON.parse(tag.dataset[opt]);
  91. }
  92. catch (_) { }
  93. }
  94. }
  95. }
  96. }
  97. var browser = {
  98. createCSS: function (document, styles, sheet) {
  99. // Strip the query-string
  100. var href = sheet.href || '';
  101. // If there is no title set, use the filename, minus the extension
  102. var id = "less:" + (sheet.title || extractId(href));
  103. // If this has already been inserted into the DOM, we may need to replace it
  104. var oldStyleNode = document.getElementById(id);
  105. var keepOldStyleNode = false;
  106. // Create a new stylesheet node for insertion or (if necessary) replacement
  107. var styleNode = document.createElement('style');
  108. styleNode.setAttribute('type', 'text/css');
  109. if (sheet.media) {
  110. styleNode.setAttribute('media', sheet.media);
  111. }
  112. styleNode.id = id;
  113. if (!styleNode.styleSheet) {
  114. styleNode.appendChild(document.createTextNode(styles));
  115. // If new contents match contents of oldStyleNode, don't replace oldStyleNode
  116. keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
  117. oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
  118. }
  119. var head = document.getElementsByTagName('head')[0];
  120. // If there is no oldStyleNode, just append; otherwise, only append if we need
  121. // to replace oldStyleNode with an updated stylesheet
  122. if (oldStyleNode === null || keepOldStyleNode === false) {
  123. var nextEl = sheet && sheet.nextSibling || null;
  124. if (nextEl) {
  125. nextEl.parentNode.insertBefore(styleNode, nextEl);
  126. }
  127. else {
  128. head.appendChild(styleNode);
  129. }
  130. }
  131. if (oldStyleNode && keepOldStyleNode === false) {
  132. oldStyleNode.parentNode.removeChild(oldStyleNode);
  133. }
  134. // For IE.
  135. // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
  136. // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
  137. if (styleNode.styleSheet) {
  138. try {
  139. styleNode.styleSheet.cssText = styles;
  140. }
  141. catch (e) {
  142. throw new Error('Couldn\'t reassign styleSheet.cssText.');
  143. }
  144. }
  145. },
  146. currentScript: function (window) {
  147. var document = window.document;
  148. return document.currentScript || (function () {
  149. var scripts = document.getElementsByTagName('script');
  150. return scripts[scripts.length - 1];
  151. })();
  152. }
  153. };
  154. var addDefaultOptions = (function (window, options) {
  155. // use options from the current script tag data attribues
  156. addDataAttr(options, browser.currentScript(window));
  157. if (options.isFileProtocol === undefined) {
  158. options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
  159. }
  160. // Load styles asynchronously (default: false)
  161. //
  162. // This is set to `false` by default, so that the body
  163. // doesn't start loading before the stylesheets are parsed.
  164. // Setting this to `true` can result in flickering.
  165. //
  166. options.async = options.async || false;
  167. options.fileAsync = options.fileAsync || false;
  168. // Interval between watch polls
  169. options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
  170. options.env = options.env || (window.location.hostname == '127.0.0.1' ||
  171. window.location.hostname == '0.0.0.0' ||
  172. window.location.hostname == 'localhost' ||
  173. (window.location.port &&
  174. window.location.port.length > 0) ||
  175. options.isFileProtocol ? 'development'
  176. : 'production');
  177. var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
  178. if (dumpLineNumbers) {
  179. options.dumpLineNumbers = dumpLineNumbers[1];
  180. }
  181. if (options.useFileCache === undefined) {
  182. options.useFileCache = true;
  183. }
  184. if (options.onReady === undefined) {
  185. options.onReady = true;
  186. }
  187. if (options.relativeUrls) {
  188. options.rewriteUrls = 'all';
  189. }
  190. });
  191. var logger$1 = {
  192. error: function (msg) {
  193. this._fireEvent('error', msg);
  194. },
  195. warn: function (msg) {
  196. this._fireEvent('warn', msg);
  197. },
  198. info: function (msg) {
  199. this._fireEvent('info', msg);
  200. },
  201. debug: function (msg) {
  202. this._fireEvent('debug', msg);
  203. },
  204. addListener: function (listener) {
  205. this._listeners.push(listener);
  206. },
  207. removeListener: function (listener) {
  208. for (var i = 0; i < this._listeners.length; i++) {
  209. if (this._listeners[i] === listener) {
  210. this._listeners.splice(i, 1);
  211. return;
  212. }
  213. }
  214. },
  215. _fireEvent: function (type, msg) {
  216. for (var i = 0; i < this._listeners.length; i++) {
  217. var logFunction = this._listeners[i][type];
  218. if (logFunction) {
  219. logFunction(msg);
  220. }
  221. }
  222. },
  223. _listeners: []
  224. };
  225. /**
  226. * @todo Document why this abstraction exists, and the relationship between
  227. * environment, file managers, and plugin manager
  228. */
  229. var Environment = /** @class */ (function () {
  230. function Environment(externalEnvironment, fileManagers) {
  231. this.fileManagers = fileManagers || [];
  232. externalEnvironment = externalEnvironment || {};
  233. var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
  234. var requiredFunctions = [];
  235. var functions = requiredFunctions.concat(optionalFunctions);
  236. for (var i = 0; i < functions.length; i++) {
  237. var propName = functions[i];
  238. var environmentFunc = externalEnvironment[propName];
  239. if (environmentFunc) {
  240. this[propName] = environmentFunc.bind(externalEnvironment);
  241. }
  242. else if (i < requiredFunctions.length) {
  243. this.warn("missing required function in environment - " + propName);
  244. }
  245. }
  246. }
  247. Environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) {
  248. if (!filename) {
  249. logger$1.warn('getFileManager called with no filename.. Please report this issue. continuing.');
  250. }
  251. if (currentDirectory == null) {
  252. logger$1.warn('getFileManager called with null directory.. Please report this issue. continuing.');
  253. }
  254. var fileManagers = this.fileManagers;
  255. if (options.pluginManager) {
  256. fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
  257. }
  258. for (var i = fileManagers.length - 1; i >= 0; i--) {
  259. var fileManager = fileManagers[i];
  260. if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
  261. return fileManager;
  262. }
  263. }
  264. return null;
  265. };
  266. Environment.prototype.addFileManager = function (fileManager) {
  267. this.fileManagers.push(fileManager);
  268. };
  269. Environment.prototype.clearFileManagers = function () {
  270. this.fileManagers = [];
  271. };
  272. return Environment;
  273. }());
  274. var colors = {
  275. 'aliceblue': '#f0f8ff',
  276. 'antiquewhite': '#faebd7',
  277. 'aqua': '#00ffff',
  278. 'aquamarine': '#7fffd4',
  279. 'azure': '#f0ffff',
  280. 'beige': '#f5f5dc',
  281. 'bisque': '#ffe4c4',
  282. 'black': '#000000',
  283. 'blanchedalmond': '#ffebcd',
  284. 'blue': '#0000ff',
  285. 'blueviolet': '#8a2be2',
  286. 'brown': '#a52a2a',
  287. 'burlywood': '#deb887',
  288. 'cadetblue': '#5f9ea0',
  289. 'chartreuse': '#7fff00',
  290. 'chocolate': '#d2691e',
  291. 'coral': '#ff7f50',
  292. 'cornflowerblue': '#6495ed',
  293. 'cornsilk': '#fff8dc',
  294. 'crimson': '#dc143c',
  295. 'cyan': '#00ffff',
  296. 'darkblue': '#00008b',
  297. 'darkcyan': '#008b8b',
  298. 'darkgoldenrod': '#b8860b',
  299. 'darkgray': '#a9a9a9',
  300. 'darkgrey': '#a9a9a9',
  301. 'darkgreen': '#006400',
  302. 'darkkhaki': '#bdb76b',
  303. 'darkmagenta': '#8b008b',
  304. 'darkolivegreen': '#556b2f',
  305. 'darkorange': '#ff8c00',
  306. 'darkorchid': '#9932cc',
  307. 'darkred': '#8b0000',
  308. 'darksalmon': '#e9967a',
  309. 'darkseagreen': '#8fbc8f',
  310. 'darkslateblue': '#483d8b',
  311. 'darkslategray': '#2f4f4f',
  312. 'darkslategrey': '#2f4f4f',
  313. 'darkturquoise': '#00ced1',
  314. 'darkviolet': '#9400d3',
  315. 'deeppink': '#ff1493',
  316. 'deepskyblue': '#00bfff',
  317. 'dimgray': '#696969',
  318. 'dimgrey': '#696969',
  319. 'dodgerblue': '#1e90ff',
  320. 'firebrick': '#b22222',
  321. 'floralwhite': '#fffaf0',
  322. 'forestgreen': '#228b22',
  323. 'fuchsia': '#ff00ff',
  324. 'gainsboro': '#dcdcdc',
  325. 'ghostwhite': '#f8f8ff',
  326. 'gold': '#ffd700',
  327. 'goldenrod': '#daa520',
  328. 'gray': '#808080',
  329. 'grey': '#808080',
  330. 'green': '#008000',
  331. 'greenyellow': '#adff2f',
  332. 'honeydew': '#f0fff0',
  333. 'hotpink': '#ff69b4',
  334. 'indianred': '#cd5c5c',
  335. 'indigo': '#4b0082',
  336. 'ivory': '#fffff0',
  337. 'khaki': '#f0e68c',
  338. 'lavender': '#e6e6fa',
  339. 'lavenderblush': '#fff0f5',
  340. 'lawngreen': '#7cfc00',
  341. 'lemonchiffon': '#fffacd',
  342. 'lightblue': '#add8e6',
  343. 'lightcoral': '#f08080',
  344. 'lightcyan': '#e0ffff',
  345. 'lightgoldenrodyellow': '#fafad2',
  346. 'lightgray': '#d3d3d3',
  347. 'lightgrey': '#d3d3d3',
  348. 'lightgreen': '#90ee90',
  349. 'lightpink': '#ffb6c1',
  350. 'lightsalmon': '#ffa07a',
  351. 'lightseagreen': '#20b2aa',
  352. 'lightskyblue': '#87cefa',
  353. 'lightslategray': '#778899',
  354. 'lightslategrey': '#778899',
  355. 'lightsteelblue': '#b0c4de',
  356. 'lightyellow': '#ffffe0',
  357. 'lime': '#00ff00',
  358. 'limegreen': '#32cd32',
  359. 'linen': '#faf0e6',
  360. 'magenta': '#ff00ff',
  361. 'maroon': '#800000',
  362. 'mediumaquamarine': '#66cdaa',
  363. 'mediumblue': '#0000cd',
  364. 'mediumorchid': '#ba55d3',
  365. 'mediumpurple': '#9370d8',
  366. 'mediumseagreen': '#3cb371',
  367. 'mediumslateblue': '#7b68ee',
  368. 'mediumspringgreen': '#00fa9a',
  369. 'mediumturquoise': '#48d1cc',
  370. 'mediumvioletred': '#c71585',
  371. 'midnightblue': '#191970',
  372. 'mintcream': '#f5fffa',
  373. 'mistyrose': '#ffe4e1',
  374. 'moccasin': '#ffe4b5',
  375. 'navajowhite': '#ffdead',
  376. 'navy': '#000080',
  377. 'oldlace': '#fdf5e6',
  378. 'olive': '#808000',
  379. 'olivedrab': '#6b8e23',
  380. 'orange': '#ffa500',
  381. 'orangered': '#ff4500',
  382. 'orchid': '#da70d6',
  383. 'palegoldenrod': '#eee8aa',
  384. 'palegreen': '#98fb98',
  385. 'paleturquoise': '#afeeee',
  386. 'palevioletred': '#d87093',
  387. 'papayawhip': '#ffefd5',
  388. 'peachpuff': '#ffdab9',
  389. 'peru': '#cd853f',
  390. 'pink': '#ffc0cb',
  391. 'plum': '#dda0dd',
  392. 'powderblue': '#b0e0e6',
  393. 'purple': '#800080',
  394. 'rebeccapurple': '#663399',
  395. 'red': '#ff0000',
  396. 'rosybrown': '#bc8f8f',
  397. 'royalblue': '#4169e1',
  398. 'saddlebrown': '#8b4513',
  399. 'salmon': '#fa8072',
  400. 'sandybrown': '#f4a460',
  401. 'seagreen': '#2e8b57',
  402. 'seashell': '#fff5ee',
  403. 'sienna': '#a0522d',
  404. 'silver': '#c0c0c0',
  405. 'skyblue': '#87ceeb',
  406. 'slateblue': '#6a5acd',
  407. 'slategray': '#708090',
  408. 'slategrey': '#708090',
  409. 'snow': '#fffafa',
  410. 'springgreen': '#00ff7f',
  411. 'steelblue': '#4682b4',
  412. 'tan': '#d2b48c',
  413. 'teal': '#008080',
  414. 'thistle': '#d8bfd8',
  415. 'tomato': '#ff6347',
  416. 'turquoise': '#40e0d0',
  417. 'violet': '#ee82ee',
  418. 'wheat': '#f5deb3',
  419. 'white': '#ffffff',
  420. 'whitesmoke': '#f5f5f5',
  421. 'yellow': '#ffff00',
  422. 'yellowgreen': '#9acd32'
  423. };
  424. var unitConversions = {
  425. length: {
  426. 'm': 1,
  427. 'cm': 0.01,
  428. 'mm': 0.001,
  429. 'in': 0.0254,
  430. 'px': 0.0254 / 96,
  431. 'pt': 0.0254 / 72,
  432. 'pc': 0.0254 / 72 * 12
  433. },
  434. duration: {
  435. 's': 1,
  436. 'ms': 0.001
  437. },
  438. angle: {
  439. 'rad': 1 / (2 * Math.PI),
  440. 'deg': 1 / 360,
  441. 'grad': 1 / 400,
  442. 'turn': 1
  443. }
  444. };
  445. var data = { colors: colors, unitConversions: unitConversions };
  446. /**
  447. * The reason why Node is a class and other nodes simply do not extend
  448. * from Node (since we're transpiling) is due to this issue:
  449. *
  450. * https://github.com/less/less.js/issues/3434
  451. */
  452. var Node = /** @class */ (function () {
  453. function Node() {
  454. this.parent = null;
  455. this.visibilityBlocks = undefined;
  456. this.nodeVisible = undefined;
  457. this.rootNode = null;
  458. this.parsed = null;
  459. }
  460. Object.defineProperty(Node.prototype, "currentFileInfo", {
  461. get: function () {
  462. return this.fileInfo();
  463. },
  464. enumerable: false,
  465. configurable: true
  466. });
  467. Object.defineProperty(Node.prototype, "index", {
  468. get: function () {
  469. return this.getIndex();
  470. },
  471. enumerable: false,
  472. configurable: true
  473. });
  474. Node.prototype.setParent = function (nodes, parent) {
  475. function set(node) {
  476. if (node && node instanceof Node) {
  477. node.parent = parent;
  478. }
  479. }
  480. if (Array.isArray(nodes)) {
  481. nodes.forEach(set);
  482. }
  483. else {
  484. set(nodes);
  485. }
  486. };
  487. Node.prototype.getIndex = function () {
  488. return this._index || (this.parent && this.parent.getIndex()) || 0;
  489. };
  490. Node.prototype.fileInfo = function () {
  491. return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
  492. };
  493. Node.prototype.isRulesetLike = function () { return false; };
  494. Node.prototype.toCSS = function (context) {
  495. var strs = [];
  496. this.genCSS(context, {
  497. add: function (chunk, fileInfo, index) {
  498. strs.push(chunk);
  499. },
  500. isEmpty: function () {
  501. return strs.length === 0;
  502. }
  503. });
  504. return strs.join('');
  505. };
  506. Node.prototype.genCSS = function (context, output) {
  507. output.add(this.value);
  508. };
  509. Node.prototype.accept = function (visitor) {
  510. this.value = visitor.visit(this.value);
  511. };
  512. Node.prototype.eval = function () { return this; };
  513. Node.prototype._operate = function (context, op, a, b) {
  514. switch (op) {
  515. case '+': return a + b;
  516. case '-': return a - b;
  517. case '*': return a * b;
  518. case '/': return a / b;
  519. }
  520. };
  521. Node.prototype.fround = function (context, value) {
  522. var precision = context && context.numPrecision;
  523. // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
  524. return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
  525. };
  526. Node.compare = function (a, b) {
  527. /* returns:
  528. -1: a < b
  529. 0: a = b
  530. 1: a > b
  531. and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
  532. if ((a.compare) &&
  533. // for "symmetric results" force toCSS-based comparison
  534. // of Quoted or Anonymous if either value is one of those
  535. !(b.type === 'Quoted' || b.type === 'Anonymous')) {
  536. return a.compare(b);
  537. }
  538. else if (b.compare) {
  539. return -b.compare(a);
  540. }
  541. else if (a.type !== b.type) {
  542. return undefined;
  543. }
  544. a = a.value;
  545. b = b.value;
  546. if (!Array.isArray(a)) {
  547. return a === b ? 0 : undefined;
  548. }
  549. if (a.length !== b.length) {
  550. return undefined;
  551. }
  552. for (var i = 0; i < a.length; i++) {
  553. if (Node.compare(a[i], b[i]) !== 0) {
  554. return undefined;
  555. }
  556. }
  557. return 0;
  558. };
  559. Node.numericCompare = function (a, b) {
  560. return a < b ? -1
  561. : a === b ? 0
  562. : a > b ? 1 : undefined;
  563. };
  564. // Returns true if this node represents root of ast imported by reference
  565. Node.prototype.blocksVisibility = function () {
  566. if (this.visibilityBlocks == null) {
  567. this.visibilityBlocks = 0;
  568. }
  569. return this.visibilityBlocks !== 0;
  570. };
  571. Node.prototype.addVisibilityBlock = function () {
  572. if (this.visibilityBlocks == null) {
  573. this.visibilityBlocks = 0;
  574. }
  575. this.visibilityBlocks = this.visibilityBlocks + 1;
  576. };
  577. Node.prototype.removeVisibilityBlock = function () {
  578. if (this.visibilityBlocks == null) {
  579. this.visibilityBlocks = 0;
  580. }
  581. this.visibilityBlocks = this.visibilityBlocks - 1;
  582. };
  583. // Turns on node visibility - if called node will be shown in output regardless
  584. // of whether it comes from import by reference or not
  585. Node.prototype.ensureVisibility = function () {
  586. this.nodeVisible = true;
  587. };
  588. // Turns off node visibility - if called node will NOT be shown in output regardless
  589. // of whether it comes from import by reference or not
  590. Node.prototype.ensureInvisibility = function () {
  591. this.nodeVisible = false;
  592. };
  593. // return values:
  594. // false - the node must not be visible
  595. // true - the node must be visible
  596. // undefined or null - the node has the same visibility as its parent
  597. Node.prototype.isVisible = function () {
  598. return this.nodeVisible;
  599. };
  600. Node.prototype.visibilityInfo = function () {
  601. return {
  602. visibilityBlocks: this.visibilityBlocks,
  603. nodeVisible: this.nodeVisible
  604. };
  605. };
  606. Node.prototype.copyVisibilityInfo = function (info) {
  607. if (!info) {
  608. return;
  609. }
  610. this.visibilityBlocks = info.visibilityBlocks;
  611. this.nodeVisible = info.nodeVisible;
  612. };
  613. return Node;
  614. }());
  615. //
  616. // RGB Colors - #ff0014, #eee
  617. //
  618. var Color = function (rgb, a, originalForm) {
  619. var self = this;
  620. //
  621. // The end goal here, is to parse the arguments
  622. // into an integer triplet, such as `128, 255, 0`
  623. //
  624. // This facilitates operations and conversions.
  625. //
  626. if (Array.isArray(rgb)) {
  627. this.rgb = rgb;
  628. }
  629. else if (rgb.length >= 6) {
  630. this.rgb = [];
  631. rgb.match(/.{2}/g).map(function (c, i) {
  632. if (i < 3) {
  633. self.rgb.push(parseInt(c, 16));
  634. }
  635. else {
  636. self.alpha = (parseInt(c, 16)) / 255;
  637. }
  638. });
  639. }
  640. else {
  641. this.rgb = [];
  642. rgb.split('').map(function (c, i) {
  643. if (i < 3) {
  644. self.rgb.push(parseInt(c + c, 16));
  645. }
  646. else {
  647. self.alpha = (parseInt(c + c, 16)) / 255;
  648. }
  649. });
  650. }
  651. this.alpha = this.alpha || (typeof a === 'number' ? a : 1);
  652. if (typeof originalForm !== 'undefined') {
  653. this.value = originalForm;
  654. }
  655. };
  656. Color.prototype = Object.assign(new Node(), {
  657. type: 'Color',
  658. luma: function () {
  659. var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255;
  660. r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
  661. g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
  662. b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
  663. return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  664. },
  665. genCSS: function (context, output) {
  666. output.add(this.toCSS(context));
  667. },
  668. toCSS: function (context, doNotCompress) {
  669. var compress = context && context.compress && !doNotCompress;
  670. var color;
  671. var alpha;
  672. var colorFunction;
  673. var args = [];
  674. // `value` is set if this color was originally
  675. // converted from a named color string so we need
  676. // to respect this and try to output named color too.
  677. alpha = this.fround(context, this.alpha);
  678. if (this.value) {
  679. if (this.value.indexOf('rgb') === 0) {
  680. if (alpha < 1) {
  681. colorFunction = 'rgba';
  682. }
  683. }
  684. else if (this.value.indexOf('hsl') === 0) {
  685. if (alpha < 1) {
  686. colorFunction = 'hsla';
  687. }
  688. else {
  689. colorFunction = 'hsl';
  690. }
  691. }
  692. else {
  693. return this.value;
  694. }
  695. }
  696. else {
  697. if (alpha < 1) {
  698. colorFunction = 'rgba';
  699. }
  700. }
  701. switch (colorFunction) {
  702. case 'rgba':
  703. args = this.rgb.map(function (c) {
  704. return clamp$1(Math.round(c), 255);
  705. }).concat(clamp$1(alpha, 1));
  706. break;
  707. case 'hsla':
  708. args.push(clamp$1(alpha, 1));
  709. case 'hsl':
  710. color = this.toHSL();
  711. args = [
  712. this.fround(context, color.h),
  713. this.fround(context, color.s * 100) + "%",
  714. this.fround(context, color.l * 100) + "%"
  715. ].concat(args);
  716. }
  717. if (colorFunction) {
  718. // Values are capped between `0` and `255`, rounded and zero-padded.
  719. return colorFunction + "(" + args.join("," + (compress ? '' : ' ')) + ")";
  720. }
  721. color = this.toRGB();
  722. if (compress) {
  723. var splitcolor = color.split('');
  724. // Convert color to short format
  725. if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
  726. color = "#" + splitcolor[1] + splitcolor[3] + splitcolor[5];
  727. }
  728. }
  729. return color;
  730. },
  731. //
  732. // Operations have to be done per-channel, if not,
  733. // channels will spill onto each other. Once we have
  734. // our result, in the form of an integer triplet,
  735. // we create a new Color node to hold the result.
  736. //
  737. operate: function (context, op, other) {
  738. var rgb = new Array(3);
  739. var alpha = this.alpha * (1 - other.alpha) + other.alpha;
  740. for (var c = 0; c < 3; c++) {
  741. rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
  742. }
  743. return new Color(rgb, alpha);
  744. },
  745. toRGB: function () {
  746. return toHex(this.rgb);
  747. },
  748. toHSL: function () {
  749. var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
  750. var max = Math.max(r, g, b), min = Math.min(r, g, b);
  751. var h;
  752. var s;
  753. var l = (max + min) / 2;
  754. var d = max - min;
  755. if (max === min) {
  756. h = s = 0;
  757. }
  758. else {
  759. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  760. switch (max) {
  761. case r:
  762. h = (g - b) / d + (g < b ? 6 : 0);
  763. break;
  764. case g:
  765. h = (b - r) / d + 2;
  766. break;
  767. case b:
  768. h = (r - g) / d + 4;
  769. break;
  770. }
  771. h /= 6;
  772. }
  773. return { h: h * 360, s: s, l: l, a: a };
  774. },
  775. // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  776. toHSV: function () {
  777. var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
  778. var max = Math.max(r, g, b), min = Math.min(r, g, b);
  779. var h;
  780. var s;
  781. var v = max;
  782. var d = max - min;
  783. if (max === 0) {
  784. s = 0;
  785. }
  786. else {
  787. s = d / max;
  788. }
  789. if (max === min) {
  790. h = 0;
  791. }
  792. else {
  793. switch (max) {
  794. case r:
  795. h = (g - b) / d + (g < b ? 6 : 0);
  796. break;
  797. case g:
  798. h = (b - r) / d + 2;
  799. break;
  800. case b:
  801. h = (r - g) / d + 4;
  802. break;
  803. }
  804. h /= 6;
  805. }
  806. return { h: h * 360, s: s, v: v, a: a };
  807. },
  808. toARGB: function () {
  809. return toHex([this.alpha * 255].concat(this.rgb));
  810. },
  811. compare: function (x) {
  812. return (x.rgb &&
  813. x.rgb[0] === this.rgb[0] &&
  814. x.rgb[1] === this.rgb[1] &&
  815. x.rgb[2] === this.rgb[2] &&
  816. x.alpha === this.alpha) ? 0 : undefined;
  817. }
  818. });
  819. Color.fromKeyword = function (keyword) {
  820. var c;
  821. var key = keyword.toLowerCase();
  822. if (colors.hasOwnProperty(key)) {
  823. c = new Color(colors[key].slice(1));
  824. }
  825. else if (key === 'transparent') {
  826. c = new Color([0, 0, 0], 0);
  827. }
  828. if (c) {
  829. c.value = keyword;
  830. return c;
  831. }
  832. };
  833. function clamp$1(v, max) {
  834. return Math.min(Math.max(v, 0), max);
  835. }
  836. function toHex(v) {
  837. return "#" + v.map(function (c) {
  838. c = clamp$1(Math.round(c), 255);
  839. return (c < 16 ? '0' : '') + c.toString(16);
  840. }).join('');
  841. }
  842. var Paren = function (node) {
  843. this.value = node;
  844. };
  845. Paren.prototype = Object.assign(new Node(), {
  846. type: 'Paren',
  847. genCSS: function (context, output) {
  848. output.add('(');
  849. this.value.genCSS(context, output);
  850. output.add(')');
  851. },
  852. eval: function (context) {
  853. return new Paren(this.value.eval(context));
  854. }
  855. });
  856. var _noSpaceCombinators = {
  857. '': true,
  858. ' ': true,
  859. '|': true
  860. };
  861. var Combinator = function (value) {
  862. if (value === ' ') {
  863. this.value = ' ';
  864. this.emptyOrWhitespace = true;
  865. }
  866. else {
  867. this.value = value ? value.trim() : '';
  868. this.emptyOrWhitespace = this.value === '';
  869. }
  870. };
  871. Combinator.prototype = Object.assign(new Node(), {
  872. type: 'Combinator',
  873. genCSS: function (context, output) {
  874. var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' ';
  875. output.add(spaceOrEmpty + this.value + spaceOrEmpty);
  876. }
  877. });
  878. var Element = function (combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
  879. this.combinator = combinator instanceof Combinator ?
  880. combinator : new Combinator(combinator);
  881. if (typeof value === 'string') {
  882. this.value = value.trim();
  883. }
  884. else if (value) {
  885. this.value = value;
  886. }
  887. else {
  888. this.value = '';
  889. }
  890. this.isVariable = isVariable;
  891. this._index = index;
  892. this._fileInfo = currentFileInfo;
  893. this.copyVisibilityInfo(visibilityInfo);
  894. this.setParent(this.combinator, this);
  895. };
  896. Element.prototype = Object.assign(new Node(), {
  897. type: 'Element',
  898. accept: function (visitor) {
  899. var value = this.value;
  900. this.combinator = visitor.visit(this.combinator);
  901. if (typeof value === 'object') {
  902. this.value = visitor.visit(value);
  903. }
  904. },
  905. eval: function (context) {
  906. return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  907. },
  908. clone: function () {
  909. return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  910. },
  911. genCSS: function (context, output) {
  912. output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
  913. },
  914. toCSS: function (context) {
  915. context = context || {};
  916. var value = this.value;
  917. var firstSelector = context.firstSelector;
  918. if (value instanceof Paren) {
  919. // selector in parens should not be affected by outer selector
  920. // flags (breaks only interpolated selectors - see #1973)
  921. context.firstSelector = true;
  922. }
  923. value = value.toCSS ? value.toCSS(context) : value;
  924. context.firstSelector = firstSelector;
  925. if (value === '' && this.combinator.value.charAt(0) === '&') {
  926. return '';
  927. }
  928. else {
  929. return this.combinator.toCSS(context) + value;
  930. }
  931. }
  932. });
  933. var Math$1 = {
  934. ALWAYS: 0,
  935. PARENS_DIVISION: 1,
  936. PARENS: 2
  937. // removed - STRICT_LEGACY: 3
  938. };
  939. var RewriteUrls = {
  940. OFF: 0,
  941. LOCAL: 1,
  942. ALL: 2
  943. };
  944. /**
  945. * Returns the object type of the given payload
  946. *
  947. * @param {*} payload
  948. * @returns {string}
  949. */
  950. function getType(payload) {
  951. return Object.prototype.toString.call(payload).slice(8, -1);
  952. }
  953. /**
  954. * Returns whether the payload is a plain JavaScript object (excluding special classes or objects with other prototypes)
  955. *
  956. * @param {*} payload
  957. * @returns {payload is Record<string, any>}
  958. */
  959. function isPlainObject(payload) {
  960. if (getType(payload) !== 'Object')
  961. return false;
  962. return payload.constructor === Object && Object.getPrototypeOf(payload) === Object.prototype;
  963. }
  964. /**
  965. * Returns whether the payload is an array
  966. *
  967. * @param {any} payload
  968. * @returns {payload is any[]}
  969. */
  970. function isArray(payload) {
  971. return getType(payload) === 'Array';
  972. }
  973. /*! *****************************************************************************
  974. Copyright (c) Microsoft Corporation. All rights reserved.
  975. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  976. this file except in compliance with the License. You may obtain a copy of the
  977. License at http://www.apache.org/licenses/LICENSE-2.0
  978. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  979. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  980. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  981. MERCHANTABLITY OR NON-INFRINGEMENT.
  982. See the Apache Version 2.0 License for specific language governing permissions
  983. and limitations under the License.
  984. ***************************************************************************** */
  985. function __spreadArrays() {
  986. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  987. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  988. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  989. r[k] = a[j];
  990. return r;
  991. }
  992. function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
  993. var propType = {}.propertyIsEnumerable.call(originalObject, key)
  994. ? 'enumerable'
  995. : 'nonenumerable';
  996. if (propType === 'enumerable')
  997. carry[key] = newVal;
  998. if (includeNonenumerable && propType === 'nonenumerable') {
  999. Object.defineProperty(carry, key, {
  1000. value: newVal,
  1001. enumerable: false,
  1002. writable: true,
  1003. configurable: true,
  1004. });
  1005. }
  1006. }
  1007. /**
  1008. * Copy (clone) an object and all its props recursively to get rid of any prop referenced of the original object. Arrays are also cloned, however objects inside arrays are still linked.
  1009. *
  1010. * @export
  1011. * @template T
  1012. * @param {T} target Target can be anything
  1013. * @param {Options} [options={}] Options can be `props` or `nonenumerable`
  1014. * @returns {T} the target with replaced values
  1015. * @export
  1016. */
  1017. function copy(target, options) {
  1018. if (options === void 0) { options = {}; }
  1019. if (isArray(target))
  1020. return target.map(function (i) { return copy(i, options); });
  1021. if (!isPlainObject(target))
  1022. return target;
  1023. var props = Object.getOwnPropertyNames(target);
  1024. var symbols = Object.getOwnPropertySymbols(target);
  1025. return __spreadArrays(props, symbols).reduce(function (carry, key) {
  1026. if (isArray(options.props) && !options.props.includes(key)) {
  1027. return carry;
  1028. }
  1029. var val = target[key];
  1030. var newVal = copy(val, options);
  1031. assignProp(carry, key, newVal, target, options.nonenumerable);
  1032. return carry;
  1033. }, {});
  1034. }
  1035. /* jshint proto: true */
  1036. function getLocation(index, inputStream) {
  1037. var n = index + 1;
  1038. var line = null;
  1039. var column = -1;
  1040. while (--n >= 0 && inputStream.charAt(n) !== '\n') {
  1041. column++;
  1042. }
  1043. if (typeof index === 'number') {
  1044. line = (inputStream.slice(0, index).match(/\n/g) || '').length;
  1045. }
  1046. return {
  1047. line: line,
  1048. column: column
  1049. };
  1050. }
  1051. function copyArray(arr) {
  1052. var i;
  1053. var length = arr.length;
  1054. var copy = new Array(length);
  1055. for (i = 0; i < length; i++) {
  1056. copy[i] = arr[i];
  1057. }
  1058. return copy;
  1059. }
  1060. function clone(obj) {
  1061. var cloned = {};
  1062. for (var prop in obj) {
  1063. if (obj.hasOwnProperty(prop)) {
  1064. cloned[prop] = obj[prop];
  1065. }
  1066. }
  1067. return cloned;
  1068. }
  1069. function defaults(obj1, obj2) {
  1070. var newObj = obj2 || {};
  1071. if (!obj2._defaults) {
  1072. newObj = {};
  1073. var defaults_1 = copy(obj1);
  1074. newObj._defaults = defaults_1;
  1075. var cloned = obj2 ? copy(obj2) : {};
  1076. Object.assign(newObj, defaults_1, cloned);
  1077. }
  1078. return newObj;
  1079. }
  1080. function copyOptions(obj1, obj2) {
  1081. if (obj2 && obj2._defaults) {
  1082. return obj2;
  1083. }
  1084. var opts = defaults(obj1, obj2);
  1085. if (opts.strictMath) {
  1086. opts.math = Math$1.PARENS;
  1087. }
  1088. // Back compat with changed relativeUrls option
  1089. if (opts.relativeUrls) {
  1090. opts.rewriteUrls = RewriteUrls.ALL;
  1091. }
  1092. if (typeof opts.math === 'string') {
  1093. switch (opts.math.toLowerCase()) {
  1094. case 'always':
  1095. opts.math = Math$1.ALWAYS;
  1096. break;
  1097. case 'parens-division':
  1098. opts.math = Math$1.PARENS_DIVISION;
  1099. break;
  1100. case 'strict':
  1101. case 'parens':
  1102. opts.math = Math$1.PARENS;
  1103. break;
  1104. default:
  1105. opts.math = Math$1.PARENS;
  1106. }
  1107. }
  1108. if (typeof opts.rewriteUrls === 'string') {
  1109. switch (opts.rewriteUrls.toLowerCase()) {
  1110. case 'off':
  1111. opts.rewriteUrls = RewriteUrls.OFF;
  1112. break;
  1113. case 'local':
  1114. opts.rewriteUrls = RewriteUrls.LOCAL;
  1115. break;
  1116. case 'all':
  1117. opts.rewriteUrls = RewriteUrls.ALL;
  1118. break;
  1119. }
  1120. }
  1121. return opts;
  1122. }
  1123. function merge(obj1, obj2) {
  1124. for (var prop in obj2) {
  1125. if (obj2.hasOwnProperty(prop)) {
  1126. obj1[prop] = obj2[prop];
  1127. }
  1128. }
  1129. return obj1;
  1130. }
  1131. function flattenArray(arr, result) {
  1132. if (result === void 0) { result = []; }
  1133. for (var i = 0, length_1 = arr.length; i < length_1; i++) {
  1134. var value = arr[i];
  1135. if (Array.isArray(value)) {
  1136. flattenArray(value, result);
  1137. }
  1138. else {
  1139. if (value !== undefined) {
  1140. result.push(value);
  1141. }
  1142. }
  1143. }
  1144. return result;
  1145. }
  1146. var utils = /*#__PURE__*/Object.freeze({
  1147. __proto__: null,
  1148. getLocation: getLocation,
  1149. copyArray: copyArray,
  1150. clone: clone,
  1151. defaults: defaults,
  1152. copyOptions: copyOptions,
  1153. merge: merge,
  1154. flattenArray: flattenArray
  1155. });
  1156. var anonymousFunc = /(<anonymous>|Function):(\d+):(\d+)/;
  1157. /**
  1158. * This is a centralized class of any error that could be thrown internally (mostly by the parser).
  1159. * Besides standard .message it keeps some additional data like a path to the file where the error
  1160. * occurred along with line and column numbers.
  1161. *
  1162. * @class
  1163. * @extends Error
  1164. * @type {module.LessError}
  1165. *
  1166. * @prop {string} type
  1167. * @prop {string} filename
  1168. * @prop {number} index
  1169. * @prop {number} line
  1170. * @prop {number} column
  1171. * @prop {number} callLine
  1172. * @prop {number} callExtract
  1173. * @prop {string[]} extract
  1174. *
  1175. * @param {Object} e - An error object to wrap around or just a descriptive object
  1176. * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
  1177. * @param {string} [currentFilename]
  1178. */
  1179. var LessError = function (e, fileContentMap, currentFilename) {
  1180. Error.call(this);
  1181. var filename = e.filename || currentFilename;
  1182. this.message = e.message;
  1183. this.stack = e.stack;
  1184. if (fileContentMap && filename) {
  1185. var input = fileContentMap.contents[filename];
  1186. var loc = getLocation(e.index, input);
  1187. var line = loc.line;
  1188. var col = loc.column;
  1189. var callLine = e.call && getLocation(e.call, input).line;
  1190. var lines = input ? input.split('\n') : '';
  1191. this.type = e.type || 'Syntax';
  1192. this.filename = filename;
  1193. this.index = e.index;
  1194. this.line = typeof line === 'number' ? line + 1 : null;
  1195. this.column = col;
  1196. if (!this.line && this.stack) {
  1197. var found = this.stack.match(anonymousFunc);
  1198. /**
  1199. * We have to figure out how this environment stringifies anonymous functions
  1200. * so we can correctly map plugin errors.
  1201. *
  1202. * Note, in Node 8, the output of anonymous funcs varied based on parameters
  1203. * being present or not, so we inject dummy params.
  1204. */
  1205. var func = new Function('a', 'throw new Error()');
  1206. var lineAdjust = 0;
  1207. try {
  1208. func();
  1209. }
  1210. catch (e) {
  1211. var match = e.stack.match(anonymousFunc);
  1212. var line = parseInt(match[2]);
  1213. lineAdjust = 1 - line;
  1214. }
  1215. if (found) {
  1216. if (found[2]) {
  1217. this.line = parseInt(found[2]) + lineAdjust;
  1218. }
  1219. if (found[3]) {
  1220. this.column = parseInt(found[3]);
  1221. }
  1222. }
  1223. }
  1224. this.callLine = callLine + 1;
  1225. this.callExtract = lines[callLine];
  1226. this.extract = [
  1227. lines[this.line - 2],
  1228. lines[this.line - 1],
  1229. lines[this.line]
  1230. ];
  1231. }
  1232. };
  1233. if (typeof Object.create === 'undefined') {
  1234. var F = function () { };
  1235. F.prototype = Error.prototype;
  1236. LessError.prototype = new F();
  1237. }
  1238. else {
  1239. LessError.prototype = Object.create(Error.prototype);
  1240. }
  1241. LessError.prototype.constructor = LessError;
  1242. /**
  1243. * An overridden version of the default Object.prototype.toString
  1244. * which uses additional information to create a helpful message.
  1245. *
  1246. * @param {Object} options
  1247. * @returns {string}
  1248. */
  1249. LessError.prototype.toString = function (options) {
  1250. options = options || {};
  1251. var message = '';
  1252. var extract = this.extract || [];
  1253. var error = [];
  1254. var stylize = function (str) { return str; };
  1255. if (options.stylize) {
  1256. var type = typeof options.stylize;
  1257. if (type !== 'function') {
  1258. throw Error("options.stylize should be a function, got a " + type + "!");
  1259. }
  1260. stylize = options.stylize;
  1261. }
  1262. if (this.line !== null) {
  1263. if (typeof extract[0] === 'string') {
  1264. error.push(stylize(this.line - 1 + " " + extract[0], 'grey'));
  1265. }
  1266. if (typeof extract[1] === 'string') {
  1267. var errorTxt = this.line + " ";
  1268. if (extract[1]) {
  1269. errorTxt += extract[1].slice(0, this.column) +
  1270. stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') +
  1271. extract[1].slice(this.column + 1), 'red'), 'inverse');
  1272. }
  1273. error.push(errorTxt);
  1274. }
  1275. if (typeof extract[2] === 'string') {
  1276. error.push(stylize(this.line + 1 + " " + extract[2], 'grey'));
  1277. }
  1278. error = error.join('\n') + stylize('', 'reset') + "\n";
  1279. }
  1280. message += stylize(this.type + "Error: " + this.message, 'red');
  1281. if (this.filename) {
  1282. message += stylize(' in ', 'red') + this.filename;
  1283. }
  1284. if (this.line) {
  1285. message += stylize(" on line " + this.line + ", column " + (this.column + 1) + ":", 'grey');
  1286. }
  1287. message += "\n" + error;
  1288. if (this.callLine) {
  1289. message += stylize('from ', 'red') + (this.filename || '') + "/n";
  1290. message += stylize(this.callLine, 'grey') + " " + this.callExtract + "/n";
  1291. }
  1292. return message;
  1293. };
  1294. var Selector = function (elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
  1295. this.extendList = extendList;
  1296. this.condition = condition;
  1297. this.evaldCondition = !condition;
  1298. this._index = index;
  1299. this._fileInfo = currentFileInfo;
  1300. this.elements = this.getElements(elements);
  1301. this.mixinElements_ = undefined;
  1302. this.copyVisibilityInfo(visibilityInfo);
  1303. this.setParent(this.elements, this);
  1304. };
  1305. Selector.prototype = Object.assign(new Node(), {
  1306. type: 'Selector',
  1307. accept: function (visitor) {
  1308. if (this.elements) {
  1309. this.elements = visitor.visitArray(this.elements);
  1310. }
  1311. if (this.extendList) {
  1312. this.extendList = visitor.visitArray(this.extendList);
  1313. }
  1314. if (this.condition) {
  1315. this.condition = visitor.visit(this.condition);
  1316. }
  1317. },
  1318. createDerived: function (elements, extendList, evaldCondition) {
  1319. elements = this.getElements(elements);
  1320. var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  1321. newSelector.evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition;
  1322. newSelector.mediaEmpty = this.mediaEmpty;
  1323. return newSelector;
  1324. },
  1325. getElements: function (els) {
  1326. if (!els) {
  1327. return [new Element('', '&', false, this._index, this._fileInfo)];
  1328. }
  1329. if (typeof els === 'string') {
  1330. this.parse.parseNode(els, ['selector'], this._index, this._fileInfo, function (err, result) {
  1331. if (err) {
  1332. throw new LessError({
  1333. index: err.index,
  1334. message: err.message
  1335. }, this.parse.imports, this._fileInfo.filename);
  1336. }
  1337. els = result[0].elements;
  1338. });
  1339. }
  1340. return els;
  1341. },
  1342. createEmptySelectors: function () {
  1343. var el = new Element('', '&', false, this._index, this._fileInfo), sels = [new Selector([el], null, null, this._index, this._fileInfo)];
  1344. sels[0].mediaEmpty = true;
  1345. return sels;
  1346. },
  1347. match: function (other) {
  1348. var elements = this.elements;
  1349. var len = elements.length;
  1350. var olen;
  1351. var i;
  1352. other = other.mixinElements();
  1353. olen = other.length;
  1354. if (olen === 0 || len < olen) {
  1355. return 0;
  1356. }
  1357. else {
  1358. for (i = 0; i < olen; i++) {
  1359. if (elements[i].value !== other[i]) {
  1360. return 0;
  1361. }
  1362. }
  1363. }
  1364. return olen; // return number of matched elements
  1365. },
  1366. mixinElements: function () {
  1367. if (this.mixinElements_) {
  1368. return this.mixinElements_;
  1369. }
  1370. var elements = this.elements.map(function (v) {
  1371. return v.combinator.value + (v.value.value || v.value);
  1372. }).join('').match(/[,&#\*\.\w-]([\w-]|(\\.))*/g);
  1373. if (elements) {
  1374. if (elements[0] === '&') {
  1375. elements.shift();
  1376. }
  1377. }
  1378. else {
  1379. elements = [];
  1380. }
  1381. return (this.mixinElements_ = elements);
  1382. },
  1383. isJustParentSelector: function () {
  1384. return !this.mediaEmpty &&
  1385. this.elements.length === 1 &&
  1386. this.elements[0].value === '&' &&
  1387. (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
  1388. },
  1389. eval: function (context) {
  1390. var evaldCondition = this.condition && this.condition.eval(context);
  1391. var elements = this.elements;
  1392. var extendList = this.extendList;
  1393. elements = elements && elements.map(function (e) { return e.eval(context); });
  1394. extendList = extendList && extendList.map(function (extend) { return extend.eval(context); });
  1395. return this.createDerived(elements, extendList, evaldCondition);
  1396. },
  1397. genCSS: function (context, output) {
  1398. var i, element;
  1399. if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
  1400. output.add(' ', this.fileInfo(), this.getIndex());
  1401. }
  1402. for (i = 0; i < this.elements.length; i++) {
  1403. element = this.elements[i];
  1404. element.genCSS(context, output);
  1405. }
  1406. },
  1407. getIsOutput: function () {
  1408. return this.evaldCondition;
  1409. }
  1410. });
  1411. var Value = function (value) {
  1412. if (!value) {
  1413. throw new Error('Value requires an array argument');
  1414. }
  1415. if (!Array.isArray(value)) {
  1416. this.value = [value];
  1417. }
  1418. else {
  1419. this.value = value;
  1420. }
  1421. };
  1422. Value.prototype = Object.assign(new Node(), {
  1423. type: 'Value',
  1424. accept: function (visitor) {
  1425. if (this.value) {
  1426. this.value = visitor.visitArray(this.value);
  1427. }
  1428. },
  1429. eval: function (context) {
  1430. if (this.value.length === 1) {
  1431. return this.value[0].eval(context);
  1432. }
  1433. else {
  1434. return new Value(this.value.map(function (v) {
  1435. return v.eval(context);
  1436. }));
  1437. }
  1438. },
  1439. genCSS: function (context, output) {
  1440. var i;
  1441. for (i = 0; i < this.value.length; i++) {
  1442. this.value[i].genCSS(context, output);
  1443. if (i + 1 < this.value.length) {
  1444. output.add((context && context.compress) ? ',' : ', ');
  1445. }
  1446. }
  1447. }
  1448. });
  1449. var Keyword = function (value) {
  1450. this.value = value;
  1451. };
  1452. Keyword.prototype = Object.assign(new Node(), {
  1453. type: 'Keyword',
  1454. genCSS: function (context, output) {
  1455. if (this.value === '%') {
  1456. throw { type: 'Syntax', message: 'Invalid % without number' };
  1457. }
  1458. output.add(this.value);
  1459. }
  1460. });
  1461. Keyword.True = new Keyword('true');
  1462. Keyword.False = new Keyword('false');
  1463. var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
  1464. this.value = value;
  1465. this._index = index;
  1466. this._fileInfo = currentFileInfo;
  1467. this.mapLines = mapLines;
  1468. this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
  1469. this.allowRoot = true;
  1470. this.copyVisibilityInfo(visibilityInfo);
  1471. };
  1472. Anonymous.prototype = Object.assign(new Node(), {
  1473. type: 'Anonymous',
  1474. eval: function () {
  1475. return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
  1476. },
  1477. compare: function (other) {
  1478. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  1479. },
  1480. isRulesetLike: function () {
  1481. return this.rulesetLike;
  1482. },
  1483. genCSS: function (context, output) {
  1484. this.nodeVisible = Boolean(this.value);
  1485. if (this.nodeVisible) {
  1486. output.add(this.value, this._fileInfo, this._index, this.mapLines);
  1487. }
  1488. }
  1489. });
  1490. var MATH$1 = Math$1;
  1491. function evalName(context, name) {
  1492. var value = '';
  1493. var i;
  1494. var n = name.length;
  1495. var output = { add: function (s) { value += s; } };
  1496. for (i = 0; i < n; i++) {
  1497. name[i].eval(context).genCSS(context, output);
  1498. }
  1499. return value;
  1500. }
  1501. var Declaration = function (name, value, important, merge, index, currentFileInfo, inline, variable) {
  1502. this.name = name;
  1503. this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
  1504. this.important = important ? " " + important.trim() : '';
  1505. this.merge = merge;
  1506. this._index = index;
  1507. this._fileInfo = currentFileInfo;
  1508. this.inline = inline || false;
  1509. this.variable = (variable !== undefined) ? variable
  1510. : (name.charAt && (name.charAt(0) === '@'));
  1511. this.allowRoot = true;
  1512. this.setParent(this.value, this);
  1513. };
  1514. Declaration.prototype = Object.assign(new Node(), {
  1515. type: 'Declaration',
  1516. genCSS: function (context, output) {
  1517. output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
  1518. try {
  1519. this.value.genCSS(context, output);
  1520. }
  1521. catch (e) {
  1522. e.index = this._index;
  1523. e.filename = this._fileInfo.filename;
  1524. throw e;
  1525. }
  1526. output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index);
  1527. },
  1528. eval: function (context) {
  1529. var mathBypass = false, prevMath, name = this.name, evaldValue, variable = this.variable;
  1530. if (typeof name !== 'string') {
  1531. // expand 'primitive' name directly to get
  1532. // things faster (~10% for benchmark.less):
  1533. name = (name.length === 1) && (name[0] instanceof Keyword) ?
  1534. name[0].value : evalName(context, name);
  1535. variable = false; // never treat expanded interpolation as new variable name
  1536. }
  1537. // @todo remove when parens-division is default
  1538. if (name === 'font' && context.math === MATH$1.ALWAYS) {
  1539. mathBypass = true;
  1540. prevMath = context.math;
  1541. context.math = MATH$1.PARENS_DIVISION;
  1542. }
  1543. try {
  1544. context.importantScope.push({});
  1545. evaldValue = this.value.eval(context);
  1546. if (!this.variable && evaldValue.type === 'DetachedRuleset') {
  1547. throw { message: 'Rulesets cannot be evaluated on a property.',
  1548. index: this.getIndex(), filename: this.fileInfo().filename };
  1549. }
  1550. var important = this.important;
  1551. var importantResult = context.importantScope.pop();
  1552. if (!important && importantResult.important) {
  1553. important = importantResult.important;
  1554. }
  1555. return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
  1556. }
  1557. catch (e) {
  1558. if (typeof e.index !== 'number') {
  1559. e.index = this.getIndex();
  1560. e.filename = this.fileInfo().filename;
  1561. }
  1562. throw e;
  1563. }
  1564. finally {
  1565. if (mathBypass) {
  1566. context.math = prevMath;
  1567. }
  1568. }
  1569. },
  1570. makeImportant: function () {
  1571. return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
  1572. }
  1573. });
  1574. function asComment(ctx) {
  1575. return "/* line " + ctx.debugInfo.lineNumber + ", " + ctx.debugInfo.fileName + " */\n";
  1576. }
  1577. function asMediaQuery(ctx) {
  1578. var filenameWithProtocol = ctx.debugInfo.fileName;
  1579. if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
  1580. filenameWithProtocol = "file://" + filenameWithProtocol;
  1581. }
  1582. return "@media -sass-debug-info{filename{font-family:" + filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
  1583. if (a == '\\') {
  1584. a = '\/';
  1585. }
  1586. return "\\" + a;
  1587. }) + "}line{font-family:\\00003" + ctx.debugInfo.lineNumber + "}}\n";
  1588. }
  1589. function debugInfo(context, ctx, lineSeparator) {
  1590. var result = '';
  1591. if (context.dumpLineNumbers && !context.compress) {
  1592. switch (context.dumpLineNumbers) {
  1593. case 'comments':
  1594. result = asComment(ctx);
  1595. break;
  1596. case 'mediaquery':
  1597. result = asMediaQuery(ctx);
  1598. break;
  1599. case 'all':
  1600. result = asComment(ctx) + (lineSeparator || '') + asMediaQuery(ctx);
  1601. break;
  1602. }
  1603. }
  1604. return result;
  1605. }
  1606. var Comment = function (value, isLineComment, index, currentFileInfo) {
  1607. this.value = value;
  1608. this.isLineComment = isLineComment;
  1609. this._index = index;
  1610. this._fileInfo = currentFileInfo;
  1611. this.allowRoot = true;
  1612. };
  1613. Comment.prototype = Object.assign(new Node(), {
  1614. type: 'Comment',
  1615. genCSS: function (context, output) {
  1616. if (this.debugInfo) {
  1617. output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
  1618. }
  1619. output.add(this.value);
  1620. },
  1621. isSilent: function (context) {
  1622. var isCompressed = context.compress && this.value[2] !== '!';
  1623. return this.isLineComment || isCompressed;
  1624. }
  1625. });
  1626. var contexts = {};
  1627. var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
  1628. if (!original) {
  1629. return;
  1630. }
  1631. for (var i = 0; i < propertiesToCopy.length; i++) {
  1632. if (original.hasOwnProperty(propertiesToCopy[i])) {
  1633. destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
  1634. }
  1635. }
  1636. };
  1637. /*
  1638. parse is used whilst parsing
  1639. */
  1640. var parseCopyProperties = [
  1641. // options
  1642. 'paths',
  1643. 'rewriteUrls',
  1644. 'rootpath',
  1645. 'strictImports',
  1646. 'insecure',
  1647. 'dumpLineNumbers',
  1648. 'compress',
  1649. 'syncImport',
  1650. 'chunkInput',
  1651. 'mime',
  1652. 'useFileCache',
  1653. // context
  1654. 'processImports',
  1655. // Used by the import manager to stop multiple import visitors being created.
  1656. 'pluginManager' // Used as the plugin manager for the session
  1657. ];
  1658. contexts.Parse = function (options) {
  1659. copyFromOriginal(options, this, parseCopyProperties);
  1660. if (typeof this.paths === 'string') {
  1661. this.paths = [this.paths];
  1662. }
  1663. };
  1664. var evalCopyProperties = [
  1665. 'paths',
  1666. 'compress',
  1667. 'math',
  1668. 'strictUnits',
  1669. 'sourceMap',
  1670. 'importMultiple',
  1671. 'urlArgs',
  1672. 'javascriptEnabled',
  1673. 'pluginManager',
  1674. 'importantScope',
  1675. 'rewriteUrls' // option - whether to adjust URL's to be relative
  1676. ];
  1677. contexts.Eval = function (options, frames) {
  1678. copyFromOriginal(options, this, evalCopyProperties);
  1679. if (typeof this.paths === 'string') {
  1680. this.paths = [this.paths];
  1681. }
  1682. this.frames = frames || [];
  1683. this.importantScope = this.importantScope || [];
  1684. };
  1685. contexts.Eval.prototype.enterCalc = function () {
  1686. if (!this.calcStack) {
  1687. this.calcStack = [];
  1688. }
  1689. this.calcStack.push(true);
  1690. this.inCalc = true;
  1691. };
  1692. contexts.Eval.prototype.exitCalc = function () {
  1693. this.calcStack.pop();
  1694. if (!this.calcStack.length) {
  1695. this.inCalc = false;
  1696. }
  1697. };
  1698. contexts.Eval.prototype.inParenthesis = function () {
  1699. if (!this.parensStack) {
  1700. this.parensStack = [];
  1701. }
  1702. this.parensStack.push(true);
  1703. };
  1704. contexts.Eval.prototype.outOfParenthesis = function () {
  1705. this.parensStack.pop();
  1706. };
  1707. contexts.Eval.prototype.inCalc = false;
  1708. contexts.Eval.prototype.mathOn = true;
  1709. contexts.Eval.prototype.isMathOn = function (op) {
  1710. if (!this.mathOn) {
  1711. return false;
  1712. }
  1713. if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
  1714. return false;
  1715. }
  1716. if (this.math > Math$1.PARENS_DIVISION) {
  1717. return this.parensStack && this.parensStack.length;
  1718. }
  1719. return true;
  1720. };
  1721. contexts.Eval.prototype.pathRequiresRewrite = function (path) {
  1722. var isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
  1723. return isRelative(path);
  1724. };
  1725. contexts.Eval.prototype.rewritePath = function (path, rootpath) {
  1726. var newPath;
  1727. rootpath = rootpath || '';
  1728. newPath = this.normalizePath(rootpath + path);
  1729. // If a path was explicit relative and the rootpath was not an absolute path
  1730. // we must ensure that the new path is also explicit relative.
  1731. if (isPathLocalRelative(path) &&
  1732. isPathRelative(rootpath) &&
  1733. isPathLocalRelative(newPath) === false) {
  1734. newPath = "./" + newPath;
  1735. }
  1736. return newPath;
  1737. };
  1738. contexts.Eval.prototype.normalizePath = function (path) {
  1739. var segments = path.split('/').reverse();
  1740. var segment;
  1741. path = [];
  1742. while (segments.length !== 0) {
  1743. segment = segments.pop();
  1744. switch (segment) {
  1745. case '.':
  1746. break;
  1747. case '..':
  1748. if ((path.length === 0) || (path[path.length - 1] === '..')) {
  1749. path.push(segment);
  1750. }
  1751. else {
  1752. path.pop();
  1753. }
  1754. break;
  1755. default:
  1756. path.push(segment);
  1757. break;
  1758. }
  1759. }
  1760. return path.join('/');
  1761. };
  1762. function isPathRelative(path) {
  1763. return !/^(?:[a-z-]+:|\/|#)/i.test(path);
  1764. }
  1765. function isPathLocalRelative(path) {
  1766. return path.charAt(0) === '.';
  1767. }
  1768. // todo - do the same for the toCSS ?
  1769. function makeRegistry(base) {
  1770. return {
  1771. _data: {},
  1772. add: function (name, func) {
  1773. // precautionary case conversion, as later querying of
  1774. // the registry by function-caller uses lower case as well.
  1775. name = name.toLowerCase();
  1776. if (this._data.hasOwnProperty(name)) ;
  1777. this._data[name] = func;
  1778. },
  1779. addMultiple: function (functions) {
  1780. var _this = this;
  1781. Object.keys(functions).forEach(function (name) {
  1782. _this.add(name, functions[name]);
  1783. });
  1784. },
  1785. get: function (name) {
  1786. return this._data[name] || (base && base.get(name));
  1787. },
  1788. getLocalFunctions: function () {
  1789. return this._data;
  1790. },
  1791. inherit: function () {
  1792. return makeRegistry(this);
  1793. },
  1794. create: function (base) {
  1795. return makeRegistry(base);
  1796. }
  1797. };
  1798. }
  1799. var functionRegistry = makeRegistry(null);
  1800. var defaultFunc = {
  1801. eval: function () {
  1802. var v = this.value_;
  1803. var e = this.error_;
  1804. if (e) {
  1805. throw e;
  1806. }
  1807. if (v != null) {
  1808. return v ? Keyword.True : Keyword.False;
  1809. }
  1810. },
  1811. value: function (v) {
  1812. this.value_ = v;
  1813. },
  1814. error: function (e) {
  1815. this.error_ = e;
  1816. },
  1817. reset: function () {
  1818. this.value_ = this.error_ = null;
  1819. }
  1820. };
  1821. var Ruleset = function (selectors, rules, strictImports, visibilityInfo) {
  1822. this.selectors = selectors;
  1823. this.rules = rules;
  1824. this._lookups = {};
  1825. this._variables = null;
  1826. this._properties = null;
  1827. this.strictImports = strictImports;
  1828. this.copyVisibilityInfo(visibilityInfo);
  1829. this.allowRoot = true;
  1830. this.setParent(this.selectors, this);
  1831. this.setParent(this.rules, this);
  1832. };
  1833. Ruleset.prototype = Object.assign(new Node(), {
  1834. type: 'Ruleset',
  1835. isRuleset: true,
  1836. isRulesetLike: function () { return true; },
  1837. accept: function (visitor) {
  1838. if (this.paths) {
  1839. this.paths = visitor.visitArray(this.paths, true);
  1840. }
  1841. else if (this.selectors) {
  1842. this.selectors = visitor.visitArray(this.selectors);
  1843. }
  1844. if (this.rules && this.rules.length) {
  1845. this.rules = visitor.visitArray(this.rules);
  1846. }
  1847. },
  1848. eval: function (context) {
  1849. var selectors;
  1850. var selCnt;
  1851. var selector;
  1852. var i;
  1853. var hasVariable;
  1854. var hasOnePassingSelector = false;
  1855. if (this.selectors && (selCnt = this.selectors.length)) {
  1856. selectors = new Array(selCnt);
  1857. defaultFunc.error({
  1858. type: 'Syntax',
  1859. message: 'it is currently only allowed in parametric mixin guards,'
  1860. });
  1861. for (i = 0; i < selCnt; i++) {
  1862. selector = this.selectors[i].eval(context);
  1863. for (var j = 0; j < selector.elements.length; j++) {
  1864. if (selector.elements[j].isVariable) {
  1865. hasVariable = true;
  1866. break;
  1867. }
  1868. }
  1869. selectors[i] = selector;
  1870. if (selector.evaldCondition) {
  1871. hasOnePassingSelector = true;
  1872. }
  1873. }
  1874. if (hasVariable) {
  1875. var toParseSelectors = new Array(selCnt);
  1876. for (i = 0; i < selCnt; i++) {
  1877. selector = selectors[i];
  1878. toParseSelectors[i] = selector.toCSS(context);
  1879. }
  1880. this.parse.parseNode(toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function (err, result) {
  1881. if (result) {
  1882. selectors = flattenArray(result);
  1883. }
  1884. });
  1885. }
  1886. defaultFunc.reset();
  1887. }
  1888. else {
  1889. hasOnePassingSelector = true;
  1890. }
  1891. var rules = this.rules ? copyArray(this.rules) : null;
  1892. var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
  1893. var rule;
  1894. var subRule;
  1895. ruleset.originalRuleset = this;
  1896. ruleset.root = this.root;
  1897. ruleset.firstRoot = this.firstRoot;
  1898. ruleset.allowImports = this.allowImports;
  1899. if (this.debugInfo) {
  1900. ruleset.debugInfo = this.debugInfo;
  1901. }
  1902. if (!hasOnePassingSelector) {
  1903. rules.length = 0;
  1904. }
  1905. // inherit a function registry from the frames stack when possible;
  1906. // otherwise from the global registry
  1907. ruleset.functionRegistry = (function (frames) {
  1908. var i = 0;
  1909. var n = frames.length;
  1910. var found;
  1911. for (; i !== n; ++i) {
  1912. found = frames[i].functionRegistry;
  1913. if (found) {
  1914. return found;
  1915. }
  1916. }
  1917. return functionRegistry;
  1918. }(context.frames)).inherit();
  1919. // push the current ruleset to the frames stack
  1920. var ctxFrames = context.frames;
  1921. ctxFrames.unshift(ruleset);
  1922. // currrent selectors
  1923. var ctxSelectors = context.selectors;
  1924. if (!ctxSelectors) {
  1925. context.selectors = ctxSelectors = [];
  1926. }
  1927. ctxSelectors.unshift(this.selectors);
  1928. // Evaluate imports
  1929. if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
  1930. ruleset.evalImports(context);
  1931. }
  1932. // Store the frames around mixin definitions,
  1933. // so they can be evaluated like closures when the time comes.
  1934. var rsRules = ruleset.rules;
  1935. for (i = 0; (rule = rsRules[i]); i++) {
  1936. if (rule.evalFirst) {
  1937. rsRules[i] = rule.eval(context);
  1938. }
  1939. }
  1940. var mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0;
  1941. // Evaluate mixin calls.
  1942. for (i = 0; (rule = rsRules[i]); i++) {
  1943. if (rule.type === 'MixinCall') {
  1944. /* jshint loopfunc:true */
  1945. rules = rule.eval(context).filter(function (r) {
  1946. if ((r instanceof Declaration) && r.variable) {
  1947. // do not pollute the scope if the variable is
  1948. // already there. consider returning false here
  1949. // but we need a way to "return" variable from mixins
  1950. return !(ruleset.variable(r.name));
  1951. }
  1952. return true;
  1953. });
  1954. rsRules.splice.apply(rsRules, [i, 1].concat(rules));
  1955. i += rules.length - 1;
  1956. ruleset.resetCache();
  1957. }
  1958. else if (rule.type === 'VariableCall') {
  1959. /* jshint loopfunc:true */
  1960. rules = rule.eval(context).rules.filter(function (r) {
  1961. if ((r instanceof Declaration) && r.variable) {
  1962. // do not pollute the scope at all
  1963. return false;
  1964. }
  1965. return true;
  1966. });
  1967. rsRules.splice.apply(rsRules, [i, 1].concat(rules));
  1968. i += rules.length - 1;
  1969. ruleset.resetCache();
  1970. }
  1971. }
  1972. // Evaluate everything else
  1973. for (i = 0; (rule = rsRules[i]); i++) {
  1974. if (!rule.evalFirst) {
  1975. rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
  1976. }
  1977. }
  1978. // Evaluate everything else
  1979. for (i = 0; (rule = rsRules[i]); i++) {
  1980. // for rulesets, check if it is a css guard and can be removed
  1981. if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
  1982. // check if it can be folded in (e.g. & where)
  1983. if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
  1984. rsRules.splice(i--, 1);
  1985. for (var j = 0; (subRule = rule.rules[j]); j++) {
  1986. if (subRule instanceof Node) {
  1987. subRule.copyVisibilityInfo(rule.visibilityInfo());
  1988. if (!(subRule instanceof Declaration) || !subRule.variable) {
  1989. rsRules.splice(++i, 0, subRule);
  1990. }
  1991. }
  1992. }
  1993. }
  1994. }
  1995. }
  1996. // Pop the stack
  1997. ctxFrames.shift();
  1998. ctxSelectors.shift();
  1999. if (context.mediaBlocks) {
  2000. for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
  2001. context.mediaBlocks[i].bubbleSelectors(selectors);
  2002. }
  2003. }
  2004. return ruleset;
  2005. },
  2006. evalImports: function (context) {
  2007. var rules = this.rules;
  2008. var i;
  2009. var importRules;
  2010. if (!rules) {
  2011. return;
  2012. }
  2013. for (i = 0; i < rules.length; i++) {
  2014. if (rules[i].type === 'Import') {
  2015. importRules = rules[i].eval(context);
  2016. if (importRules && (importRules.length || importRules.length === 0)) {
  2017. rules.splice.apply(rules, [i, 1].concat(importRules));
  2018. i += importRules.length - 1;
  2019. }
  2020. else {
  2021. rules.splice(i, 1, importRules);
  2022. }
  2023. this.resetCache();
  2024. }
  2025. }
  2026. },
  2027. makeImportant: function () {
  2028. var result = new Ruleset(this.selectors, this.rules.map(function (r) {
  2029. if (r.makeImportant) {
  2030. return r.makeImportant();
  2031. }
  2032. else {
  2033. return r;
  2034. }
  2035. }), this.strictImports, this.visibilityInfo());
  2036. return result;
  2037. },
  2038. matchArgs: function (args) {
  2039. return !args || args.length === 0;
  2040. },
  2041. // lets you call a css selector with a guard
  2042. matchCondition: function (args, context) {
  2043. var lastSelector = this.selectors[this.selectors.length - 1];
  2044. if (!lastSelector.evaldCondition) {
  2045. return false;
  2046. }
  2047. if (lastSelector.condition &&
  2048. !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
  2049. return false;
  2050. }
  2051. return true;
  2052. },
  2053. resetCache: function () {
  2054. this._rulesets = null;
  2055. this._variables = null;
  2056. this._properties = null;
  2057. this._lookups = {};
  2058. },
  2059. variables: function () {
  2060. if (!this._variables) {
  2061. this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  2062. if (r instanceof Declaration && r.variable === true) {
  2063. hash[r.name] = r;
  2064. }
  2065. // when evaluating variables in an import statement, imports have not been eval'd
  2066. // so we need to go inside import statements.
  2067. // guard against root being a string (in the case of inlined less)
  2068. if (r.type === 'Import' && r.root && r.root.variables) {
  2069. var vars = r.root.variables();
  2070. for (var name_1 in vars) {
  2071. if (vars.hasOwnProperty(name_1)) {
  2072. hash[name_1] = r.root.variable(name_1);
  2073. }
  2074. }
  2075. }
  2076. return hash;
  2077. }, {});
  2078. }
  2079. return this._variables;
  2080. },
  2081. properties: function () {
  2082. if (!this._properties) {
  2083. this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  2084. if (r instanceof Declaration && r.variable !== true) {
  2085. var name_2 = (r.name.length === 1) && (r.name[0] instanceof Keyword) ?
  2086. r.name[0].value : r.name;
  2087. // Properties don't overwrite as they can merge
  2088. if (!hash["$" + name_2]) {
  2089. hash["$" + name_2] = [r];
  2090. }
  2091. else {
  2092. hash["$" + name_2].push(r);
  2093. }
  2094. }
  2095. return hash;
  2096. }, {});
  2097. }
  2098. return this._properties;
  2099. },
  2100. variable: function (name) {
  2101. var decl = this.variables()[name];
  2102. if (decl) {
  2103. return this.parseValue(decl);
  2104. }
  2105. },
  2106. property: function (name) {
  2107. var decl = this.properties()[name];
  2108. if (decl) {
  2109. return this.parseValue(decl);
  2110. }
  2111. },
  2112. lastDeclaration: function () {
  2113. for (var i = this.rules.length; i > 0; i--) {
  2114. var decl = this.rules[i - 1];
  2115. if (decl instanceof Declaration) {
  2116. return this.parseValue(decl);
  2117. }
  2118. }
  2119. },
  2120. parseValue: function (toParse) {
  2121. var self = this;
  2122. function transformDeclaration(decl) {
  2123. if (decl.value instanceof Anonymous && !decl.parsed) {
  2124. if (typeof decl.value.value === 'string') {
  2125. this.parse.parseNode(decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
  2126. if (err) {
  2127. decl.parsed = true;
  2128. }
  2129. if (result) {
  2130. decl.value = result[0];
  2131. decl.important = result[1] || '';
  2132. decl.parsed = true;
  2133. }
  2134. });
  2135. }
  2136. else {
  2137. decl.parsed = true;
  2138. }
  2139. return decl;
  2140. }
  2141. else {
  2142. return decl;
  2143. }
  2144. }
  2145. if (!Array.isArray(toParse)) {
  2146. return transformDeclaration.call(self, toParse);
  2147. }
  2148. else {
  2149. var nodes_1 = [];
  2150. toParse.forEach(function (n) {
  2151. nodes_1.push(transformDeclaration.call(self, n));
  2152. });
  2153. return nodes_1;
  2154. }
  2155. },
  2156. rulesets: function () {
  2157. if (!this.rules) {
  2158. return [];
  2159. }
  2160. var filtRules = [];
  2161. var rules = this.rules;
  2162. var i;
  2163. var rule;
  2164. for (i = 0; (rule = rules[i]); i++) {
  2165. if (rule.isRuleset) {
  2166. filtRules.push(rule);
  2167. }
  2168. }
  2169. return filtRules;
  2170. },
  2171. prependRule: function (rule) {
  2172. var rules = this.rules;
  2173. if (rules) {
  2174. rules.unshift(rule);
  2175. }
  2176. else {
  2177. this.rules = [rule];
  2178. }
  2179. this.setParent(rule, this);
  2180. },
  2181. find: function (selector, self, filter) {
  2182. self = self || this;
  2183. var rules = [];
  2184. var match;
  2185. var foundMixins;
  2186. var key = selector.toCSS();
  2187. if (key in this._lookups) {
  2188. return this._lookups[key];
  2189. }
  2190. this.rulesets().forEach(function (rule) {
  2191. if (rule !== self) {
  2192. for (var j = 0; j < rule.selectors.length; j++) {
  2193. match = selector.match(rule.selectors[j]);
  2194. if (match) {
  2195. if (selector.elements.length > match) {
  2196. if (!filter || filter(rule)) {
  2197. foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
  2198. for (var i = 0; i < foundMixins.length; ++i) {
  2199. foundMixins[i].path.push(rule);
  2200. }
  2201. Array.prototype.push.apply(rules, foundMixins);
  2202. }
  2203. }
  2204. else {
  2205. rules.push({ rule: rule, path: [] });
  2206. }
  2207. break;
  2208. }
  2209. }
  2210. }
  2211. });
  2212. this._lookups[key] = rules;
  2213. return rules;
  2214. },
  2215. genCSS: function (context, output) {
  2216. var i;
  2217. var j;
  2218. var charsetRuleNodes = [];
  2219. var ruleNodes = [];
  2220. var // Line number debugging
  2221. debugInfo$1;
  2222. var rule;
  2223. var path;
  2224. context.tabLevel = (context.tabLevel || 0);
  2225. if (!this.root) {
  2226. context.tabLevel++;
  2227. }
  2228. var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
  2229. var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
  2230. var sep;
  2231. var charsetNodeIndex = 0;
  2232. var importNodeIndex = 0;
  2233. for (i = 0; (rule = this.rules[i]); i++) {
  2234. if (rule instanceof Comment) {
  2235. if (importNodeIndex === i) {
  2236. importNodeIndex++;
  2237. }
  2238. ruleNodes.push(rule);
  2239. }
  2240. else if (rule.isCharset && rule.isCharset()) {
  2241. ruleNodes.splice(charsetNodeIndex, 0, rule);
  2242. charsetNodeIndex++;
  2243. importNodeIndex++;
  2244. }
  2245. else if (rule.type === 'Import') {
  2246. ruleNodes.splice(importNodeIndex, 0, rule);
  2247. importNodeIndex++;
  2248. }
  2249. else {
  2250. ruleNodes.push(rule);
  2251. }
  2252. }
  2253. ruleNodes = charsetRuleNodes.concat(ruleNodes);
  2254. // If this is the root node, we don't render
  2255. // a selector, or {}.
  2256. if (!this.root) {
  2257. debugInfo$1 = debugInfo(context, this, tabSetStr);
  2258. if (debugInfo$1) {
  2259. output.add(debugInfo$1);
  2260. output.add(tabSetStr);
  2261. }
  2262. var paths = this.paths;
  2263. var pathCnt = paths.length;
  2264. var pathSubCnt = void 0;
  2265. sep = context.compress ? ',' : (",\n" + tabSetStr);
  2266. for (i = 0; i < pathCnt; i++) {
  2267. path = paths[i];
  2268. if (!(pathSubCnt = path.length)) {
  2269. continue;
  2270. }
  2271. if (i > 0) {
  2272. output.add(sep);
  2273. }
  2274. context.firstSelector = true;
  2275. path[0].genCSS(context, output);
  2276. context.firstSelector = false;
  2277. for (j = 1; j < pathSubCnt; j++) {
  2278. path[j].genCSS(context, output);
  2279. }
  2280. }
  2281. output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
  2282. }
  2283. // Compile rules and rulesets
  2284. for (i = 0; (rule = ruleNodes[i]); i++) {
  2285. if (i + 1 === ruleNodes.length) {
  2286. context.lastRule = true;
  2287. }
  2288. var currentLastRule = context.lastRule;
  2289. if (rule.isRulesetLike(rule)) {
  2290. context.lastRule = false;
  2291. }
  2292. if (rule.genCSS) {
  2293. rule.genCSS(context, output);
  2294. }
  2295. else if (rule.value) {
  2296. output.add(rule.value.toString());
  2297. }
  2298. context.lastRule = currentLastRule;
  2299. if (!context.lastRule && rule.isVisible()) {
  2300. output.add(context.compress ? '' : ("\n" + tabRuleStr));
  2301. }
  2302. else {
  2303. context.lastRule = false;
  2304. }
  2305. }
  2306. if (!this.root) {
  2307. output.add((context.compress ? '}' : "\n" + tabSetStr + "}"));
  2308. context.tabLevel--;
  2309. }
  2310. if (!output.isEmpty() && !context.compress && this.firstRoot) {
  2311. output.add('\n');
  2312. }
  2313. },
  2314. joinSelectors: function (paths, context, selectors) {
  2315. for (var s = 0; s < selectors.length; s++) {
  2316. this.joinSelector(paths, context, selectors[s]);
  2317. }
  2318. },
  2319. joinSelector: function (paths, context, selector) {
  2320. function createParenthesis(elementsToPak, originalElement) {
  2321. var replacementParen, j;
  2322. if (elementsToPak.length === 0) {
  2323. replacementParen = new Paren(elementsToPak[0]);
  2324. }
  2325. else {
  2326. var insideParent = new Array(elementsToPak.length);
  2327. for (j = 0; j < elementsToPak.length; j++) {
  2328. insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  2329. }
  2330. replacementParen = new Paren(new Selector(insideParent));
  2331. }
  2332. return replacementParen;
  2333. }
  2334. function createSelector(containedElement, originalElement) {
  2335. var element, selector;
  2336. element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  2337. selector = new Selector([element]);
  2338. return selector;
  2339. }
  2340. // joins selector path from `beginningPath` with selector path in `addPath`
  2341. // `replacedElement` contains element that is being replaced by `addPath`
  2342. // returns concatenated path
  2343. function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
  2344. var newSelectorPath, lastSelector, newJoinedSelector;
  2345. // our new selector path
  2346. newSelectorPath = [];
  2347. // construct the joined selector - if & is the first thing this will be empty,
  2348. // if not newJoinedSelector will be the last set of elements in the selector
  2349. if (beginningPath.length > 0) {
  2350. newSelectorPath = copyArray(beginningPath);
  2351. lastSelector = newSelectorPath.pop();
  2352. newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
  2353. }
  2354. else {
  2355. newJoinedSelector = originalSelector.createDerived([]);
  2356. }
  2357. if (addPath.length > 0) {
  2358. // /deep/ is a CSS4 selector - (removed, so should deprecate)
  2359. // that is valid without anything in front of it
  2360. // so if the & does not have a combinator that is "" or " " then
  2361. // and there is a combinator on the parent, then grab that.
  2362. // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
  2363. var combinator = replacedElement.combinator;
  2364. var parentEl = addPath[0].elements[0];
  2365. if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
  2366. combinator = parentEl.combinator;
  2367. }
  2368. // join the elements so far with the first part of the parent
  2369. newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
  2370. newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
  2371. }
  2372. // now add the joined selector - but only if it is not empty
  2373. if (newJoinedSelector.elements.length !== 0) {
  2374. newSelectorPath.push(newJoinedSelector);
  2375. }
  2376. // put together the parent selectors after the join (e.g. the rest of the parent)
  2377. if (addPath.length > 1) {
  2378. var restOfPath = addPath.slice(1);
  2379. restOfPath = restOfPath.map(function (selector) {
  2380. return selector.createDerived(selector.elements, []);
  2381. });
  2382. newSelectorPath = newSelectorPath.concat(restOfPath);
  2383. }
  2384. return newSelectorPath;
  2385. }
  2386. // joins selector path from `beginningPath` with every selector path in `addPaths` array
  2387. // `replacedElement` contains element that is being replaced by `addPath`
  2388. // returns array with all concatenated paths
  2389. function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
  2390. var j;
  2391. for (j = 0; j < beginningPath.length; j++) {
  2392. var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
  2393. result.push(newSelectorPath);
  2394. }
  2395. return result;
  2396. }
  2397. function mergeElementsOnToSelectors(elements, selectors) {
  2398. var i, sel;
  2399. if (elements.length === 0) {
  2400. return;
  2401. }
  2402. if (selectors.length === 0) {
  2403. selectors.push([new Selector(elements)]);
  2404. return;
  2405. }
  2406. for (i = 0; (sel = selectors[i]); i++) {
  2407. // if the previous thing in sel is a parent this needs to join on to it
  2408. if (sel.length > 0) {
  2409. sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
  2410. }
  2411. else {
  2412. sel.push(new Selector(elements));
  2413. }
  2414. }
  2415. }
  2416. // replace all parent selectors inside `inSelector` by content of `context` array
  2417. // resulting selectors are returned inside `paths` array
  2418. // returns true if `inSelector` contained at least one parent selector
  2419. function replaceParentSelector(paths, context, inSelector) {
  2420. // The paths are [[Selector]]
  2421. // The first list is a list of comma separated selectors
  2422. // The inner list is a list of inheritance separated selectors
  2423. // e.g.
  2424. // .a, .b {
  2425. // .c {
  2426. // }
  2427. // }
  2428. // == [[.a] [.c]] [[.b] [.c]]
  2429. //
  2430. var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector;
  2431. function findNestedSelector(element) {
  2432. var maybeSelector;
  2433. if (!(element.value instanceof Paren)) {
  2434. return null;
  2435. }
  2436. maybeSelector = element.value.value;
  2437. if (!(maybeSelector instanceof Selector)) {
  2438. return null;
  2439. }
  2440. return maybeSelector;
  2441. }
  2442. // the elements from the current selector so far
  2443. currentElements = [];
  2444. // the current list of new selectors to add to the path.
  2445. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
  2446. // by the parents
  2447. newSelectors = [
  2448. []
  2449. ];
  2450. for (i = 0; (el = inSelector.elements[i]); i++) {
  2451. // non parent reference elements just get added
  2452. if (el.value !== '&') {
  2453. var nestedSelector = findNestedSelector(el);
  2454. if (nestedSelector != null) {
  2455. // merge the current list of non parent selector elements
  2456. // on to the current list of selectors to add
  2457. mergeElementsOnToSelectors(currentElements, newSelectors);
  2458. var nestedPaths = [];
  2459. var replaced = void 0;
  2460. var replacedNewSelectors = [];
  2461. replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
  2462. hadParentSelector = hadParentSelector || replaced;
  2463. // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
  2464. for (k = 0; k < nestedPaths.length; k++) {
  2465. var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
  2466. addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
  2467. }
  2468. newSelectors = replacedNewSelectors;
  2469. currentElements = [];
  2470. }
  2471. else {
  2472. currentElements.push(el);
  2473. }
  2474. }
  2475. else {
  2476. hadParentSelector = true;
  2477. // the new list of selectors to add
  2478. selectorsMultiplied = [];
  2479. // merge the current list of non parent selector elements
  2480. // on to the current list of selectors to add
  2481. mergeElementsOnToSelectors(currentElements, newSelectors);
  2482. // loop through our current selectors
  2483. for (j = 0; j < newSelectors.length; j++) {
  2484. sel = newSelectors[j];
  2485. // if we don't have any parent paths, the & might be in a mixin so that it can be used
  2486. // whether there are parents or not
  2487. if (context.length === 0) {
  2488. // the combinator used on el should now be applied to the next element instead so that
  2489. // it is not lost
  2490. if (sel.length > 0) {
  2491. sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
  2492. }
  2493. selectorsMultiplied.push(sel);
  2494. }
  2495. else {
  2496. // and the parent selectors
  2497. for (k = 0; k < context.length; k++) {
  2498. // We need to put the current selectors
  2499. // then join the last selector's elements on to the parents selectors
  2500. var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);
  2501. // add that to our new set of selectors
  2502. selectorsMultiplied.push(newSelectorPath);
  2503. }
  2504. }
  2505. }
  2506. // our new selectors has been multiplied, so reset the state
  2507. newSelectors = selectorsMultiplied;
  2508. currentElements = [];
  2509. }
  2510. }
  2511. // if we have any elements left over (e.g. .a& .b == .b)
  2512. // add them on to all the current selectors
  2513. mergeElementsOnToSelectors(currentElements, newSelectors);
  2514. for (i = 0; i < newSelectors.length; i++) {
  2515. length = newSelectors[i].length;
  2516. if (length > 0) {
  2517. paths.push(newSelectors[i]);
  2518. lastSelector = newSelectors[i][length - 1];
  2519. newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
  2520. }
  2521. }
  2522. return hadParentSelector;
  2523. }
  2524. function deriveSelector(visibilityInfo, deriveFrom) {
  2525. var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
  2526. newSelector.copyVisibilityInfo(visibilityInfo);
  2527. return newSelector;
  2528. }
  2529. // joinSelector code follows
  2530. var i, newPaths, hadParentSelector;
  2531. newPaths = [];
  2532. hadParentSelector = replaceParentSelector(newPaths, context, selector);
  2533. if (!hadParentSelector) {
  2534. if (context.length > 0) {
  2535. newPaths = [];
  2536. for (i = 0; i < context.length; i++) {
  2537. var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
  2538. concatenated.push(selector);
  2539. newPaths.push(concatenated);
  2540. }
  2541. }
  2542. else {
  2543. newPaths = [[selector]];
  2544. }
  2545. }
  2546. for (i = 0; i < newPaths.length; i++) {
  2547. paths.push(newPaths[i]);
  2548. }
  2549. }
  2550. });
  2551. var AtRule = function (name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
  2552. var i;
  2553. this.name = name;
  2554. this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
  2555. if (rules) {
  2556. if (Array.isArray(rules)) {
  2557. this.rules = rules;
  2558. }
  2559. else {
  2560. this.rules = [rules];
  2561. this.rules[0].selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
  2562. }
  2563. for (i = 0; i < this.rules.length; i++) {
  2564. this.rules[i].allowImports = true;
  2565. }
  2566. this.setParent(this.rules, this);
  2567. }
  2568. this._index = index;
  2569. this._fileInfo = currentFileInfo;
  2570. this.debugInfo = debugInfo;
  2571. this.isRooted = isRooted || false;
  2572. this.copyVisibilityInfo(visibilityInfo);
  2573. this.allowRoot = true;
  2574. };
  2575. AtRule.prototype = Object.assign(new Node(), {
  2576. type: 'AtRule',
  2577. accept: function (visitor) {
  2578. var value = this.value, rules = this.rules;
  2579. if (rules) {
  2580. this.rules = visitor.visitArray(rules);
  2581. }
  2582. if (value) {
  2583. this.value = visitor.visit(value);
  2584. }
  2585. },
  2586. isRulesetLike: function () {
  2587. return this.rules || !this.isCharset();
  2588. },
  2589. isCharset: function () {
  2590. return '@charset' === this.name;
  2591. },
  2592. genCSS: function (context, output) {
  2593. var value = this.value, rules = this.rules;
  2594. output.add(this.name, this.fileInfo(), this.getIndex());
  2595. if (value) {
  2596. output.add(' ');
  2597. value.genCSS(context, output);
  2598. }
  2599. if (rules) {
  2600. this.outputRuleset(context, output, rules);
  2601. }
  2602. else {
  2603. output.add(';');
  2604. }
  2605. },
  2606. eval: function (context) {
  2607. var mediaPathBackup, mediaBlocksBackup, value = this.value, rules = this.rules;
  2608. // media stored inside other atrule should not bubble over it
  2609. // backpup media bubbling information
  2610. mediaPathBackup = context.mediaPath;
  2611. mediaBlocksBackup = context.mediaBlocks;
  2612. // deleted media bubbling information
  2613. context.mediaPath = [];
  2614. context.mediaBlocks = [];
  2615. if (value) {
  2616. value = value.eval(context);
  2617. }
  2618. if (rules) {
  2619. // assuming that there is only one rule at this point - that is how parser constructs the rule
  2620. rules = [rules[0].eval(context)];
  2621. rules[0].root = true;
  2622. }
  2623. // restore media bubbling information
  2624. context.mediaPath = mediaPathBackup;
  2625. context.mediaBlocks = mediaBlocksBackup;
  2626. return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
  2627. },
  2628. variable: function (name) {
  2629. if (this.rules) {
  2630. // assuming that there is only one rule at this point - that is how parser constructs the rule
  2631. return Ruleset.prototype.variable.call(this.rules[0], name);
  2632. }
  2633. },
  2634. find: function () {
  2635. if (this.rules) {
  2636. // assuming that there is only one rule at this point - that is how parser constructs the rule
  2637. return Ruleset.prototype.find.apply(this.rules[0], arguments);
  2638. }
  2639. },
  2640. rulesets: function () {
  2641. if (this.rules) {
  2642. // assuming that there is only one rule at this point - that is how parser constructs the rule
  2643. return Ruleset.prototype.rulesets.apply(this.rules[0]);
  2644. }
  2645. },
  2646. outputRuleset: function (context, output, rules) {
  2647. var ruleCnt = rules.length;
  2648. var i;
  2649. context.tabLevel = (context.tabLevel | 0) + 1;
  2650. // Compressed
  2651. if (context.compress) {
  2652. output.add('{');
  2653. for (i = 0; i < ruleCnt; i++) {
  2654. rules[i].genCSS(context, output);
  2655. }
  2656. output.add('}');
  2657. context.tabLevel--;
  2658. return;
  2659. }
  2660. // Non-compressed
  2661. var tabSetStr = "\n" + Array(context.tabLevel).join(' '), tabRuleStr = tabSetStr + " ";
  2662. if (!ruleCnt) {
  2663. output.add(" {" + tabSetStr + "}");
  2664. }
  2665. else {
  2666. output.add(" {" + tabRuleStr);
  2667. rules[0].genCSS(context, output);
  2668. for (i = 1; i < ruleCnt; i++) {
  2669. output.add(tabRuleStr);
  2670. rules[i].genCSS(context, output);
  2671. }
  2672. output.add(tabSetStr + "}");
  2673. }
  2674. context.tabLevel--;
  2675. }
  2676. });
  2677. var DetachedRuleset = function (ruleset, frames) {
  2678. this.ruleset = ruleset;
  2679. this.frames = frames;
  2680. this.setParent(this.ruleset, this);
  2681. };
  2682. DetachedRuleset.prototype = Object.assign(new Node(), {
  2683. type: 'DetachedRuleset',
  2684. evalFirst: true,
  2685. accept: function (visitor) {
  2686. this.ruleset = visitor.visit(this.ruleset);
  2687. },
  2688. eval: function (context) {
  2689. var frames = this.frames || copyArray(context.frames);
  2690. return new DetachedRuleset(this.ruleset, frames);
  2691. },
  2692. callEval: function (context) {
  2693. return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
  2694. }
  2695. });
  2696. var Unit = function (numerator, denominator, backupUnit) {
  2697. this.numerator = numerator ? copyArray(numerator).sort() : [];
  2698. this.denominator = denominator ? copyArray(denominator).sort() : [];
  2699. if (backupUnit) {
  2700. this.backupUnit = backupUnit;
  2701. }
  2702. else if (numerator && numerator.length) {
  2703. this.backupUnit = numerator[0];
  2704. }
  2705. };
  2706. Unit.prototype = Object.assign(new Node(), {
  2707. type: 'Unit',
  2708. clone: function () {
  2709. return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
  2710. },
  2711. genCSS: function (context, output) {
  2712. // Dimension checks the unit is singular and throws an error if in strict math mode.
  2713. var strictUnits = context && context.strictUnits;
  2714. if (this.numerator.length === 1) {
  2715. output.add(this.numerator[0]); // the ideal situation
  2716. }
  2717. else if (!strictUnits && this.backupUnit) {
  2718. output.add(this.backupUnit);
  2719. }
  2720. else if (!strictUnits && this.denominator.length) {
  2721. output.add(this.denominator[0]);
  2722. }
  2723. },
  2724. toString: function () {
  2725. var i, returnStr = this.numerator.join('*');
  2726. for (i = 0; i < this.denominator.length; i++) {
  2727. returnStr += "/" + this.denominator[i];
  2728. }
  2729. return returnStr;
  2730. },
  2731. compare: function (other) {
  2732. return this.is(other.toString()) ? 0 : undefined;
  2733. },
  2734. is: function (unitString) {
  2735. return this.toString().toUpperCase() === unitString.toUpperCase();
  2736. },
  2737. isLength: function () {
  2738. return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
  2739. },
  2740. isEmpty: function () {
  2741. return this.numerator.length === 0 && this.denominator.length === 0;
  2742. },
  2743. isSingular: function () {
  2744. return this.numerator.length <= 1 && this.denominator.length === 0;
  2745. },
  2746. map: function (callback) {
  2747. var i;
  2748. for (i = 0; i < this.numerator.length; i++) {
  2749. this.numerator[i] = callback(this.numerator[i], false);
  2750. }
  2751. for (i = 0; i < this.denominator.length; i++) {
  2752. this.denominator[i] = callback(this.denominator[i], true);
  2753. }
  2754. },
  2755. usedUnits: function () {
  2756. var group;
  2757. var result = {};
  2758. var mapUnit;
  2759. var groupName;
  2760. mapUnit = function (atomicUnit) {
  2761. /* jshint loopfunc:true */
  2762. if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
  2763. result[groupName] = atomicUnit;
  2764. }
  2765. return atomicUnit;
  2766. };
  2767. for (groupName in unitConversions) {
  2768. if (unitConversions.hasOwnProperty(groupName)) {
  2769. group = unitConversions[groupName];
  2770. this.map(mapUnit);
  2771. }
  2772. }
  2773. return result;
  2774. },
  2775. cancel: function () {
  2776. var counter = {};
  2777. var atomicUnit;
  2778. var i;
  2779. for (i = 0; i < this.numerator.length; i++) {
  2780. atomicUnit = this.numerator[i];
  2781. counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
  2782. }
  2783. for (i = 0; i < this.denominator.length; i++) {
  2784. atomicUnit = this.denominator[i];
  2785. counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
  2786. }
  2787. this.numerator = [];
  2788. this.denominator = [];
  2789. for (atomicUnit in counter) {
  2790. if (counter.hasOwnProperty(atomicUnit)) {
  2791. var count = counter[atomicUnit];
  2792. if (count > 0) {
  2793. for (i = 0; i < count; i++) {
  2794. this.numerator.push(atomicUnit);
  2795. }
  2796. }
  2797. else if (count < 0) {
  2798. for (i = 0; i < -count; i++) {
  2799. this.denominator.push(atomicUnit);
  2800. }
  2801. }
  2802. }
  2803. }
  2804. this.numerator.sort();
  2805. this.denominator.sort();
  2806. }
  2807. });
  2808. //
  2809. // A number with a unit
  2810. //
  2811. var Dimension = function (value, unit) {
  2812. this.value = parseFloat(value);
  2813. if (isNaN(this.value)) {
  2814. throw new Error('Dimension is not a number.');
  2815. }
  2816. this.unit = (unit && unit instanceof Unit) ? unit :
  2817. new Unit(unit ? [unit] : undefined);
  2818. this.setParent(this.unit, this);
  2819. };
  2820. Dimension.prototype = Object.assign(new Node(), {
  2821. type: 'Dimension',
  2822. accept: function (visitor) {
  2823. this.unit = visitor.visit(this.unit);
  2824. },
  2825. eval: function (context) {
  2826. return this;
  2827. },
  2828. toColor: function () {
  2829. return new Color([this.value, this.value, this.value]);
  2830. },
  2831. genCSS: function (context, output) {
  2832. if ((context && context.strictUnits) && !this.unit.isSingular()) {
  2833. throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: " + this.unit.toString());
  2834. }
  2835. var value = this.fround(context, this.value);
  2836. var strValue = String(value);
  2837. if (value !== 0 && value < 0.000001 && value > -0.000001) {
  2838. // would be output 1e-6 etc.
  2839. strValue = value.toFixed(20).replace(/0+$/, '');
  2840. }
  2841. if (context && context.compress) {
  2842. // Zero values doesn't need a unit
  2843. if (value === 0 && this.unit.isLength()) {
  2844. output.add(strValue);
  2845. return;
  2846. }
  2847. // Float values doesn't need a leading zero
  2848. if (value > 0 && value < 1) {
  2849. strValue = (strValue).substr(1);
  2850. }
  2851. }
  2852. output.add(strValue);
  2853. this.unit.genCSS(context, output);
  2854. },
  2855. // In an operation between two Dimensions,
  2856. // we default to the first Dimension's unit,
  2857. // so `1px + 2` will yield `3px`.
  2858. operate: function (context, op, other) {
  2859. /* jshint noempty:false */
  2860. var value = this._operate(context, op, this.value, other.value);
  2861. var unit = this.unit.clone();
  2862. if (op === '+' || op === '-') {
  2863. if (unit.numerator.length === 0 && unit.denominator.length === 0) {
  2864. unit = other.unit.clone();
  2865. if (this.unit.backupUnit) {
  2866. unit.backupUnit = this.unit.backupUnit;
  2867. }
  2868. }
  2869. else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ;
  2870. else {
  2871. other = other.convertTo(this.unit.usedUnits());
  2872. if (context.strictUnits && other.unit.toString() !== unit.toString()) {
  2873. throw new Error("Incompatible units. Change the units or use the unit function. "
  2874. + ("Bad units: '" + unit.toString() + "' and '" + other.unit.toString() + "'."));
  2875. }
  2876. value = this._operate(context, op, this.value, other.value);
  2877. }
  2878. }
  2879. else if (op === '*') {
  2880. unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
  2881. unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
  2882. unit.cancel();
  2883. }
  2884. else if (op === '/') {
  2885. unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
  2886. unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
  2887. unit.cancel();
  2888. }
  2889. return new Dimension(value, unit);
  2890. },
  2891. compare: function (other) {
  2892. var a, b;
  2893. if (!(other instanceof Dimension)) {
  2894. return undefined;
  2895. }
  2896. if (this.unit.isEmpty() || other.unit.isEmpty()) {
  2897. a = this;
  2898. b = other;
  2899. }
  2900. else {
  2901. a = this.unify();
  2902. b = other.unify();
  2903. if (a.unit.compare(b.unit) !== 0) {
  2904. return undefined;
  2905. }
  2906. }
  2907. return Node.numericCompare(a.value, b.value);
  2908. },
  2909. unify: function () {
  2910. return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
  2911. },
  2912. convertTo: function (conversions) {
  2913. var value = this.value;
  2914. var unit = this.unit.clone();
  2915. var i;
  2916. var groupName;
  2917. var group;
  2918. var targetUnit;
  2919. var derivedConversions = {};
  2920. var applyUnit;
  2921. if (typeof conversions === 'string') {
  2922. for (i in unitConversions) {
  2923. if (unitConversions[i].hasOwnProperty(conversions)) {
  2924. derivedConversions = {};
  2925. derivedConversions[i] = conversions;
  2926. }
  2927. }
  2928. conversions = derivedConversions;
  2929. }
  2930. applyUnit = function (atomicUnit, denominator) {
  2931. /* jshint loopfunc:true */
  2932. if (group.hasOwnProperty(atomicUnit)) {
  2933. if (denominator) {
  2934. value = value / (group[atomicUnit] / group[targetUnit]);
  2935. }
  2936. else {
  2937. value = value * (group[atomicUnit] / group[targetUnit]);
  2938. }
  2939. return targetUnit;
  2940. }
  2941. return atomicUnit;
  2942. };
  2943. for (groupName in conversions) {
  2944. if (conversions.hasOwnProperty(groupName)) {
  2945. targetUnit = conversions[groupName];
  2946. group = unitConversions[groupName];
  2947. unit.map(applyUnit);
  2948. }
  2949. }
  2950. unit.cancel();
  2951. return new Dimension(value, unit);
  2952. }
  2953. });
  2954. var MATH = Math$1;
  2955. var Operation = function (op, operands, isSpaced) {
  2956. this.op = op.trim();
  2957. this.operands = operands;
  2958. this.isSpaced = isSpaced;
  2959. };
  2960. Operation.prototype = Object.assign(new Node(), {
  2961. type: 'Operation',
  2962. accept: function (visitor) {
  2963. this.operands = visitor.visitArray(this.operands);
  2964. },
  2965. eval: function (context) {
  2966. var a = this.operands[0].eval(context), b = this.operands[1].eval(context), op;
  2967. if (context.isMathOn(this.op)) {
  2968. op = this.op === './' ? '/' : this.op;
  2969. if (a instanceof Dimension && b instanceof Color) {
  2970. a = a.toColor();
  2971. }
  2972. if (b instanceof Dimension && a instanceof Color) {
  2973. b = b.toColor();
  2974. }
  2975. if (!a.operate || !b.operate) {
  2976. if ((a instanceof Operation || b instanceof Operation)
  2977. && a.op === '/' && context.math === MATH.PARENS_DIVISION) {
  2978. return new Operation(this.op, [a, b], this.isSpaced);
  2979. }
  2980. throw { type: 'Operation',
  2981. message: 'Operation on an invalid type' };
  2982. }
  2983. return a.operate(context, op, b);
  2984. }
  2985. else {
  2986. return new Operation(this.op, [a, b], this.isSpaced);
  2987. }
  2988. },
  2989. genCSS: function (context, output) {
  2990. this.operands[0].genCSS(context, output);
  2991. if (this.isSpaced) {
  2992. output.add(' ');
  2993. }
  2994. output.add(this.op);
  2995. if (this.isSpaced) {
  2996. output.add(' ');
  2997. }
  2998. this.operands[1].genCSS(context, output);
  2999. }
  3000. });
  3001. /*! *****************************************************************************
  3002. Copyright (c) Microsoft Corporation.
  3003. Permission to use, copy, modify, and/or distribute this software for any
  3004. purpose with or without fee is hereby granted.
  3005. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  3006. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  3007. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  3008. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  3009. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  3010. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  3011. PERFORMANCE OF THIS SOFTWARE.
  3012. ***************************************************************************** */
  3013. function __spreadArray(to, from, pack) {
  3014. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  3015. if (ar || !(i in from)) {
  3016. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  3017. ar[i] = from[i];
  3018. }
  3019. }
  3020. return to.concat(ar || from);
  3021. }
  3022. var Expression = function (value, noSpacing) {
  3023. this.value = value;
  3024. this.noSpacing = noSpacing;
  3025. if (!value) {
  3026. throw new Error('Expression requires an array parameter');
  3027. }
  3028. };
  3029. Expression.prototype = Object.assign(new Node(), {
  3030. type: 'Expression',
  3031. accept: function (visitor) {
  3032. this.value = visitor.visitArray(this.value);
  3033. },
  3034. eval: function (context) {
  3035. var returnValue;
  3036. var mathOn = context.isMathOn();
  3037. var inParenthesis = this.parens;
  3038. var doubleParen = false;
  3039. if (inParenthesis) {
  3040. context.inParenthesis();
  3041. }
  3042. if (this.value.length > 1) {
  3043. returnValue = new Expression(this.value.map(function (e) {
  3044. if (!e.eval) {
  3045. return e;
  3046. }
  3047. return e.eval(context);
  3048. }), this.noSpacing);
  3049. }
  3050. else if (this.value.length === 1) {
  3051. if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
  3052. doubleParen = true;
  3053. }
  3054. returnValue = this.value[0].eval(context);
  3055. }
  3056. else {
  3057. returnValue = this;
  3058. }
  3059. if (inParenthesis) {
  3060. context.outOfParenthesis();
  3061. }
  3062. if (this.parens && this.parensInOp && !mathOn && !doubleParen
  3063. && (!(returnValue instanceof Dimension))) {
  3064. returnValue = new Paren(returnValue);
  3065. }
  3066. return returnValue;
  3067. },
  3068. genCSS: function (context, output) {
  3069. for (var i = 0; i < this.value.length; i++) {
  3070. this.value[i].genCSS(context, output);
  3071. if (!this.noSpacing && i + 1 < this.value.length) {
  3072. output.add(' ');
  3073. }
  3074. }
  3075. },
  3076. throwAwayComments: function () {
  3077. this.value = this.value.filter(function (v) {
  3078. return !(v instanceof Comment);
  3079. });
  3080. }
  3081. });
  3082. var functionCaller = /** @class */ (function () {
  3083. function functionCaller(name, context, index, currentFileInfo) {
  3084. this.name = name.toLowerCase();
  3085. this.index = index;
  3086. this.context = context;
  3087. this.currentFileInfo = currentFileInfo;
  3088. this.func = context.frames[0].functionRegistry.get(this.name);
  3089. }
  3090. functionCaller.prototype.isValid = function () {
  3091. return Boolean(this.func);
  3092. };
  3093. functionCaller.prototype.call = function (args) {
  3094. var _this = this;
  3095. if (!(Array.isArray(args))) {
  3096. args = [args];
  3097. }
  3098. var evalArgs = this.func.evalArgs;
  3099. if (evalArgs !== false) {
  3100. args = args.map(function (a) { return a.eval(_this.context); });
  3101. }
  3102. var commentFilter = function (item) { return !(item.type === 'Comment'); };
  3103. // This code is terrible and should be replaced as per this issue...
  3104. // https://github.com/less/less.js/issues/2477
  3105. args = args
  3106. .filter(commentFilter)
  3107. .map(function (item) {
  3108. if (item.type === 'Expression') {
  3109. var subNodes = item.value.filter(commentFilter);
  3110. if (subNodes.length === 1) {
  3111. // https://github.com/less/less.js/issues/3616
  3112. if (item.parens && subNodes[0].op === '/') {
  3113. return item;
  3114. }
  3115. return subNodes[0];
  3116. }
  3117. else {
  3118. return new Expression(subNodes);
  3119. }
  3120. }
  3121. return item;
  3122. });
  3123. if (evalArgs === false) {
  3124. return this.func.apply(this, __spreadArray([this.context], args));
  3125. }
  3126. return this.func.apply(this, args);
  3127. };
  3128. return functionCaller;
  3129. }());
  3130. //
  3131. // A function call node.
  3132. //
  3133. var Call = function (name, args, index, currentFileInfo) {
  3134. this.name = name;
  3135. this.args = args;
  3136. this.calc = name === 'calc';
  3137. this._index = index;
  3138. this._fileInfo = currentFileInfo;
  3139. };
  3140. Call.prototype = Object.assign(new Node(), {
  3141. type: 'Call',
  3142. accept: function (visitor) {
  3143. if (this.args) {
  3144. this.args = visitor.visitArray(this.args);
  3145. }
  3146. },
  3147. //
  3148. // When evaluating a function call,
  3149. // we either find the function in the functionRegistry,
  3150. // in which case we call it, passing the evaluated arguments,
  3151. // if this returns null or we cannot find the function, we
  3152. // simply print it out as it appeared originally [2].
  3153. //
  3154. // The reason why we evaluate the arguments, is in the case where
  3155. // we try to pass a variable to a function, like: `saturate(@color)`.
  3156. // The function should receive the value, not the variable.
  3157. //
  3158. eval: function (context) {
  3159. var _this = this;
  3160. /**
  3161. * Turn off math for calc(), and switch back on for evaluating nested functions
  3162. */
  3163. var currentMathContext = context.mathOn;
  3164. context.mathOn = !this.calc;
  3165. if (this.calc || context.inCalc) {
  3166. context.enterCalc();
  3167. }
  3168. var exitCalc = function () {
  3169. if (_this.calc || context.inCalc) {
  3170. context.exitCalc();
  3171. }
  3172. context.mathOn = currentMathContext;
  3173. };
  3174. var result;
  3175. var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
  3176. if (funcCaller.isValid()) {
  3177. try {
  3178. result = funcCaller.call(this.args);
  3179. exitCalc();
  3180. }
  3181. catch (e) {
  3182. if (e.hasOwnProperty('line') && e.hasOwnProperty('column')) {
  3183. throw e;
  3184. }
  3185. throw {
  3186. type: e.type || 'Runtime',
  3187. message: "Error evaluating function `" + this.name + "`" + (e.message ? ": " + e.message : ''),
  3188. index: this.getIndex(),
  3189. filename: this.fileInfo().filename,
  3190. line: e.lineNumber,
  3191. column: e.columnNumber
  3192. };
  3193. }
  3194. }
  3195. if (result !== null && result !== undefined) {
  3196. // Results that that are not nodes are cast as Anonymous nodes
  3197. // Falsy values or booleans are returned as empty nodes
  3198. if (!(result instanceof Node)) {
  3199. if (!result || result === true) {
  3200. result = new Anonymous(null);
  3201. }
  3202. else {
  3203. result = new Anonymous(result.toString());
  3204. }
  3205. }
  3206. result._index = this._index;
  3207. result._fileInfo = this._fileInfo;
  3208. return result;
  3209. }
  3210. var args = this.args.map(function (a) { return a.eval(context); });
  3211. exitCalc();
  3212. return new Call(this.name, args, this.getIndex(), this.fileInfo());
  3213. },
  3214. genCSS: function (context, output) {
  3215. output.add(this.name + "(", this.fileInfo(), this.getIndex());
  3216. for (var i = 0; i < this.args.length; i++) {
  3217. this.args[i].genCSS(context, output);
  3218. if (i + 1 < this.args.length) {
  3219. output.add(', ');
  3220. }
  3221. }
  3222. output.add(')');
  3223. }
  3224. });
  3225. var Variable = function (name, index, currentFileInfo) {
  3226. this.name = name;
  3227. this._index = index;
  3228. this._fileInfo = currentFileInfo;
  3229. };
  3230. Variable.prototype = Object.assign(new Node(), {
  3231. type: 'Variable',
  3232. eval: function (context) {
  3233. var variable, name = this.name;
  3234. if (name.indexOf('@@') === 0) {
  3235. name = "@" + new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value;
  3236. }
  3237. if (this.evaluating) {
  3238. throw { type: 'Name',
  3239. message: "Recursive variable definition for " + name,
  3240. filename: this.fileInfo().filename,
  3241. index: this.getIndex() };
  3242. }
  3243. this.evaluating = true;
  3244. variable = this.find(context.frames, function (frame) {
  3245. var v = frame.variable(name);
  3246. if (v) {
  3247. if (v.important) {
  3248. var importantScope = context.importantScope[context.importantScope.length - 1];
  3249. importantScope.important = v.important;
  3250. }
  3251. // If in calc, wrap vars in a function call to cascade evaluate args first
  3252. if (context.inCalc) {
  3253. return (new Call('_SELF', [v.value])).eval(context);
  3254. }
  3255. else {
  3256. return v.value.eval(context);
  3257. }
  3258. }
  3259. });
  3260. if (variable) {
  3261. this.evaluating = false;
  3262. return variable;
  3263. }
  3264. else {
  3265. throw { type: 'Name',
  3266. message: "variable " + name + " is undefined",
  3267. filename: this.fileInfo().filename,
  3268. index: this.getIndex() };
  3269. }
  3270. },
  3271. find: function (obj, fun) {
  3272. for (var i = 0, r = void 0; i < obj.length; i++) {
  3273. r = fun.call(obj, obj[i]);
  3274. if (r) {
  3275. return r;
  3276. }
  3277. }
  3278. return null;
  3279. }
  3280. });
  3281. var Property = function (name, index, currentFileInfo) {
  3282. this.name = name;
  3283. this._index = index;
  3284. this._fileInfo = currentFileInfo;
  3285. };
  3286. Property.prototype = Object.assign(new Node(), {
  3287. type: 'Property',
  3288. eval: function (context) {
  3289. var property;
  3290. var name = this.name;
  3291. // TODO: shorten this reference
  3292. var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
  3293. if (this.evaluating) {
  3294. throw { type: 'Name',
  3295. message: "Recursive property reference for " + name,
  3296. filename: this.fileInfo().filename,
  3297. index: this.getIndex() };
  3298. }
  3299. this.evaluating = true;
  3300. property = this.find(context.frames, function (frame) {
  3301. var v;
  3302. var vArr = frame.property(name);
  3303. if (vArr) {
  3304. for (var i = 0; i < vArr.length; i++) {
  3305. v = vArr[i];
  3306. vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
  3307. }
  3308. mergeRules(vArr);
  3309. v = vArr[vArr.length - 1];
  3310. if (v.important) {
  3311. var importantScope = context.importantScope[context.importantScope.length - 1];
  3312. importantScope.important = v.important;
  3313. }
  3314. v = v.value.eval(context);
  3315. return v;
  3316. }
  3317. });
  3318. if (property) {
  3319. this.evaluating = false;
  3320. return property;
  3321. }
  3322. else {
  3323. throw { type: 'Name',
  3324. message: "Property '" + name + "' is undefined",
  3325. filename: this.currentFileInfo.filename,
  3326. index: this.index };
  3327. }
  3328. },
  3329. find: function (obj, fun) {
  3330. for (var i = 0, r = void 0; i < obj.length; i++) {
  3331. r = fun.call(obj, obj[i]);
  3332. if (r) {
  3333. return r;
  3334. }
  3335. }
  3336. return null;
  3337. }
  3338. });
  3339. var Attribute = function (key, op, value, cif) {
  3340. this.key = key;
  3341. this.op = op;
  3342. this.value = value;
  3343. this.cif = cif;
  3344. };
  3345. Attribute.prototype = Object.assign(new Node(), {
  3346. type: 'Attribute',
  3347. eval: function (context) {
  3348. 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, this.cif);
  3349. },
  3350. genCSS: function (context, output) {
  3351. output.add(this.toCSS(context));
  3352. },
  3353. toCSS: function (context) {
  3354. var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
  3355. if (this.op) {
  3356. value += this.op;
  3357. value += (this.value.toCSS ? this.value.toCSS(context) : this.value);
  3358. }
  3359. if (this.cif) {
  3360. value = value + " " + this.cif;
  3361. }
  3362. return "[" + value + "]";
  3363. }
  3364. });
  3365. var Quoted = function (str, content, escaped, index, currentFileInfo) {
  3366. this.escaped = (escaped == null) ? true : escaped;
  3367. this.value = content || '';
  3368. this.quote = str.charAt(0);
  3369. this._index = index;
  3370. this._fileInfo = currentFileInfo;
  3371. this.variableRegex = /@\{([\w-]+)\}/g;
  3372. this.propRegex = /\$\{([\w-]+)\}/g;
  3373. this.allowRoot = escaped;
  3374. };
  3375. Quoted.prototype = Object.assign(new Node(), {
  3376. type: 'Quoted',
  3377. genCSS: function (context, output) {
  3378. if (!this.escaped) {
  3379. output.add(this.quote, this.fileInfo(), this.getIndex());
  3380. }
  3381. output.add(this.value);
  3382. if (!this.escaped) {
  3383. output.add(this.quote);
  3384. }
  3385. },
  3386. containsVariables: function () {
  3387. return this.value.match(this.variableRegex);
  3388. },
  3389. eval: function (context) {
  3390. var that = this;
  3391. var value = this.value;
  3392. var variableReplacement = function (_, name) {
  3393. var v = new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context, true);
  3394. return (v instanceof Quoted) ? v.value : v.toCSS();
  3395. };
  3396. var propertyReplacement = function (_, name) {
  3397. var v = new Property("$" + name, that.getIndex(), that.fileInfo()).eval(context, true);
  3398. return (v instanceof Quoted) ? v.value : v.toCSS();
  3399. };
  3400. function iterativeReplace(value, regexp, replacementFnc) {
  3401. var evaluatedValue = value;
  3402. do {
  3403. value = evaluatedValue.toString();
  3404. evaluatedValue = value.replace(regexp, replacementFnc);
  3405. } while (value !== evaluatedValue);
  3406. return evaluatedValue;
  3407. }
  3408. value = iterativeReplace(value, this.variableRegex, variableReplacement);
  3409. value = iterativeReplace(value, this.propRegex, propertyReplacement);
  3410. return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
  3411. },
  3412. compare: function (other) {
  3413. // when comparing quoted strings allow the quote to differ
  3414. if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
  3415. return Node.numericCompare(this.value, other.value);
  3416. }
  3417. else {
  3418. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  3419. }
  3420. }
  3421. });
  3422. function escapePath(path) {
  3423. return path.replace(/[\(\)'"\s]/g, function (match) { return "\\" + match; });
  3424. }
  3425. var URL = function (val, index, currentFileInfo, isEvald) {
  3426. this.value = val;
  3427. this._index = index;
  3428. this._fileInfo = currentFileInfo;
  3429. this.isEvald = isEvald;
  3430. };
  3431. URL.prototype = Object.assign(new Node(), {
  3432. type: 'Url',
  3433. accept: function (visitor) {
  3434. this.value = visitor.visit(this.value);
  3435. },
  3436. genCSS: function (context, output) {
  3437. output.add('url(');
  3438. this.value.genCSS(context, output);
  3439. output.add(')');
  3440. },
  3441. eval: function (context) {
  3442. var val = this.value.eval(context);
  3443. var rootpath;
  3444. if (!this.isEvald) {
  3445. // Add the rootpath if the URL requires a rewrite
  3446. rootpath = this.fileInfo() && this.fileInfo().rootpath;
  3447. if (typeof rootpath === 'string' &&
  3448. typeof val.value === 'string' &&
  3449. context.pathRequiresRewrite(val.value)) {
  3450. if (!val.quote) {
  3451. rootpath = escapePath(rootpath);
  3452. }
  3453. val.value = context.rewritePath(val.value, rootpath);
  3454. }
  3455. else {
  3456. val.value = context.normalizePath(val.value);
  3457. }
  3458. // Add url args if enabled
  3459. if (context.urlArgs) {
  3460. if (!val.value.match(/^\s*data:/)) {
  3461. var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
  3462. var urlArgs = delimiter + context.urlArgs;
  3463. if (val.value.indexOf('#') !== -1) {
  3464. val.value = val.value.replace('#', urlArgs + "#");
  3465. }
  3466. else {
  3467. val.value += urlArgs;
  3468. }
  3469. }
  3470. }
  3471. }
  3472. return new URL(val, this.getIndex(), this.fileInfo(), true);
  3473. }
  3474. });
  3475. var Media = function (value, features, index, currentFileInfo, visibilityInfo) {
  3476. this._index = index;
  3477. this._fileInfo = currentFileInfo;
  3478. var selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
  3479. this.features = new Value(features);
  3480. this.rules = [new Ruleset(selectors, value)];
  3481. this.rules[0].allowImports = true;
  3482. this.copyVisibilityInfo(visibilityInfo);
  3483. this.allowRoot = true;
  3484. this.setParent(selectors, this);
  3485. this.setParent(this.features, this);
  3486. this.setParent(this.rules, this);
  3487. };
  3488. Media.prototype = Object.assign(new AtRule(), {
  3489. type: 'Media',
  3490. isRulesetLike: function () {
  3491. return true;
  3492. },
  3493. accept: function (visitor) {
  3494. if (this.features) {
  3495. this.features = visitor.visit(this.features);
  3496. }
  3497. if (this.rules) {
  3498. this.rules = visitor.visitArray(this.rules);
  3499. }
  3500. },
  3501. genCSS: function (context, output) {
  3502. output.add('@media ', this._fileInfo, this._index);
  3503. this.features.genCSS(context, output);
  3504. this.outputRuleset(context, output, this.rules);
  3505. },
  3506. eval: function (context) {
  3507. if (!context.mediaBlocks) {
  3508. context.mediaBlocks = [];
  3509. context.mediaPath = [];
  3510. }
  3511. var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
  3512. if (this.debugInfo) {
  3513. this.rules[0].debugInfo = this.debugInfo;
  3514. media.debugInfo = this.debugInfo;
  3515. }
  3516. media.features = this.features.eval(context);
  3517. context.mediaPath.push(media);
  3518. context.mediaBlocks.push(media);
  3519. this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
  3520. context.frames.unshift(this.rules[0]);
  3521. media.rules = [this.rules[0].eval(context)];
  3522. context.frames.shift();
  3523. context.mediaPath.pop();
  3524. return context.mediaPath.length === 0 ? media.evalTop(context) :
  3525. media.evalNested(context);
  3526. },
  3527. evalTop: function (context) {
  3528. var result = this;
  3529. // Render all dependent Media blocks.
  3530. if (context.mediaBlocks.length > 1) {
  3531. var selectors = (new Selector([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors();
  3532. result = new Ruleset(selectors, context.mediaBlocks);
  3533. result.multiMedia = true;
  3534. result.copyVisibilityInfo(this.visibilityInfo());
  3535. this.setParent(result, this);
  3536. }
  3537. delete context.mediaBlocks;
  3538. delete context.mediaPath;
  3539. return result;
  3540. },
  3541. evalNested: function (context) {
  3542. var i;
  3543. var value;
  3544. var path = context.mediaPath.concat([this]);
  3545. // Extract the media-query conditions separated with `,` (OR).
  3546. for (i = 0; i < path.length; i++) {
  3547. value = path[i].features instanceof Value ?
  3548. path[i].features.value : path[i].features;
  3549. path[i] = Array.isArray(value) ? value : [value];
  3550. }
  3551. // Trace all permutations to generate the resulting media-query.
  3552. //
  3553. // (a, b and c) with nested (d, e) ->
  3554. // a and d
  3555. // a and e
  3556. // b and c and d
  3557. // b and c and e
  3558. this.features = new Value(this.permute(path).map(function (path) {
  3559. path = path.map(function (fragment) { return fragment.toCSS ? fragment : new Anonymous(fragment); });
  3560. for (i = path.length - 1; i > 0; i--) {
  3561. path.splice(i, 0, new Anonymous('and'));
  3562. }
  3563. return new Expression(path);
  3564. }));
  3565. this.setParent(this.features, this);
  3566. // Fake a tree-node that doesn't output anything.
  3567. return new Ruleset([], []);
  3568. },
  3569. permute: function (arr) {
  3570. if (arr.length === 0) {
  3571. return [];
  3572. }
  3573. else if (arr.length === 1) {
  3574. return arr[0];
  3575. }
  3576. else {
  3577. var result = [];
  3578. var rest = this.permute(arr.slice(1));
  3579. for (var i = 0; i < rest.length; i++) {
  3580. for (var j = 0; j < arr[0].length; j++) {
  3581. result.push([arr[0][j]].concat(rest[i]));
  3582. }
  3583. }
  3584. return result;
  3585. }
  3586. },
  3587. bubbleSelectors: function (selectors) {
  3588. if (!selectors) {
  3589. return;
  3590. }
  3591. this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
  3592. this.setParent(this.rules, this);
  3593. }
  3594. });
  3595. //
  3596. // CSS @import node
  3597. //
  3598. // The general strategy here is that we don't want to wait
  3599. // for the parsing to be completed, before we start importing
  3600. // the file. That's because in the context of a browser,
  3601. // most of the time will be spent waiting for the server to respond.
  3602. //
  3603. // On creation, we push the import path to our import queue, though
  3604. // `import,push`, we also pass it a callback, which it'll call once
  3605. // the file has been fetched, and parsed.
  3606. //
  3607. var Import = function (path, features, options, index, currentFileInfo, visibilityInfo) {
  3608. this.options = options;
  3609. this._index = index;
  3610. this._fileInfo = currentFileInfo;
  3611. this.path = path;
  3612. this.features = features;
  3613. this.allowRoot = true;
  3614. if (this.options.less !== undefined || this.options.inline) {
  3615. this.css = !this.options.less || this.options.inline;
  3616. }
  3617. else {
  3618. var pathValue = this.getPath();
  3619. if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
  3620. this.css = true;
  3621. }
  3622. }
  3623. this.copyVisibilityInfo(visibilityInfo);
  3624. this.setParent(this.features, this);
  3625. this.setParent(this.path, this);
  3626. };
  3627. Import.prototype = Object.assign(new Node(), {
  3628. type: 'Import',
  3629. accept: function (visitor) {
  3630. if (this.features) {
  3631. this.features = visitor.visit(this.features);
  3632. }
  3633. this.path = visitor.visit(this.path);
  3634. if (!this.options.isPlugin && !this.options.inline && this.root) {
  3635. this.root = visitor.visit(this.root);
  3636. }
  3637. },
  3638. genCSS: function (context, output) {
  3639. if (this.css && this.path._fileInfo.reference === undefined) {
  3640. output.add('@import ', this._fileInfo, this._index);
  3641. this.path.genCSS(context, output);
  3642. if (this.features) {
  3643. output.add(' ');
  3644. this.features.genCSS(context, output);
  3645. }
  3646. output.add(';');
  3647. }
  3648. },
  3649. getPath: function () {
  3650. return (this.path instanceof URL) ?
  3651. this.path.value.value : this.path.value;
  3652. },
  3653. isVariableImport: function () {
  3654. var path = this.path;
  3655. if (path instanceof URL) {
  3656. path = path.value;
  3657. }
  3658. if (path instanceof Quoted) {
  3659. return path.containsVariables();
  3660. }
  3661. return true;
  3662. },
  3663. evalForImport: function (context) {
  3664. var path = this.path;
  3665. if (path instanceof URL) {
  3666. path = path.value;
  3667. }
  3668. return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
  3669. },
  3670. evalPath: function (context) {
  3671. var path = this.path.eval(context);
  3672. var fileInfo = this._fileInfo;
  3673. if (!(path instanceof URL)) {
  3674. // Add the rootpath if the URL requires a rewrite
  3675. var pathValue = path.value;
  3676. if (fileInfo &&
  3677. pathValue &&
  3678. context.pathRequiresRewrite(pathValue)) {
  3679. path.value = context.rewritePath(pathValue, fileInfo.rootpath);
  3680. }
  3681. else {
  3682. path.value = context.normalizePath(path.value);
  3683. }
  3684. }
  3685. return path;
  3686. },
  3687. eval: function (context) {
  3688. var result = this.doEval(context);
  3689. if (this.options.reference || this.blocksVisibility()) {
  3690. if (result.length || result.length === 0) {
  3691. result.forEach(function (node) {
  3692. node.addVisibilityBlock();
  3693. });
  3694. }
  3695. else {
  3696. result.addVisibilityBlock();
  3697. }
  3698. }
  3699. return result;
  3700. },
  3701. doEval: function (context) {
  3702. var ruleset;
  3703. var registry;
  3704. var features = this.features && this.features.eval(context);
  3705. if (this.options.isPlugin) {
  3706. if (this.root && this.root.eval) {
  3707. try {
  3708. this.root.eval(context);
  3709. }
  3710. catch (e) {
  3711. e.message = 'Plugin error during evaluation';
  3712. throw new LessError(e, this.root.imports, this.root.filename);
  3713. }
  3714. }
  3715. registry = context.frames[0] && context.frames[0].functionRegistry;
  3716. if (registry && this.root && this.root.functions) {
  3717. registry.addMultiple(this.root.functions);
  3718. }
  3719. return [];
  3720. }
  3721. if (this.skip) {
  3722. if (typeof this.skip === 'function') {
  3723. this.skip = this.skip();
  3724. }
  3725. if (this.skip) {
  3726. return [];
  3727. }
  3728. }
  3729. if (this.options.inline) {
  3730. var contents = new Anonymous(this.root, 0, {
  3731. filename: this.importedFilename,
  3732. reference: this.path._fileInfo && this.path._fileInfo.reference
  3733. }, true, true);
  3734. return this.features ? new Media([contents], this.features.value) : [contents];
  3735. }
  3736. else if (this.css) {
  3737. var newImport = new Import(this.evalPath(context), features, this.options, this._index);
  3738. if (!newImport.css && this.error) {
  3739. throw this.error;
  3740. }
  3741. return newImport;
  3742. }
  3743. else if (this.root) {
  3744. ruleset = new Ruleset(null, copyArray(this.root.rules));
  3745. ruleset.evalImports(context);
  3746. return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
  3747. }
  3748. else {
  3749. return [];
  3750. }
  3751. }
  3752. });
  3753. var JsEvalNode = function () { };
  3754. JsEvalNode.prototype = Object.assign(new Node(), {
  3755. evaluateJavaScript: function (expression, context) {
  3756. var result;
  3757. var that = this;
  3758. var evalContext = {};
  3759. if (!context.javascriptEnabled) {
  3760. throw { message: 'Inline JavaScript is not enabled. Is it set in your options?',
  3761. filename: this.fileInfo().filename,
  3762. index: this.getIndex() };
  3763. }
  3764. expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
  3765. return that.jsify(new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context));
  3766. });
  3767. try {
  3768. expression = new Function("return (" + expression + ")");
  3769. }
  3770. catch (e) {
  3771. throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`",
  3772. filename: this.fileInfo().filename,
  3773. index: this.getIndex() };
  3774. }
  3775. var variables = context.frames[0].variables();
  3776. for (var k in variables) {
  3777. if (variables.hasOwnProperty(k)) {
  3778. /* jshint loopfunc:true */
  3779. evalContext[k.slice(1)] = {
  3780. value: variables[k].value,
  3781. toJS: function () {
  3782. return this.value.eval(context).toCSS();
  3783. }
  3784. };
  3785. }
  3786. }
  3787. try {
  3788. result = expression.call(evalContext);
  3789. }
  3790. catch (e) {
  3791. throw { message: "JavaScript evaluation error: '" + e.name + ": " + e.message.replace(/["]/g, '\'') + "'",
  3792. filename: this.fileInfo().filename,
  3793. index: this.getIndex() };
  3794. }
  3795. return result;
  3796. },
  3797. jsify: function (obj) {
  3798. if (Array.isArray(obj.value) && (obj.value.length > 1)) {
  3799. return "[" + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + "]";
  3800. }
  3801. else {
  3802. return obj.toCSS();
  3803. }
  3804. }
  3805. });
  3806. var JavaScript = function (string, escaped, index, currentFileInfo) {
  3807. this.escaped = escaped;
  3808. this.expression = string;
  3809. this._index = index;
  3810. this._fileInfo = currentFileInfo;
  3811. };
  3812. JavaScript.prototype = Object.assign(new JsEvalNode(), {
  3813. type: 'JavaScript',
  3814. eval: function (context) {
  3815. var result = this.evaluateJavaScript(this.expression, context);
  3816. var type = typeof result;
  3817. if (type === 'number' && !isNaN(result)) {
  3818. return new Dimension(result);
  3819. }
  3820. else if (type === 'string') {
  3821. return new Quoted("\"" + result + "\"", result, this.escaped, this._index);
  3822. }
  3823. else if (Array.isArray(result)) {
  3824. return new Anonymous(result.join(', '));
  3825. }
  3826. else {
  3827. return new Anonymous(result);
  3828. }
  3829. }
  3830. });
  3831. var Assignment = function (key, val) {
  3832. this.key = key;
  3833. this.value = val;
  3834. };
  3835. Assignment.prototype = Object.assign(new Node(), {
  3836. type: 'Assignment',
  3837. accept: function (visitor) {
  3838. this.value = visitor.visit(this.value);
  3839. },
  3840. eval: function (context) {
  3841. if (this.value.eval) {
  3842. return new Assignment(this.key, this.value.eval(context));
  3843. }
  3844. return this;
  3845. },
  3846. genCSS: function (context, output) {
  3847. output.add(this.key + "=");
  3848. if (this.value.genCSS) {
  3849. this.value.genCSS(context, output);
  3850. }
  3851. else {
  3852. output.add(this.value);
  3853. }
  3854. }
  3855. });
  3856. var Condition = function (op, l, r, i, negate) {
  3857. this.op = op.trim();
  3858. this.lvalue = l;
  3859. this.rvalue = r;
  3860. this._index = i;
  3861. this.negate = negate;
  3862. };
  3863. Condition.prototype = Object.assign(new Node(), {
  3864. type: 'Condition',
  3865. accept: function (visitor) {
  3866. this.lvalue = visitor.visit(this.lvalue);
  3867. this.rvalue = visitor.visit(this.rvalue);
  3868. },
  3869. eval: function (context) {
  3870. var result = (function (op, a, b) {
  3871. switch (op) {
  3872. case 'and': return a && b;
  3873. case 'or': return a || b;
  3874. default:
  3875. switch (Node.compare(a, b)) {
  3876. case -1:
  3877. return op === '<' || op === '=<' || op === '<=';
  3878. case 0:
  3879. return op === '=' || op === '>=' || op === '=<' || op === '<=';
  3880. case 1:
  3881. return op === '>' || op === '>=';
  3882. default:
  3883. return false;
  3884. }
  3885. }
  3886. })(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
  3887. return this.negate ? !result : result;
  3888. }
  3889. });
  3890. var UnicodeDescriptor = function (value) {
  3891. this.value = value;
  3892. };
  3893. UnicodeDescriptor.prototype = Object.assign(new Node(), {
  3894. type: 'UnicodeDescriptor'
  3895. });
  3896. var Negative = function (node) {
  3897. this.value = node;
  3898. };
  3899. Negative.prototype = Object.assign(new Node(), {
  3900. type: 'Negative',
  3901. genCSS: function (context, output) {
  3902. output.add('-');
  3903. this.value.genCSS(context, output);
  3904. },
  3905. eval: function (context) {
  3906. if (context.isMathOn()) {
  3907. return (new Operation('*', [new Dimension(-1), this.value])).eval(context);
  3908. }
  3909. return new Negative(this.value.eval(context));
  3910. }
  3911. });
  3912. var Extend = function (selector, option, index, currentFileInfo, visibilityInfo) {
  3913. this.selector = selector;
  3914. this.option = option;
  3915. this.object_id = Extend.next_id++;
  3916. this.parent_ids = [this.object_id];
  3917. this._index = index;
  3918. this._fileInfo = currentFileInfo;
  3919. this.copyVisibilityInfo(visibilityInfo);
  3920. this.allowRoot = true;
  3921. switch (option) {
  3922. case 'all':
  3923. this.allowBefore = true;
  3924. this.allowAfter = true;
  3925. break;
  3926. default:
  3927. this.allowBefore = false;
  3928. this.allowAfter = false;
  3929. break;
  3930. }
  3931. this.setParent(this.selector, this);
  3932. };
  3933. Extend.prototype = Object.assign(new Node(), {
  3934. type: 'Extend',
  3935. accept: function (visitor) {
  3936. this.selector = visitor.visit(this.selector);
  3937. },
  3938. eval: function (context) {
  3939. return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  3940. },
  3941. clone: function (context) {
  3942. return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  3943. },
  3944. // it concatenates (joins) all selectors in selector array
  3945. findSelfSelectors: function (selectors) {
  3946. var selfElements = [], i, selectorElements;
  3947. for (i = 0; i < selectors.length; i++) {
  3948. selectorElements = selectors[i].elements;
  3949. // duplicate the logic in genCSS function inside the selector node.
  3950. // future TODO - move both logics into the selector joiner visitor
  3951. if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
  3952. selectorElements[0].combinator.value = ' ';
  3953. }
  3954. selfElements = selfElements.concat(selectors[i].elements);
  3955. }
  3956. this.selfSelectors = [new Selector(selfElements)];
  3957. this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
  3958. }
  3959. });
  3960. Extend.next_id = 0;
  3961. var VariableCall = function (variable, index, currentFileInfo) {
  3962. this.variable = variable;
  3963. this._index = index;
  3964. this._fileInfo = currentFileInfo;
  3965. this.allowRoot = true;
  3966. };
  3967. VariableCall.prototype = Object.assign(new Node(), {
  3968. type: 'VariableCall',
  3969. eval: function (context) {
  3970. var rules;
  3971. var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
  3972. var error = new LessError({ message: "Could not evaluate variable call " + this.variable });
  3973. if (!detachedRuleset.ruleset) {
  3974. if (detachedRuleset.rules) {
  3975. rules = detachedRuleset;
  3976. }
  3977. else if (Array.isArray(detachedRuleset)) {
  3978. rules = new Ruleset('', detachedRuleset);
  3979. }
  3980. else if (Array.isArray(detachedRuleset.value)) {
  3981. rules = new Ruleset('', detachedRuleset.value);
  3982. }
  3983. else {
  3984. throw error;
  3985. }
  3986. detachedRuleset = new DetachedRuleset(rules);
  3987. }
  3988. if (detachedRuleset.ruleset) {
  3989. return detachedRuleset.callEval(context);
  3990. }
  3991. throw error;
  3992. }
  3993. });
  3994. var NamespaceValue = function (ruleCall, lookups, index, fileInfo) {
  3995. this.value = ruleCall;
  3996. this.lookups = lookups;
  3997. this._index = index;
  3998. this._fileInfo = fileInfo;
  3999. };
  4000. NamespaceValue.prototype = Object.assign(new Node(), {
  4001. type: 'NamespaceValue',
  4002. eval: function (context) {
  4003. var i, name, rules = this.value.eval(context);
  4004. for (i = 0; i < this.lookups.length; i++) {
  4005. name = this.lookups[i];
  4006. /**
  4007. * Eval'd DRs return rulesets.
  4008. * Eval'd mixins return rules, so let's make a ruleset if we need it.
  4009. * We need to do this because of late parsing of values
  4010. */
  4011. if (Array.isArray(rules)) {
  4012. rules = new Ruleset([new Selector()], rules);
  4013. }
  4014. if (name === '') {
  4015. rules = rules.lastDeclaration();
  4016. }
  4017. else if (name.charAt(0) === '@') {
  4018. if (name.charAt(1) === '@') {
  4019. name = "@" + new Variable(name.substr(1)).eval(context).value;
  4020. }
  4021. if (rules.variables) {
  4022. rules = rules.variable(name);
  4023. }
  4024. if (!rules) {
  4025. throw { type: 'Name',
  4026. message: "variable " + name + " not found",
  4027. filename: this.fileInfo().filename,
  4028. index: this.getIndex() };
  4029. }
  4030. }
  4031. else {
  4032. if (name.substring(0, 2) === '$@') {
  4033. name = "$" + new Variable(name.substr(1)).eval(context).value;
  4034. }
  4035. else {
  4036. name = name.charAt(0) === '$' ? name : "$" + name;
  4037. }
  4038. if (rules.properties) {
  4039. rules = rules.property(name);
  4040. }
  4041. if (!rules) {
  4042. throw { type: 'Name',
  4043. message: "property \"" + name.substr(1) + "\" not found",
  4044. filename: this.fileInfo().filename,
  4045. index: this.getIndex() };
  4046. }
  4047. // Properties are an array of values, since a ruleset can have multiple props.
  4048. // We pick the last one (the "cascaded" value)
  4049. rules = rules[rules.length - 1];
  4050. }
  4051. if (rules.value) {
  4052. rules = rules.eval(context).value;
  4053. }
  4054. if (rules.ruleset) {
  4055. rules = rules.ruleset.eval(context);
  4056. }
  4057. }
  4058. return rules;
  4059. }
  4060. });
  4061. var Definition = function (name, params, rules, condition, variadic, frames, visibilityInfo) {
  4062. this.name = name || 'anonymous mixin';
  4063. this.selectors = [new Selector([new Element(null, name, false, this._index, this._fileInfo)])];
  4064. this.params = params;
  4065. this.condition = condition;
  4066. this.variadic = variadic;
  4067. this.arity = params.length;
  4068. this.rules = rules;
  4069. this._lookups = {};
  4070. var optionalParameters = [];
  4071. this.required = params.reduce(function (count, p) {
  4072. if (!p.name || (p.name && !p.value)) {
  4073. return count + 1;
  4074. }
  4075. else {
  4076. optionalParameters.push(p.name);
  4077. return count;
  4078. }
  4079. }, 0);
  4080. this.optionalParameters = optionalParameters;
  4081. this.frames = frames;
  4082. this.copyVisibilityInfo(visibilityInfo);
  4083. this.allowRoot = true;
  4084. };
  4085. Definition.prototype = Object.assign(new Ruleset(), {
  4086. type: 'MixinDefinition',
  4087. evalFirst: true,
  4088. accept: function (visitor) {
  4089. if (this.params && this.params.length) {
  4090. this.params = visitor.visitArray(this.params);
  4091. }
  4092. this.rules = visitor.visitArray(this.rules);
  4093. if (this.condition) {
  4094. this.condition = visitor.visit(this.condition);
  4095. }
  4096. },
  4097. evalParams: function (context, mixinEnv, args, evaldArguments) {
  4098. /* jshint boss:true */
  4099. var frame = new Ruleset(null, null);
  4100. var varargs;
  4101. var arg;
  4102. var params = copyArray(this.params);
  4103. var i;
  4104. var j;
  4105. var val;
  4106. var name;
  4107. var isNamedFound;
  4108. var argIndex;
  4109. var argsLength = 0;
  4110. if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
  4111. frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
  4112. }
  4113. mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
  4114. if (args) {
  4115. args = copyArray(args);
  4116. argsLength = args.length;
  4117. for (i = 0; i < argsLength; i++) {
  4118. arg = args[i];
  4119. if (name = (arg && arg.name)) {
  4120. isNamedFound = false;
  4121. for (j = 0; j < params.length; j++) {
  4122. if (!evaldArguments[j] && name === params[j].name) {
  4123. evaldArguments[j] = arg.value.eval(context);
  4124. frame.prependRule(new Declaration(name, arg.value.eval(context)));
  4125. isNamedFound = true;
  4126. break;
  4127. }
  4128. }
  4129. if (isNamedFound) {
  4130. args.splice(i, 1);
  4131. i--;
  4132. continue;
  4133. }
  4134. else {
  4135. throw { type: 'Runtime', message: "Named argument for " + this.name + " " + args[i].name + " not found" };
  4136. }
  4137. }
  4138. }
  4139. }
  4140. argIndex = 0;
  4141. for (i = 0; i < params.length; i++) {
  4142. if (evaldArguments[i]) {
  4143. continue;
  4144. }
  4145. arg = args && args[argIndex];
  4146. if (name = params[i].name) {
  4147. if (params[i].variadic) {
  4148. varargs = [];
  4149. for (j = argIndex; j < argsLength; j++) {
  4150. varargs.push(args[j].value.eval(context));
  4151. }
  4152. frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
  4153. }
  4154. else {
  4155. val = arg && arg.value;
  4156. if (val) {
  4157. // This was a mixin call, pass in a detached ruleset of it's eval'd rules
  4158. if (Array.isArray(val)) {
  4159. val = new DetachedRuleset(new Ruleset('', val));
  4160. }
  4161. else {
  4162. val = val.eval(context);
  4163. }
  4164. }
  4165. else if (params[i].value) {
  4166. val = params[i].value.eval(mixinEnv);
  4167. frame.resetCache();
  4168. }
  4169. else {
  4170. throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + " (" + argsLength + " for " + this.arity + ")" };
  4171. }
  4172. frame.prependRule(new Declaration(name, val));
  4173. evaldArguments[i] = val;
  4174. }
  4175. }
  4176. if (params[i].variadic && args) {
  4177. for (j = argIndex; j < argsLength; j++) {
  4178. evaldArguments[j] = args[j].value.eval(context);
  4179. }
  4180. }
  4181. argIndex++;
  4182. }
  4183. return frame;
  4184. },
  4185. makeImportant: function () {
  4186. var rules = !this.rules ? this.rules : this.rules.map(function (r) {
  4187. if (r.makeImportant) {
  4188. return r.makeImportant(true);
  4189. }
  4190. else {
  4191. return r;
  4192. }
  4193. });
  4194. var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
  4195. return result;
  4196. },
  4197. eval: function (context) {
  4198. return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
  4199. },
  4200. evalCall: function (context, args, important) {
  4201. var _arguments = [];
  4202. var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
  4203. var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
  4204. var rules;
  4205. var ruleset;
  4206. frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
  4207. rules = copyArray(this.rules);
  4208. ruleset = new Ruleset(null, rules);
  4209. ruleset.originalRuleset = this;
  4210. ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
  4211. if (important) {
  4212. ruleset = ruleset.makeImportant();
  4213. }
  4214. return ruleset;
  4215. },
  4216. matchCondition: function (args, context) {
  4217. if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context, /* the parameter variables */ new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])]
  4218. .concat(this.frames || []) // the parent namespace/mixin frames
  4219. .concat(context.frames)))) { // the current environment frames
  4220. return false;
  4221. }
  4222. return true;
  4223. },
  4224. matchArgs: function (args, context) {
  4225. var allArgsCnt = (args && args.length) || 0;
  4226. var len;
  4227. var optionalParameters = this.optionalParameters;
  4228. var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
  4229. if (optionalParameters.indexOf(p.name) < 0) {
  4230. return count + 1;
  4231. }
  4232. else {
  4233. return count;
  4234. }
  4235. }, 0);
  4236. if (!this.variadic) {
  4237. if (requiredArgsCnt < this.required) {
  4238. return false;
  4239. }
  4240. if (allArgsCnt > this.params.length) {
  4241. return false;
  4242. }
  4243. }
  4244. else {
  4245. if (requiredArgsCnt < (this.required - 1)) {
  4246. return false;
  4247. }
  4248. }
  4249. // check patterns
  4250. len = Math.min(requiredArgsCnt, this.arity);
  4251. for (var i = 0; i < len; i++) {
  4252. if (!this.params[i].name && !this.params[i].variadic) {
  4253. if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
  4254. return false;
  4255. }
  4256. }
  4257. }
  4258. return true;
  4259. }
  4260. });
  4261. var MixinCall = function (elements, args, index, currentFileInfo, important) {
  4262. this.selector = new Selector(elements);
  4263. this.arguments = args || [];
  4264. this._index = index;
  4265. this._fileInfo = currentFileInfo;
  4266. this.important = important;
  4267. this.allowRoot = true;
  4268. this.setParent(this.selector, this);
  4269. };
  4270. MixinCall.prototype = Object.assign(new Node(), {
  4271. type: 'MixinCall',
  4272. accept: function (visitor) {
  4273. if (this.selector) {
  4274. this.selector = visitor.visit(this.selector);
  4275. }
  4276. if (this.arguments.length) {
  4277. this.arguments = visitor.visitArray(this.arguments);
  4278. }
  4279. },
  4280. eval: function (context) {
  4281. var mixins;
  4282. var mixin;
  4283. var mixinPath;
  4284. var args = [];
  4285. var arg;
  4286. var argValue;
  4287. var rules = [];
  4288. var match = false;
  4289. var i;
  4290. var m;
  4291. var f;
  4292. var isRecursive;
  4293. var isOneFound;
  4294. var candidates = [];
  4295. var candidate;
  4296. var conditionResult = [];
  4297. var defaultResult;
  4298. var defFalseEitherCase = -1;
  4299. var defNone = 0;
  4300. var defTrue = 1;
  4301. var defFalse = 2;
  4302. var count;
  4303. var originalRuleset;
  4304. var noArgumentsFilter;
  4305. this.selector = this.selector.eval(context);
  4306. function calcDefGroup(mixin, mixinPath) {
  4307. var f, p, namespace;
  4308. for (f = 0; f < 2; f++) {
  4309. conditionResult[f] = true;
  4310. defaultFunc.value(f);
  4311. for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
  4312. namespace = mixinPath[p];
  4313. if (namespace.matchCondition) {
  4314. conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
  4315. }
  4316. }
  4317. if (mixin.matchCondition) {
  4318. conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
  4319. }
  4320. }
  4321. if (conditionResult[0] || conditionResult[1]) {
  4322. if (conditionResult[0] != conditionResult[1]) {
  4323. return conditionResult[1] ?
  4324. defTrue : defFalse;
  4325. }
  4326. return defNone;
  4327. }
  4328. return defFalseEitherCase;
  4329. }
  4330. for (i = 0; i < this.arguments.length; i++) {
  4331. arg = this.arguments[i];
  4332. argValue = arg.value.eval(context);
  4333. if (arg.expand && Array.isArray(argValue.value)) {
  4334. argValue = argValue.value;
  4335. for (m = 0; m < argValue.length; m++) {
  4336. args.push({ value: argValue[m] });
  4337. }
  4338. }
  4339. else {
  4340. args.push({ name: arg.name, value: argValue });
  4341. }
  4342. }
  4343. noArgumentsFilter = function (rule) { return rule.matchArgs(null, context); };
  4344. for (i = 0; i < context.frames.length; i++) {
  4345. if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
  4346. isOneFound = true;
  4347. // To make `default()` function independent of definition order we have two "subpasses" here.
  4348. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
  4349. // and build candidate list with corresponding flags. Then, when we know all possible matches,
  4350. // we make a final decision.
  4351. for (m = 0; m < mixins.length; m++) {
  4352. mixin = mixins[m].rule;
  4353. mixinPath = mixins[m].path;
  4354. isRecursive = false;
  4355. for (f = 0; f < context.frames.length; f++) {
  4356. if ((!(mixin instanceof Definition)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
  4357. isRecursive = true;
  4358. break;
  4359. }
  4360. }
  4361. if (isRecursive) {
  4362. continue;
  4363. }
  4364. if (mixin.matchArgs(args, context)) {
  4365. candidate = { mixin: mixin, group: calcDefGroup(mixin, mixinPath) };
  4366. if (candidate.group !== defFalseEitherCase) {
  4367. candidates.push(candidate);
  4368. }
  4369. match = true;
  4370. }
  4371. }
  4372. defaultFunc.reset();
  4373. count = [0, 0, 0];
  4374. for (m = 0; m < candidates.length; m++) {
  4375. count[candidates[m].group]++;
  4376. }
  4377. if (count[defNone] > 0) {
  4378. defaultResult = defFalse;
  4379. }
  4380. else {
  4381. defaultResult = defTrue;
  4382. if ((count[defTrue] + count[defFalse]) > 1) {
  4383. throw { type: 'Runtime',
  4384. message: "Ambiguous use of `default()` found when matching for `" + this.format(args) + "`",
  4385. index: this.getIndex(), filename: this.fileInfo().filename };
  4386. }
  4387. }
  4388. for (m = 0; m < candidates.length; m++) {
  4389. candidate = candidates[m].group;
  4390. if ((candidate === defNone) || (candidate === defaultResult)) {
  4391. try {
  4392. mixin = candidates[m].mixin;
  4393. if (!(mixin instanceof Definition)) {
  4394. originalRuleset = mixin.originalRuleset || mixin;
  4395. mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
  4396. mixin.originalRuleset = originalRuleset;
  4397. }
  4398. var newRules = mixin.evalCall(context, args, this.important).rules;
  4399. this._setVisibilityToReplacement(newRules);
  4400. Array.prototype.push.apply(rules, newRules);
  4401. }
  4402. catch (e) {
  4403. throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack };
  4404. }
  4405. }
  4406. }
  4407. if (match) {
  4408. return rules;
  4409. }
  4410. }
  4411. }
  4412. if (isOneFound) {
  4413. throw { type: 'Runtime',
  4414. message: "No matching definition was found for `" + this.format(args) + "`",
  4415. index: this.getIndex(), filename: this.fileInfo().filename };
  4416. }
  4417. else {
  4418. throw { type: 'Name',
  4419. message: this.selector.toCSS().trim() + " is undefined",
  4420. index: this.getIndex(), filename: this.fileInfo().filename };
  4421. }
  4422. },
  4423. _setVisibilityToReplacement: function (replacement) {
  4424. var i, rule;
  4425. if (this.blocksVisibility()) {
  4426. for (i = 0; i < replacement.length; i++) {
  4427. rule = replacement[i];
  4428. rule.addVisibilityBlock();
  4429. }
  4430. }
  4431. },
  4432. format: function (args) {
  4433. return this.selector.toCSS().trim() + "(" + (args ? args.map(function (a) {
  4434. var argValue = '';
  4435. if (a.name) {
  4436. argValue += a.name + ":";
  4437. }
  4438. if (a.value.toCSS) {
  4439. argValue += a.value.toCSS();
  4440. }
  4441. else {
  4442. argValue += '???';
  4443. }
  4444. return argValue;
  4445. }).join(', ') : '') + ")";
  4446. }
  4447. });
  4448. var tree = {
  4449. Node: Node,
  4450. Color: Color,
  4451. AtRule: AtRule,
  4452. DetachedRuleset: DetachedRuleset,
  4453. Operation: Operation,
  4454. Dimension: Dimension,
  4455. Unit: Unit,
  4456. Keyword: Keyword,
  4457. Variable: Variable,
  4458. Property: Property,
  4459. Ruleset: Ruleset,
  4460. Element: Element,
  4461. Attribute: Attribute,
  4462. Combinator: Combinator,
  4463. Selector: Selector,
  4464. Quoted: Quoted,
  4465. Expression: Expression,
  4466. Declaration: Declaration,
  4467. Call: Call,
  4468. URL: URL,
  4469. Import: Import,
  4470. Comment: Comment,
  4471. Anonymous: Anonymous,
  4472. Value: Value,
  4473. JavaScript: JavaScript,
  4474. Assignment: Assignment,
  4475. Condition: Condition,
  4476. Paren: Paren,
  4477. Media: Media,
  4478. UnicodeDescriptor: UnicodeDescriptor,
  4479. Negative: Negative,
  4480. Extend: Extend,
  4481. VariableCall: VariableCall,
  4482. NamespaceValue: NamespaceValue,
  4483. mixin: {
  4484. Call: MixinCall,
  4485. Definition: Definition
  4486. }
  4487. };
  4488. var AbstractFileManager = /** @class */ (function () {
  4489. function AbstractFileManager() {
  4490. }
  4491. AbstractFileManager.prototype.getPath = function (filename) {
  4492. var j = filename.lastIndexOf('?');
  4493. if (j > 0) {
  4494. filename = filename.slice(0, j);
  4495. }
  4496. j = filename.lastIndexOf('/');
  4497. if (j < 0) {
  4498. j = filename.lastIndexOf('\\');
  4499. }
  4500. if (j < 0) {
  4501. return '';
  4502. }
  4503. return filename.slice(0, j + 1);
  4504. };
  4505. AbstractFileManager.prototype.tryAppendExtension = function (path, ext) {
  4506. return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
  4507. };
  4508. AbstractFileManager.prototype.tryAppendLessExtension = function (path) {
  4509. return this.tryAppendExtension(path, '.less');
  4510. };
  4511. AbstractFileManager.prototype.supportsSync = function () {
  4512. return false;
  4513. };
  4514. AbstractFileManager.prototype.alwaysMakePathsAbsolute = function () {
  4515. return false;
  4516. };
  4517. AbstractFileManager.prototype.isPathAbsolute = function (filename) {
  4518. return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
  4519. };
  4520. // TODO: pull out / replace?
  4521. AbstractFileManager.prototype.join = function (basePath, laterPath) {
  4522. if (!basePath) {
  4523. return laterPath;
  4524. }
  4525. return basePath + laterPath;
  4526. };
  4527. AbstractFileManager.prototype.pathDiff = function (url, baseUrl) {
  4528. // diff between two paths to create a relative path
  4529. var urlParts = this.extractUrlParts(url);
  4530. var baseUrlParts = this.extractUrlParts(baseUrl);
  4531. var i;
  4532. var max;
  4533. var urlDirectories;
  4534. var baseUrlDirectories;
  4535. var diff = '';
  4536. if (urlParts.hostPart !== baseUrlParts.hostPart) {
  4537. return '';
  4538. }
  4539. max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
  4540. for (i = 0; i < max; i++) {
  4541. if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
  4542. break;
  4543. }
  4544. }
  4545. baseUrlDirectories = baseUrlParts.directories.slice(i);
  4546. urlDirectories = urlParts.directories.slice(i);
  4547. for (i = 0; i < baseUrlDirectories.length - 1; i++) {
  4548. diff += '../';
  4549. }
  4550. for (i = 0; i < urlDirectories.length - 1; i++) {
  4551. diff += urlDirectories[i] + "/";
  4552. }
  4553. return diff;
  4554. };
  4555. // helper function, not part of API
  4556. AbstractFileManager.prototype.extractUrlParts = function (url, baseUrl) {
  4557. // urlParts[1] = protocol://hostname/ OR /
  4558. // urlParts[2] = / if path relative to host base
  4559. // urlParts[3] = directories
  4560. // urlParts[4] = filename
  4561. // urlParts[5] = parameters
  4562. var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i;
  4563. var urlParts = url.match(urlPartsRegex);
  4564. var returner = {};
  4565. var rawDirectories = [];
  4566. var directories = [];
  4567. var i;
  4568. var baseUrlParts;
  4569. if (!urlParts) {
  4570. throw new Error("Could not parse sheet href - '" + url + "'");
  4571. }
  4572. // Stylesheets in IE don't always return the full path
  4573. if (baseUrl && (!urlParts[1] || urlParts[2])) {
  4574. baseUrlParts = baseUrl.match(urlPartsRegex);
  4575. if (!baseUrlParts) {
  4576. throw new Error("Could not parse page url - '" + baseUrl + "'");
  4577. }
  4578. urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
  4579. if (!urlParts[2]) {
  4580. urlParts[3] = baseUrlParts[3] + urlParts[3];
  4581. }
  4582. }
  4583. if (urlParts[3]) {
  4584. rawDirectories = urlParts[3].replace(/\\/g, '/').split('/');
  4585. // collapse '..' and skip '.'
  4586. for (i = 0; i < rawDirectories.length; i++) {
  4587. if (rawDirectories[i] === '..') {
  4588. directories.pop();
  4589. }
  4590. else if (rawDirectories[i] !== '.') {
  4591. directories.push(rawDirectories[i]);
  4592. }
  4593. }
  4594. }
  4595. returner.hostPart = urlParts[1];
  4596. returner.directories = directories;
  4597. returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
  4598. returner.path = (urlParts[1] || '') + directories.join('/');
  4599. returner.filename = urlParts[4];
  4600. returner.fileUrl = returner.path + (urlParts[4] || '');
  4601. returner.url = returner.fileUrl + (urlParts[5] || '');
  4602. return returner;
  4603. };
  4604. return AbstractFileManager;
  4605. }());
  4606. var AbstractPluginLoader = /** @class */ (function () {
  4607. function AbstractPluginLoader() {
  4608. // Implemented by Node.js plugin loader
  4609. this.require = function () {
  4610. return null;
  4611. };
  4612. }
  4613. AbstractPluginLoader.prototype.evalPlugin = function (contents, context, imports, pluginOptions, fileInfo) {
  4614. var loader, registry, pluginObj, localModule, pluginManager, filename, result;
  4615. pluginManager = context.pluginManager;
  4616. if (fileInfo) {
  4617. if (typeof fileInfo === 'string') {
  4618. filename = fileInfo;
  4619. }
  4620. else {
  4621. filename = fileInfo.filename;
  4622. }
  4623. }
  4624. var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
  4625. if (filename) {
  4626. pluginObj = pluginManager.get(filename);
  4627. if (pluginObj) {
  4628. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  4629. if (result) {
  4630. return result;
  4631. }
  4632. try {
  4633. if (pluginObj.use) {
  4634. pluginObj.use.call(this.context, pluginObj);
  4635. }
  4636. }
  4637. catch (e) {
  4638. e.message = e.message || 'Error during @plugin call';
  4639. return new LessError(e, imports, filename);
  4640. }
  4641. return pluginObj;
  4642. }
  4643. }
  4644. localModule = {
  4645. exports: {},
  4646. pluginManager: pluginManager,
  4647. fileInfo: fileInfo
  4648. };
  4649. registry = functionRegistry.create();
  4650. var registerPlugin = function (obj) {
  4651. pluginObj = obj;
  4652. };
  4653. try {
  4654. loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
  4655. loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
  4656. }
  4657. catch (e) {
  4658. return new LessError(e, imports, filename);
  4659. }
  4660. if (!pluginObj) {
  4661. pluginObj = localModule.exports;
  4662. }
  4663. pluginObj = this.validatePlugin(pluginObj, filename, shortname);
  4664. if (pluginObj instanceof LessError) {
  4665. return pluginObj;
  4666. }
  4667. if (pluginObj) {
  4668. pluginObj.imports = imports;
  4669. pluginObj.filename = filename;
  4670. // For < 3.x (or unspecified minVersion) - setOptions() before install()
  4671. if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
  4672. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  4673. if (result) {
  4674. return result;
  4675. }
  4676. }
  4677. // Run on first load
  4678. pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
  4679. pluginObj.functions = registry.getLocalFunctions();
  4680. // Need to call setOptions again because the pluginObj might have functions
  4681. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  4682. if (result) {
  4683. return result;
  4684. }
  4685. // Run every @plugin call
  4686. try {
  4687. if (pluginObj.use) {
  4688. pluginObj.use.call(this.context, pluginObj);
  4689. }
  4690. }
  4691. catch (e) {
  4692. e.message = e.message || 'Error during @plugin call';
  4693. return new LessError(e, imports, filename);
  4694. }
  4695. }
  4696. else {
  4697. return new LessError({ message: 'Not a valid plugin' }, imports, filename);
  4698. }
  4699. return pluginObj;
  4700. };
  4701. AbstractPluginLoader.prototype.trySetOptions = function (plugin, filename, name, options) {
  4702. if (options && !plugin.setOptions) {
  4703. return new LessError({
  4704. message: "Options have been provided but the plugin " + name + " does not support any options."
  4705. });
  4706. }
  4707. try {
  4708. plugin.setOptions && plugin.setOptions(options);
  4709. }
  4710. catch (e) {
  4711. return new LessError(e);
  4712. }
  4713. };
  4714. AbstractPluginLoader.prototype.validatePlugin = function (plugin, filename, name) {
  4715. if (plugin) {
  4716. // support plugins being a function
  4717. // so that the plugin can be more usable programmatically
  4718. if (typeof plugin === 'function') {
  4719. plugin = new plugin();
  4720. }
  4721. if (plugin.minVersion) {
  4722. if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
  4723. return new LessError({
  4724. message: "Plugin " + name + " requires version " + this.versionToString(plugin.minVersion)
  4725. });
  4726. }
  4727. }
  4728. return plugin;
  4729. }
  4730. return null;
  4731. };
  4732. AbstractPluginLoader.prototype.compareVersion = function (aVersion, bVersion) {
  4733. if (typeof aVersion === 'string') {
  4734. aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
  4735. aVersion.shift();
  4736. }
  4737. for (var i = 0; i < aVersion.length; i++) {
  4738. if (aVersion[i] !== bVersion[i]) {
  4739. return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
  4740. }
  4741. }
  4742. return 0;
  4743. };
  4744. AbstractPluginLoader.prototype.versionToString = function (version) {
  4745. var versionString = '';
  4746. for (var i = 0; i < version.length; i++) {
  4747. versionString += (versionString ? '.' : '') + version[i];
  4748. }
  4749. return versionString;
  4750. };
  4751. AbstractPluginLoader.prototype.printUsage = function (plugins) {
  4752. for (var i = 0; i < plugins.length; i++) {
  4753. var plugin = plugins[i];
  4754. if (plugin.printUsage) {
  4755. plugin.printUsage();
  4756. }
  4757. }
  4758. };
  4759. return AbstractPluginLoader;
  4760. }());
  4761. var _visitArgs = { visitDeeper: true };
  4762. var _hasIndexed = false;
  4763. function _noop(node) {
  4764. return node;
  4765. }
  4766. function indexNodeTypes(parent, ticker) {
  4767. // add .typeIndex to tree node types for lookup table
  4768. var key, child;
  4769. for (key in parent) {
  4770. /* eslint guard-for-in: 0 */
  4771. child = parent[key];
  4772. switch (typeof child) {
  4773. case 'function':
  4774. // ignore bound functions directly on tree which do not have a prototype
  4775. // or aren't nodes
  4776. if (child.prototype && child.prototype.type) {
  4777. child.prototype.typeIndex = ticker++;
  4778. }
  4779. break;
  4780. case 'object':
  4781. ticker = indexNodeTypes(child, ticker);
  4782. break;
  4783. }
  4784. }
  4785. return ticker;
  4786. }
  4787. var Visitor = /** @class */ (function () {
  4788. function Visitor(implementation) {
  4789. this._implementation = implementation;
  4790. this._visitInCache = {};
  4791. this._visitOutCache = {};
  4792. if (!_hasIndexed) {
  4793. indexNodeTypes(tree, 1);
  4794. _hasIndexed = true;
  4795. }
  4796. }
  4797. Visitor.prototype.visit = function (node) {
  4798. if (!node) {
  4799. return node;
  4800. }
  4801. var nodeTypeIndex = node.typeIndex;
  4802. if (!nodeTypeIndex) {
  4803. // MixinCall args aren't a node type?
  4804. if (node.value && node.value.typeIndex) {
  4805. this.visit(node.value);
  4806. }
  4807. return node;
  4808. }
  4809. var impl = this._implementation;
  4810. var func = this._visitInCache[nodeTypeIndex];
  4811. var funcOut = this._visitOutCache[nodeTypeIndex];
  4812. var visitArgs = _visitArgs;
  4813. var fnName;
  4814. visitArgs.visitDeeper = true;
  4815. if (!func) {
  4816. fnName = "visit" + node.type;
  4817. func = impl[fnName] || _noop;
  4818. funcOut = impl[fnName + "Out"] || _noop;
  4819. this._visitInCache[nodeTypeIndex] = func;
  4820. this._visitOutCache[nodeTypeIndex] = funcOut;
  4821. }
  4822. if (func !== _noop) {
  4823. var newNode = func.call(impl, node, visitArgs);
  4824. if (node && impl.isReplacing) {
  4825. node = newNode;
  4826. }
  4827. }
  4828. if (visitArgs.visitDeeper && node) {
  4829. if (node.length) {
  4830. for (var i = 0, cnt = node.length; i < cnt; i++) {
  4831. if (node[i].accept) {
  4832. node[i].accept(this);
  4833. }
  4834. }
  4835. }
  4836. else if (node.accept) {
  4837. node.accept(this);
  4838. }
  4839. }
  4840. if (funcOut != _noop) {
  4841. funcOut.call(impl, node);
  4842. }
  4843. return node;
  4844. };
  4845. Visitor.prototype.visitArray = function (nodes, nonReplacing) {
  4846. if (!nodes) {
  4847. return nodes;
  4848. }
  4849. var cnt = nodes.length;
  4850. var i;
  4851. // Non-replacing
  4852. if (nonReplacing || !this._implementation.isReplacing) {
  4853. for (i = 0; i < cnt; i++) {
  4854. this.visit(nodes[i]);
  4855. }
  4856. return nodes;
  4857. }
  4858. // Replacing
  4859. var out = [];
  4860. for (i = 0; i < cnt; i++) {
  4861. var evald = this.visit(nodes[i]);
  4862. if (evald === undefined) {
  4863. continue;
  4864. }
  4865. if (!evald.splice) {
  4866. out.push(evald);
  4867. }
  4868. else if (evald.length) {
  4869. this.flatten(evald, out);
  4870. }
  4871. }
  4872. return out;
  4873. };
  4874. Visitor.prototype.flatten = function (arr, out) {
  4875. if (!out) {
  4876. out = [];
  4877. }
  4878. var cnt, i, item, nestedCnt, j, nestedItem;
  4879. for (i = 0, cnt = arr.length; i < cnt; i++) {
  4880. item = arr[i];
  4881. if (item === undefined) {
  4882. continue;
  4883. }
  4884. if (!item.splice) {
  4885. out.push(item);
  4886. continue;
  4887. }
  4888. for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
  4889. nestedItem = item[j];
  4890. if (nestedItem === undefined) {
  4891. continue;
  4892. }
  4893. if (!nestedItem.splice) {
  4894. out.push(nestedItem);
  4895. }
  4896. else if (nestedItem.length) {
  4897. this.flatten(nestedItem, out);
  4898. }
  4899. }
  4900. }
  4901. return out;
  4902. };
  4903. return Visitor;
  4904. }());
  4905. var ImportSequencer = /** @class */ (function () {
  4906. function ImportSequencer(onSequencerEmpty) {
  4907. this.imports = [];
  4908. this.variableImports = [];
  4909. this._onSequencerEmpty = onSequencerEmpty;
  4910. this._currentDepth = 0;
  4911. }
  4912. ImportSequencer.prototype.addImport = function (callback) {
  4913. var importSequencer = this, importItem = {
  4914. callback: callback,
  4915. args: null,
  4916. isReady: false
  4917. };
  4918. this.imports.push(importItem);
  4919. return function () {
  4920. importItem.args = Array.prototype.slice.call(arguments, 0);
  4921. importItem.isReady = true;
  4922. importSequencer.tryRun();
  4923. };
  4924. };
  4925. ImportSequencer.prototype.addVariableImport = function (callback) {
  4926. this.variableImports.push(callback);
  4927. };
  4928. ImportSequencer.prototype.tryRun = function () {
  4929. this._currentDepth++;
  4930. try {
  4931. while (true) {
  4932. while (this.imports.length > 0) {
  4933. var importItem = this.imports[0];
  4934. if (!importItem.isReady) {
  4935. return;
  4936. }
  4937. this.imports = this.imports.slice(1);
  4938. importItem.callback.apply(null, importItem.args);
  4939. }
  4940. if (this.variableImports.length === 0) {
  4941. break;
  4942. }
  4943. var variableImport = this.variableImports[0];
  4944. this.variableImports = this.variableImports.slice(1);
  4945. variableImport();
  4946. }
  4947. }
  4948. finally {
  4949. this._currentDepth--;
  4950. }
  4951. if (this._currentDepth === 0 && this._onSequencerEmpty) {
  4952. this._onSequencerEmpty();
  4953. }
  4954. };
  4955. return ImportSequencer;
  4956. }());
  4957. var ImportVisitor = function (importer, finish) {
  4958. this._visitor = new Visitor(this);
  4959. this._importer = importer;
  4960. this._finish = finish;
  4961. this.context = new contexts.Eval();
  4962. this.importCount = 0;
  4963. this.onceFileDetectionMap = {};
  4964. this.recursionDetector = {};
  4965. this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
  4966. };
  4967. ImportVisitor.prototype = {
  4968. isReplacing: false,
  4969. run: function (root) {
  4970. try {
  4971. // process the contents
  4972. this._visitor.visit(root);
  4973. }
  4974. catch (e) {
  4975. this.error = e;
  4976. }
  4977. this.isFinished = true;
  4978. this._sequencer.tryRun();
  4979. },
  4980. _onSequencerEmpty: function () {
  4981. if (!this.isFinished) {
  4982. return;
  4983. }
  4984. this._finish(this.error);
  4985. },
  4986. visitImport: function (importNode, visitArgs) {
  4987. var inlineCSS = importNode.options.inline;
  4988. if (!importNode.css || inlineCSS) {
  4989. var context = new contexts.Eval(this.context, copyArray(this.context.frames));
  4990. var importParent = context.frames[0];
  4991. this.importCount++;
  4992. if (importNode.isVariableImport()) {
  4993. this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
  4994. }
  4995. else {
  4996. this.processImportNode(importNode, context, importParent);
  4997. }
  4998. }
  4999. visitArgs.visitDeeper = false;
  5000. },
  5001. processImportNode: function (importNode, context, importParent) {
  5002. var evaldImportNode;
  5003. var inlineCSS = importNode.options.inline;
  5004. try {
  5005. evaldImportNode = importNode.evalForImport(context);
  5006. }
  5007. catch (e) {
  5008. if (!e.filename) {
  5009. e.index = importNode.getIndex();
  5010. e.filename = importNode.fileInfo().filename;
  5011. }
  5012. // attempt to eval properly and treat as css
  5013. importNode.css = true;
  5014. // if that fails, this error will be thrown
  5015. importNode.error = e;
  5016. }
  5017. if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
  5018. if (evaldImportNode.options.multiple) {
  5019. context.importMultiple = true;
  5020. }
  5021. // try appending if we haven't determined if it is css or not
  5022. var tryAppendLessExtension = evaldImportNode.css === undefined;
  5023. for (var i = 0; i < importParent.rules.length; i++) {
  5024. if (importParent.rules[i] === importNode) {
  5025. importParent.rules[i] = evaldImportNode;
  5026. break;
  5027. }
  5028. }
  5029. var onImported = this.onImported.bind(this, evaldImportNode, context), sequencedOnImported = this._sequencer.addImport(onImported);
  5030. this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
  5031. }
  5032. else {
  5033. this.importCount--;
  5034. if (this.isFinished) {
  5035. this._sequencer.tryRun();
  5036. }
  5037. }
  5038. },
  5039. onImported: function (importNode, context, e, root, importedAtRoot, fullPath) {
  5040. if (e) {
  5041. if (!e.filename) {
  5042. e.index = importNode.getIndex();
  5043. e.filename = importNode.fileInfo().filename;
  5044. }
  5045. this.error = e;
  5046. }
  5047. var importVisitor = this, inlineCSS = importNode.options.inline, isPlugin = importNode.options.isPlugin, isOptional = importNode.options.optional, duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
  5048. if (!context.importMultiple) {
  5049. if (duplicateImport) {
  5050. importNode.skip = true;
  5051. }
  5052. else {
  5053. importNode.skip = function () {
  5054. if (fullPath in importVisitor.onceFileDetectionMap) {
  5055. return true;
  5056. }
  5057. importVisitor.onceFileDetectionMap[fullPath] = true;
  5058. return false;
  5059. };
  5060. }
  5061. }
  5062. if (!fullPath && isOptional) {
  5063. importNode.skip = true;
  5064. }
  5065. if (root) {
  5066. importNode.root = root;
  5067. importNode.importedFilename = fullPath;
  5068. if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
  5069. importVisitor.recursionDetector[fullPath] = true;
  5070. var oldContext = this.context;
  5071. this.context = context;
  5072. try {
  5073. this._visitor.visit(root);
  5074. }
  5075. catch (e) {
  5076. this.error = e;
  5077. }
  5078. this.context = oldContext;
  5079. }
  5080. }
  5081. importVisitor.importCount--;
  5082. if (importVisitor.isFinished) {
  5083. importVisitor._sequencer.tryRun();
  5084. }
  5085. },
  5086. visitDeclaration: function (declNode, visitArgs) {
  5087. if (declNode.value.type === 'DetachedRuleset') {
  5088. this.context.frames.unshift(declNode);
  5089. }
  5090. else {
  5091. visitArgs.visitDeeper = false;
  5092. }
  5093. },
  5094. visitDeclarationOut: function (declNode) {
  5095. if (declNode.value.type === 'DetachedRuleset') {
  5096. this.context.frames.shift();
  5097. }
  5098. },
  5099. visitAtRule: function (atRuleNode, visitArgs) {
  5100. this.context.frames.unshift(atRuleNode);
  5101. },
  5102. visitAtRuleOut: function (atRuleNode) {
  5103. this.context.frames.shift();
  5104. },
  5105. visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
  5106. this.context.frames.unshift(mixinDefinitionNode);
  5107. },
  5108. visitMixinDefinitionOut: function (mixinDefinitionNode) {
  5109. this.context.frames.shift();
  5110. },
  5111. visitRuleset: function (rulesetNode, visitArgs) {
  5112. this.context.frames.unshift(rulesetNode);
  5113. },
  5114. visitRulesetOut: function (rulesetNode) {
  5115. this.context.frames.shift();
  5116. },
  5117. visitMedia: function (mediaNode, visitArgs) {
  5118. this.context.frames.unshift(mediaNode.rules[0]);
  5119. },
  5120. visitMediaOut: function (mediaNode) {
  5121. this.context.frames.shift();
  5122. }
  5123. };
  5124. var SetTreeVisibilityVisitor = /** @class */ (function () {
  5125. function SetTreeVisibilityVisitor(visible) {
  5126. this.visible = visible;
  5127. }
  5128. SetTreeVisibilityVisitor.prototype.run = function (root) {
  5129. this.visit(root);
  5130. };
  5131. SetTreeVisibilityVisitor.prototype.visitArray = function (nodes) {
  5132. if (!nodes) {
  5133. return nodes;
  5134. }
  5135. var cnt = nodes.length;
  5136. var i;
  5137. for (i = 0; i < cnt; i++) {
  5138. this.visit(nodes[i]);
  5139. }
  5140. return nodes;
  5141. };
  5142. SetTreeVisibilityVisitor.prototype.visit = function (node) {
  5143. if (!node) {
  5144. return node;
  5145. }
  5146. if (node.constructor === Array) {
  5147. return this.visitArray(node);
  5148. }
  5149. if (!node.blocksVisibility || node.blocksVisibility()) {
  5150. return node;
  5151. }
  5152. if (this.visible) {
  5153. node.ensureVisibility();
  5154. }
  5155. else {
  5156. node.ensureInvisibility();
  5157. }
  5158. node.accept(this);
  5159. return node;
  5160. };
  5161. return SetTreeVisibilityVisitor;
  5162. }());
  5163. /* jshint loopfunc:true */
  5164. var ExtendFinderVisitor = /** @class */ (function () {
  5165. function ExtendFinderVisitor() {
  5166. this._visitor = new Visitor(this);
  5167. this.contexts = [];
  5168. this.allExtendsStack = [[]];
  5169. }
  5170. ExtendFinderVisitor.prototype.run = function (root) {
  5171. root = this._visitor.visit(root);
  5172. root.allExtends = this.allExtendsStack[0];
  5173. return root;
  5174. };
  5175. ExtendFinderVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
  5176. visitArgs.visitDeeper = false;
  5177. };
  5178. ExtendFinderVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
  5179. visitArgs.visitDeeper = false;
  5180. };
  5181. ExtendFinderVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
  5182. if (rulesetNode.root) {
  5183. return;
  5184. }
  5185. var i;
  5186. var j;
  5187. var extend;
  5188. var allSelectorsExtendList = [];
  5189. var extendList;
  5190. // get &:extend(.a); rules which apply to all selectors in this ruleset
  5191. var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0;
  5192. for (i = 0; i < ruleCnt; i++) {
  5193. if (rulesetNode.rules[i] instanceof tree.Extend) {
  5194. allSelectorsExtendList.push(rules[i]);
  5195. rulesetNode.extendOnEveryPath = true;
  5196. }
  5197. }
  5198. // now find every selector and apply the extends that apply to all extends
  5199. // and the ones which apply to an individual extend
  5200. var paths = rulesetNode.paths;
  5201. for (i = 0; i < paths.length; i++) {
  5202. var selectorPath = paths[i], selector = selectorPath[selectorPath.length - 1], selExtendList = selector.extendList;
  5203. extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList)
  5204. : allSelectorsExtendList;
  5205. if (extendList) {
  5206. extendList = extendList.map(function (allSelectorsExtend) {
  5207. return allSelectorsExtend.clone();
  5208. });
  5209. }
  5210. for (j = 0; j < extendList.length; j++) {
  5211. this.foundExtends = true;
  5212. extend = extendList[j];
  5213. extend.findSelfSelectors(selectorPath);
  5214. extend.ruleset = rulesetNode;
  5215. if (j === 0) {
  5216. extend.firstExtendOnThisSelectorPath = true;
  5217. }
  5218. this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
  5219. }
  5220. }
  5221. this.contexts.push(rulesetNode.selectors);
  5222. };
  5223. ExtendFinderVisitor.prototype.visitRulesetOut = function (rulesetNode) {
  5224. if (!rulesetNode.root) {
  5225. this.contexts.length = this.contexts.length - 1;
  5226. }
  5227. };
  5228. ExtendFinderVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
  5229. mediaNode.allExtends = [];
  5230. this.allExtendsStack.push(mediaNode.allExtends);
  5231. };
  5232. ExtendFinderVisitor.prototype.visitMediaOut = function (mediaNode) {
  5233. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  5234. };
  5235. ExtendFinderVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
  5236. atRuleNode.allExtends = [];
  5237. this.allExtendsStack.push(atRuleNode.allExtends);
  5238. };
  5239. ExtendFinderVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
  5240. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  5241. };
  5242. return ExtendFinderVisitor;
  5243. }());
  5244. var ProcessExtendsVisitor = /** @class */ (function () {
  5245. function ProcessExtendsVisitor() {
  5246. this._visitor = new Visitor(this);
  5247. }
  5248. ProcessExtendsVisitor.prototype.run = function (root) {
  5249. var extendFinder = new ExtendFinderVisitor();
  5250. this.extendIndices = {};
  5251. extendFinder.run(root);
  5252. if (!extendFinder.foundExtends) {
  5253. return root;
  5254. }
  5255. root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
  5256. this.allExtendsStack = [root.allExtends];
  5257. var newRoot = this._visitor.visit(root);
  5258. this.checkExtendsForNonMatched(root.allExtends);
  5259. return newRoot;
  5260. };
  5261. ProcessExtendsVisitor.prototype.checkExtendsForNonMatched = function (extendList) {
  5262. var indices = this.extendIndices;
  5263. extendList.filter(function (extend) {
  5264. return !extend.hasFoundMatches && extend.parent_ids.length == 1;
  5265. }).forEach(function (extend) {
  5266. var selector = '_unknown_';
  5267. try {
  5268. selector = extend.selector.toCSS({});
  5269. }
  5270. catch (_) { }
  5271. if (!indices[extend.index + " " + selector]) {
  5272. indices[extend.index + " " + selector] = true;
  5273. logger$1.warn("extend '" + selector + "' has no matches");
  5274. }
  5275. });
  5276. };
  5277. ProcessExtendsVisitor.prototype.doExtendChaining = function (extendsList, extendsListTarget, iterationCount) {
  5278. //
  5279. // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
  5280. // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
  5281. // this means this new extend can then go and alter other extends
  5282. //
  5283. // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
  5284. // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
  5285. // processed if we look at each selector at a time, as is done in visitRuleset
  5286. var extendIndex;
  5287. var targetExtendIndex;
  5288. var matches;
  5289. var extendsToAdd = [];
  5290. var newSelector;
  5291. var extendVisitor = this;
  5292. var selectorPath;
  5293. var extend;
  5294. var targetExtend;
  5295. var newExtend;
  5296. iterationCount = iterationCount || 0;
  5297. // loop through comparing every extend with every target extend.
  5298. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
  5299. // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
  5300. // and the second is the target.
  5301. // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
  5302. // case when processing media queries
  5303. for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
  5304. for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
  5305. extend = extendsList[extendIndex];
  5306. targetExtend = extendsListTarget[targetExtendIndex];
  5307. // look for circular references
  5308. if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
  5309. continue;
  5310. }
  5311. // find a match in the target extends self selector (the bit before :extend)
  5312. selectorPath = [targetExtend.selfSelectors[0]];
  5313. matches = extendVisitor.findMatch(extend, selectorPath);
  5314. if (matches.length) {
  5315. extend.hasFoundMatches = true;
  5316. // we found a match, so for each self selector..
  5317. extend.selfSelectors.forEach(function (selfSelector) {
  5318. var info = targetExtend.visibilityInfo();
  5319. // process the extend as usual
  5320. newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible());
  5321. // but now we create a new extend from it
  5322. newExtend = new (tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
  5323. newExtend.selfSelectors = newSelector;
  5324. // add the extend onto the list of extends for that selector
  5325. newSelector[newSelector.length - 1].extendList = [newExtend];
  5326. // record that we need to add it.
  5327. extendsToAdd.push(newExtend);
  5328. newExtend.ruleset = targetExtend.ruleset;
  5329. // remember its parents for circular references
  5330. newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
  5331. // only process the selector once.. if we have :extend(.a,.b) then multiple
  5332. // extends will look at the same selector path, so when extending
  5333. // we know that any others will be duplicates in terms of what is added to the css
  5334. if (targetExtend.firstExtendOnThisSelectorPath) {
  5335. newExtend.firstExtendOnThisSelectorPath = true;
  5336. targetExtend.ruleset.paths.push(newSelector);
  5337. }
  5338. });
  5339. }
  5340. }
  5341. }
  5342. if (extendsToAdd.length) {
  5343. // try to detect circular references to stop a stack overflow.
  5344. // may no longer be needed.
  5345. this.extendChainCount++;
  5346. if (iterationCount > 100) {
  5347. var selectorOne = '{unable to calculate}';
  5348. var selectorTwo = '{unable to calculate}';
  5349. try {
  5350. selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
  5351. selectorTwo = extendsToAdd[0].selector.toCSS();
  5352. }
  5353. catch (e) { }
  5354. throw { message: "extend circular reference detected. One of the circular extends is currently:" + selectorOne + ":extend(" + selectorTwo + ")" };
  5355. }
  5356. // now process the new extends on the existing rules so that we can handle a extending b extending c extending
  5357. // d extending e...
  5358. return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
  5359. }
  5360. else {
  5361. return extendsToAdd;
  5362. }
  5363. };
  5364. ProcessExtendsVisitor.prototype.visitDeclaration = function (ruleNode, visitArgs) {
  5365. visitArgs.visitDeeper = false;
  5366. };
  5367. ProcessExtendsVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
  5368. visitArgs.visitDeeper = false;
  5369. };
  5370. ProcessExtendsVisitor.prototype.visitSelector = function (selectorNode, visitArgs) {
  5371. visitArgs.visitDeeper = false;
  5372. };
  5373. ProcessExtendsVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
  5374. if (rulesetNode.root) {
  5375. return;
  5376. }
  5377. var matches;
  5378. var pathIndex;
  5379. var extendIndex;
  5380. var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
  5381. var selectorsToAdd = [];
  5382. var extendVisitor = this;
  5383. var selectorPath;
  5384. // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
  5385. for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
  5386. for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
  5387. selectorPath = rulesetNode.paths[pathIndex];
  5388. // extending extends happens initially, before the main pass
  5389. if (rulesetNode.extendOnEveryPath) {
  5390. continue;
  5391. }
  5392. var extendList = selectorPath[selectorPath.length - 1].extendList;
  5393. if (extendList && extendList.length) {
  5394. continue;
  5395. }
  5396. matches = this.findMatch(allExtends[extendIndex], selectorPath);
  5397. if (matches.length) {
  5398. allExtends[extendIndex].hasFoundMatches = true;
  5399. allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
  5400. var extendedSelectors;
  5401. extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
  5402. selectorsToAdd.push(extendedSelectors);
  5403. });
  5404. }
  5405. }
  5406. }
  5407. rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
  5408. };
  5409. ProcessExtendsVisitor.prototype.findMatch = function (extend, haystackSelectorPath) {
  5410. //
  5411. // look through the haystack selector path to try and find the needle - extend.selector
  5412. // returns an array of selector matches that can then be replaced
  5413. //
  5414. var haystackSelectorIndex;
  5415. var hackstackSelector;
  5416. var hackstackElementIndex;
  5417. var haystackElement;
  5418. var targetCombinator;
  5419. var i;
  5420. var extendVisitor = this;
  5421. var needleElements = extend.selector.elements;
  5422. var potentialMatches = [];
  5423. var potentialMatch;
  5424. var matches = [];
  5425. // loop through the haystack elements
  5426. for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
  5427. hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
  5428. for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
  5429. haystackElement = hackstackSelector.elements[hackstackElementIndex];
  5430. // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
  5431. if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
  5432. potentialMatches.push({ pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0,
  5433. initialCombinator: haystackElement.combinator });
  5434. }
  5435. for (i = 0; i < potentialMatches.length; i++) {
  5436. potentialMatch = potentialMatches[i];
  5437. // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
  5438. // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
  5439. // work out what the resulting combinator will be
  5440. targetCombinator = haystackElement.combinator.value;
  5441. if (targetCombinator === '' && hackstackElementIndex === 0) {
  5442. targetCombinator = ' ';
  5443. }
  5444. // if we don't match, null our match to indicate failure
  5445. if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
  5446. (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
  5447. potentialMatch = null;
  5448. }
  5449. else {
  5450. potentialMatch.matched++;
  5451. }
  5452. // if we are still valid and have finished, test whether we have elements after and whether these are allowed
  5453. if (potentialMatch) {
  5454. potentialMatch.finished = potentialMatch.matched === needleElements.length;
  5455. if (potentialMatch.finished &&
  5456. (!extend.allowAfter &&
  5457. (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) {
  5458. potentialMatch = null;
  5459. }
  5460. }
  5461. // if null we remove, if not, we are still valid, so either push as a valid match or continue
  5462. if (potentialMatch) {
  5463. if (potentialMatch.finished) {
  5464. potentialMatch.length = needleElements.length;
  5465. potentialMatch.endPathIndex = haystackSelectorIndex;
  5466. potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
  5467. potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
  5468. matches.push(potentialMatch);
  5469. }
  5470. }
  5471. else {
  5472. potentialMatches.splice(i, 1);
  5473. i--;
  5474. }
  5475. }
  5476. }
  5477. }
  5478. return matches;
  5479. };
  5480. ProcessExtendsVisitor.prototype.isElementValuesEqual = function (elementValue1, elementValue2) {
  5481. if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
  5482. return elementValue1 === elementValue2;
  5483. }
  5484. if (elementValue1 instanceof tree.Attribute) {
  5485. if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
  5486. return false;
  5487. }
  5488. if (!elementValue1.value || !elementValue2.value) {
  5489. if (elementValue1.value || elementValue2.value) {
  5490. return false;
  5491. }
  5492. return true;
  5493. }
  5494. elementValue1 = elementValue1.value.value || elementValue1.value;
  5495. elementValue2 = elementValue2.value.value || elementValue2.value;
  5496. return elementValue1 === elementValue2;
  5497. }
  5498. elementValue1 = elementValue1.value;
  5499. elementValue2 = elementValue2.value;
  5500. if (elementValue1 instanceof tree.Selector) {
  5501. if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
  5502. return false;
  5503. }
  5504. for (var i = 0; i < elementValue1.elements.length; i++) {
  5505. if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
  5506. if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
  5507. return false;
  5508. }
  5509. }
  5510. if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
  5511. return false;
  5512. }
  5513. }
  5514. return true;
  5515. }
  5516. return false;
  5517. };
  5518. ProcessExtendsVisitor.prototype.extendSelector = function (matches, selectorPath, replacementSelector, isVisible) {
  5519. // for a set of matches, replace each match with the replacement selector
  5520. var currentSelectorPathIndex = 0, currentSelectorPathElementIndex = 0, path = [], matchIndex, selector, firstElement, match, newElements;
  5521. for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
  5522. match = matches[matchIndex];
  5523. selector = selectorPath[match.pathIndex];
  5524. firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
  5525. if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
  5526. path[path.length - 1].elements = path[path.length - 1]
  5527. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  5528. currentSelectorPathElementIndex = 0;
  5529. currentSelectorPathIndex++;
  5530. }
  5531. newElements = selector.elements
  5532. .slice(currentSelectorPathElementIndex, match.index)
  5533. .concat([firstElement])
  5534. .concat(replacementSelector.elements.slice(1));
  5535. if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
  5536. path[path.length - 1].elements =
  5537. path[path.length - 1].elements.concat(newElements);
  5538. }
  5539. else {
  5540. path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
  5541. path.push(new tree.Selector(newElements));
  5542. }
  5543. currentSelectorPathIndex = match.endPathIndex;
  5544. currentSelectorPathElementIndex = match.endPathElementIndex;
  5545. if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
  5546. currentSelectorPathElementIndex = 0;
  5547. currentSelectorPathIndex++;
  5548. }
  5549. }
  5550. if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
  5551. path[path.length - 1].elements = path[path.length - 1]
  5552. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  5553. currentSelectorPathIndex++;
  5554. }
  5555. path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
  5556. path = path.map(function (currentValue) {
  5557. // we can re-use elements here, because the visibility property matters only for selectors
  5558. var derived = currentValue.createDerived(currentValue.elements);
  5559. if (isVisible) {
  5560. derived.ensureVisibility();
  5561. }
  5562. else {
  5563. derived.ensureInvisibility();
  5564. }
  5565. return derived;
  5566. });
  5567. return path;
  5568. };
  5569. ProcessExtendsVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
  5570. var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  5571. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
  5572. this.allExtendsStack.push(newAllExtends);
  5573. };
  5574. ProcessExtendsVisitor.prototype.visitMediaOut = function (mediaNode) {
  5575. var lastIndex = this.allExtendsStack.length - 1;
  5576. this.allExtendsStack.length = lastIndex;
  5577. };
  5578. ProcessExtendsVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
  5579. var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  5580. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
  5581. this.allExtendsStack.push(newAllExtends);
  5582. };
  5583. ProcessExtendsVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
  5584. var lastIndex = this.allExtendsStack.length - 1;
  5585. this.allExtendsStack.length = lastIndex;
  5586. };
  5587. return ProcessExtendsVisitor;
  5588. }());
  5589. var JoinSelectorVisitor = /** @class */ (function () {
  5590. function JoinSelectorVisitor() {
  5591. this.contexts = [[]];
  5592. this._visitor = new Visitor(this);
  5593. }
  5594. JoinSelectorVisitor.prototype.run = function (root) {
  5595. return this._visitor.visit(root);
  5596. };
  5597. JoinSelectorVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
  5598. visitArgs.visitDeeper = false;
  5599. };
  5600. JoinSelectorVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
  5601. visitArgs.visitDeeper = false;
  5602. };
  5603. JoinSelectorVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
  5604. var context = this.contexts[this.contexts.length - 1];
  5605. var paths = [];
  5606. var selectors;
  5607. this.contexts.push(paths);
  5608. if (!rulesetNode.root) {
  5609. selectors = rulesetNode.selectors;
  5610. if (selectors) {
  5611. selectors = selectors.filter(function (selector) { return selector.getIsOutput(); });
  5612. rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
  5613. if (selectors) {
  5614. rulesetNode.joinSelectors(paths, context, selectors);
  5615. }
  5616. }
  5617. if (!selectors) {
  5618. rulesetNode.rules = null;
  5619. }
  5620. rulesetNode.paths = paths;
  5621. }
  5622. };
  5623. JoinSelectorVisitor.prototype.visitRulesetOut = function (rulesetNode) {
  5624. this.contexts.length = this.contexts.length - 1;
  5625. };
  5626. JoinSelectorVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
  5627. var context = this.contexts[this.contexts.length - 1];
  5628. mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
  5629. };
  5630. JoinSelectorVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
  5631. var context = this.contexts[this.contexts.length - 1];
  5632. if (atRuleNode.rules && atRuleNode.rules.length) {
  5633. atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);
  5634. }
  5635. };
  5636. return JoinSelectorVisitor;
  5637. }());
  5638. var CSSVisitorUtils = /** @class */ (function () {
  5639. function CSSVisitorUtils(context) {
  5640. this._visitor = new Visitor(this);
  5641. this._context = context;
  5642. }
  5643. CSSVisitorUtils.prototype.containsSilentNonBlockedChild = function (bodyRules) {
  5644. var rule;
  5645. if (!bodyRules) {
  5646. return false;
  5647. }
  5648. for (var r = 0; r < bodyRules.length; r++) {
  5649. rule = bodyRules[r];
  5650. if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
  5651. // the atrule contains something that was referenced (likely by extend)
  5652. // therefore it needs to be shown in output too
  5653. return true;
  5654. }
  5655. }
  5656. return false;
  5657. };
  5658. CSSVisitorUtils.prototype.keepOnlyVisibleChilds = function (owner) {
  5659. if (owner && owner.rules) {
  5660. owner.rules = owner.rules.filter(function (thing) { return thing.isVisible(); });
  5661. }
  5662. };
  5663. CSSVisitorUtils.prototype.isEmpty = function (owner) {
  5664. return (owner && owner.rules)
  5665. ? (owner.rules.length === 0) : true;
  5666. };
  5667. CSSVisitorUtils.prototype.hasVisibleSelector = function (rulesetNode) {
  5668. return (rulesetNode && rulesetNode.paths)
  5669. ? (rulesetNode.paths.length > 0) : false;
  5670. };
  5671. CSSVisitorUtils.prototype.resolveVisibility = function (node, originalRules) {
  5672. if (!node.blocksVisibility()) {
  5673. if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
  5674. return;
  5675. }
  5676. return node;
  5677. }
  5678. var compiledRulesBody = node.rules[0];
  5679. this.keepOnlyVisibleChilds(compiledRulesBody);
  5680. if (this.isEmpty(compiledRulesBody)) {
  5681. return;
  5682. }
  5683. node.ensureVisibility();
  5684. node.removeVisibilityBlock();
  5685. return node;
  5686. };
  5687. CSSVisitorUtils.prototype.isVisibleRuleset = function (rulesetNode) {
  5688. if (rulesetNode.firstRoot) {
  5689. return true;
  5690. }
  5691. if (this.isEmpty(rulesetNode)) {
  5692. return false;
  5693. }
  5694. if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
  5695. return false;
  5696. }
  5697. return true;
  5698. };
  5699. return CSSVisitorUtils;
  5700. }());
  5701. var ToCSSVisitor = function (context) {
  5702. this._visitor = new Visitor(this);
  5703. this._context = context;
  5704. this.utils = new CSSVisitorUtils(context);
  5705. };
  5706. ToCSSVisitor.prototype = {
  5707. isReplacing: true,
  5708. run: function (root) {
  5709. return this._visitor.visit(root);
  5710. },
  5711. visitDeclaration: function (declNode, visitArgs) {
  5712. if (declNode.blocksVisibility() || declNode.variable) {
  5713. return;
  5714. }
  5715. return declNode;
  5716. },
  5717. visitMixinDefinition: function (mixinNode, visitArgs) {
  5718. // mixin definitions do not get eval'd - this means they keep state
  5719. // so we have to clear that state here so it isn't used if toCSS is called twice
  5720. mixinNode.frames = [];
  5721. },
  5722. visitExtend: function (extendNode, visitArgs) {
  5723. },
  5724. visitComment: function (commentNode, visitArgs) {
  5725. if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
  5726. return;
  5727. }
  5728. return commentNode;
  5729. },
  5730. visitMedia: function (mediaNode, visitArgs) {
  5731. var originalRules = mediaNode.rules[0].rules;
  5732. mediaNode.accept(this._visitor);
  5733. visitArgs.visitDeeper = false;
  5734. return this.utils.resolveVisibility(mediaNode, originalRules);
  5735. },
  5736. visitImport: function (importNode, visitArgs) {
  5737. if (importNode.blocksVisibility()) {
  5738. return;
  5739. }
  5740. return importNode;
  5741. },
  5742. visitAtRule: function (atRuleNode, visitArgs) {
  5743. if (atRuleNode.rules && atRuleNode.rules.length) {
  5744. return this.visitAtRuleWithBody(atRuleNode, visitArgs);
  5745. }
  5746. else {
  5747. return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
  5748. }
  5749. },
  5750. visitAnonymous: function (anonymousNode, visitArgs) {
  5751. if (!anonymousNode.blocksVisibility()) {
  5752. anonymousNode.accept(this._visitor);
  5753. return anonymousNode;
  5754. }
  5755. },
  5756. visitAtRuleWithBody: function (atRuleNode, visitArgs) {
  5757. // if there is only one nested ruleset and that one has no path, then it is
  5758. // just fake ruleset
  5759. function hasFakeRuleset(atRuleNode) {
  5760. var bodyRules = atRuleNode.rules;
  5761. return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
  5762. }
  5763. function getBodyRules(atRuleNode) {
  5764. var nodeRules = atRuleNode.rules;
  5765. if (hasFakeRuleset(atRuleNode)) {
  5766. return nodeRules[0].rules;
  5767. }
  5768. return nodeRules;
  5769. }
  5770. // it is still true that it is only one ruleset in array
  5771. // this is last such moment
  5772. // process childs
  5773. var originalRules = getBodyRules(atRuleNode);
  5774. atRuleNode.accept(this._visitor);
  5775. visitArgs.visitDeeper = false;
  5776. if (!this.utils.isEmpty(atRuleNode)) {
  5777. this._mergeRules(atRuleNode.rules[0].rules);
  5778. }
  5779. return this.utils.resolveVisibility(atRuleNode, originalRules);
  5780. },
  5781. visitAtRuleWithoutBody: function (atRuleNode, visitArgs) {
  5782. if (atRuleNode.blocksVisibility()) {
  5783. return;
  5784. }
  5785. if (atRuleNode.name === '@charset') {
  5786. // Only output the debug info together with subsequent @charset definitions
  5787. // a comment (or @media statement) before the actual @charset atrule would
  5788. // be considered illegal css as it has to be on the first line
  5789. if (this.charset) {
  5790. if (atRuleNode.debugInfo) {
  5791. var comment = new tree.Comment("/* " + atRuleNode.toCSS(this._context).replace(/\n/g, '') + " */\n");
  5792. comment.debugInfo = atRuleNode.debugInfo;
  5793. return this._visitor.visit(comment);
  5794. }
  5795. return;
  5796. }
  5797. this.charset = true;
  5798. }
  5799. return atRuleNode;
  5800. },
  5801. checkValidNodes: function (rules, isRoot) {
  5802. if (!rules) {
  5803. return;
  5804. }
  5805. for (var i = 0; i < rules.length; i++) {
  5806. var ruleNode = rules[i];
  5807. if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
  5808. throw { message: 'Properties must be inside selector blocks. They cannot be in the root',
  5809. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
  5810. }
  5811. if (ruleNode instanceof tree.Call) {
  5812. throw { message: "Function '" + ruleNode.name + "' did not return a root node",
  5813. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
  5814. }
  5815. if (ruleNode.type && !ruleNode.allowRoot) {
  5816. throw { message: ruleNode.type + " node returned by a function is not valid here",
  5817. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
  5818. }
  5819. }
  5820. },
  5821. visitRuleset: function (rulesetNode, visitArgs) {
  5822. // at this point rulesets are nested into each other
  5823. var rule;
  5824. var rulesets = [];
  5825. this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
  5826. if (!rulesetNode.root) {
  5827. // remove invisible paths
  5828. this._compileRulesetPaths(rulesetNode);
  5829. // remove rulesets from this ruleset body and compile them separately
  5830. var nodeRules = rulesetNode.rules;
  5831. var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
  5832. for (var i = 0; i < nodeRuleCnt;) {
  5833. rule = nodeRules[i];
  5834. if (rule && rule.rules) {
  5835. // visit because we are moving them out from being a child
  5836. rulesets.push(this._visitor.visit(rule));
  5837. nodeRules.splice(i, 1);
  5838. nodeRuleCnt--;
  5839. continue;
  5840. }
  5841. i++;
  5842. }
  5843. // accept the visitor to remove rules and refactor itself
  5844. // then we can decide nogw whether we want it or not
  5845. // compile body
  5846. if (nodeRuleCnt > 0) {
  5847. rulesetNode.accept(this._visitor);
  5848. }
  5849. else {
  5850. rulesetNode.rules = null;
  5851. }
  5852. visitArgs.visitDeeper = false;
  5853. }
  5854. else { // if (! rulesetNode.root) {
  5855. rulesetNode.accept(this._visitor);
  5856. visitArgs.visitDeeper = false;
  5857. }
  5858. if (rulesetNode.rules) {
  5859. this._mergeRules(rulesetNode.rules);
  5860. this._removeDuplicateRules(rulesetNode.rules);
  5861. }
  5862. // now decide whether we keep the ruleset
  5863. if (this.utils.isVisibleRuleset(rulesetNode)) {
  5864. rulesetNode.ensureVisibility();
  5865. rulesets.splice(0, 0, rulesetNode);
  5866. }
  5867. if (rulesets.length === 1) {
  5868. return rulesets[0];
  5869. }
  5870. return rulesets;
  5871. },
  5872. _compileRulesetPaths: function (rulesetNode) {
  5873. if (rulesetNode.paths) {
  5874. rulesetNode.paths = rulesetNode.paths
  5875. .filter(function (p) {
  5876. var i;
  5877. if (p[0].elements[0].combinator.value === ' ') {
  5878. p[0].elements[0].combinator = new (tree.Combinator)('');
  5879. }
  5880. for (i = 0; i < p.length; i++) {
  5881. if (p[i].isVisible() && p[i].getIsOutput()) {
  5882. return true;
  5883. }
  5884. }
  5885. return false;
  5886. });
  5887. }
  5888. },
  5889. _removeDuplicateRules: function (rules) {
  5890. if (!rules) {
  5891. return;
  5892. }
  5893. // remove duplicates
  5894. var ruleCache = {};
  5895. var ruleList;
  5896. var rule;
  5897. var i;
  5898. for (i = rules.length - 1; i >= 0; i--) {
  5899. rule = rules[i];
  5900. if (rule instanceof tree.Declaration) {
  5901. if (!ruleCache[rule.name]) {
  5902. ruleCache[rule.name] = rule;
  5903. }
  5904. else {
  5905. ruleList = ruleCache[rule.name];
  5906. if (ruleList instanceof tree.Declaration) {
  5907. ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
  5908. }
  5909. var ruleCSS = rule.toCSS(this._context);
  5910. if (ruleList.indexOf(ruleCSS) !== -1) {
  5911. rules.splice(i, 1);
  5912. }
  5913. else {
  5914. ruleList.push(ruleCSS);
  5915. }
  5916. }
  5917. }
  5918. }
  5919. },
  5920. _mergeRules: function (rules) {
  5921. if (!rules) {
  5922. return;
  5923. }
  5924. var groups = {};
  5925. var groupsArr = [];
  5926. for (var i = 0; i < rules.length; i++) {
  5927. var rule = rules[i];
  5928. if (rule.merge) {
  5929. var key = rule.name;
  5930. groups[key] ? rules.splice(i--, 1) :
  5931. groupsArr.push(groups[key] = []);
  5932. groups[key].push(rule);
  5933. }
  5934. }
  5935. groupsArr.forEach(function (group) {
  5936. if (group.length > 0) {
  5937. var result_1 = group[0];
  5938. var space_1 = [];
  5939. var comma_1 = [new tree.Expression(space_1)];
  5940. group.forEach(function (rule) {
  5941. if ((rule.merge === '+') && (space_1.length > 0)) {
  5942. comma_1.push(new tree.Expression(space_1 = []));
  5943. }
  5944. space_1.push(rule.value);
  5945. result_1.important = result_1.important || rule.important;
  5946. });
  5947. result_1.value = new tree.Value(comma_1);
  5948. }
  5949. });
  5950. }
  5951. };
  5952. var visitors = {
  5953. Visitor: Visitor,
  5954. ImportVisitor: ImportVisitor,
  5955. MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
  5956. ExtendVisitor: ProcessExtendsVisitor,
  5957. JoinSelectorVisitor: JoinSelectorVisitor,
  5958. ToCSSVisitor: ToCSSVisitor
  5959. };
  5960. // Split the input into chunks.
  5961. function chunker (input, fail) {
  5962. var len = input.length;
  5963. var level = 0;
  5964. var parenLevel = 0;
  5965. var lastOpening;
  5966. var lastOpeningParen;
  5967. var lastMultiComment;
  5968. var lastMultiCommentEndBrace;
  5969. var chunks = [];
  5970. var emitFrom = 0;
  5971. var chunkerCurrentIndex;
  5972. var currentChunkStartIndex;
  5973. var cc;
  5974. var cc2;
  5975. var matched;
  5976. function emitChunk(force) {
  5977. var len = chunkerCurrentIndex - emitFrom;
  5978. if (((len < 512) && !force) || !len) {
  5979. return;
  5980. }
  5981. chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
  5982. emitFrom = chunkerCurrentIndex + 1;
  5983. }
  5984. for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  5985. cc = input.charCodeAt(chunkerCurrentIndex);
  5986. if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
  5987. // a-z or whitespace
  5988. continue;
  5989. }
  5990. switch (cc) {
  5991. case 40: // (
  5992. parenLevel++;
  5993. lastOpeningParen = chunkerCurrentIndex;
  5994. continue;
  5995. case 41: // )
  5996. if (--parenLevel < 0) {
  5997. return fail('missing opening `(`', chunkerCurrentIndex);
  5998. }
  5999. continue;
  6000. case 59: // ;
  6001. if (!parenLevel) {
  6002. emitChunk();
  6003. }
  6004. continue;
  6005. case 123: // {
  6006. level++;
  6007. lastOpening = chunkerCurrentIndex;
  6008. continue;
  6009. case 125: // }
  6010. if (--level < 0) {
  6011. return fail('missing opening `{`', chunkerCurrentIndex);
  6012. }
  6013. if (!level && !parenLevel) {
  6014. emitChunk();
  6015. }
  6016. continue;
  6017. case 92: // \
  6018. if (chunkerCurrentIndex < len - 1) {
  6019. chunkerCurrentIndex++;
  6020. continue;
  6021. }
  6022. return fail('unescaped `\\`', chunkerCurrentIndex);
  6023. case 34:
  6024. case 39:
  6025. case 96: // ", ' and `
  6026. matched = 0;
  6027. currentChunkStartIndex = chunkerCurrentIndex;
  6028. for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6029. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6030. if (cc2 > 96) {
  6031. continue;
  6032. }
  6033. if (cc2 == cc) {
  6034. matched = 1;
  6035. break;
  6036. }
  6037. if (cc2 == 92) { // \
  6038. if (chunkerCurrentIndex == len - 1) {
  6039. return fail('unescaped `\\`', chunkerCurrentIndex);
  6040. }
  6041. chunkerCurrentIndex++;
  6042. }
  6043. }
  6044. if (matched) {
  6045. continue;
  6046. }
  6047. return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex);
  6048. case 47: // /, check for comment
  6049. if (parenLevel || (chunkerCurrentIndex == len - 1)) {
  6050. continue;
  6051. }
  6052. cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
  6053. if (cc2 == 47) {
  6054. // //, find lnfeed
  6055. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6056. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6057. if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) {
  6058. break;
  6059. }
  6060. }
  6061. }
  6062. else if (cc2 == 42) {
  6063. // /*, find */
  6064. lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
  6065. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
  6066. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6067. if (cc2 == 125) {
  6068. lastMultiCommentEndBrace = chunkerCurrentIndex;
  6069. }
  6070. if (cc2 != 42) {
  6071. continue;
  6072. }
  6073. if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
  6074. break;
  6075. }
  6076. }
  6077. if (chunkerCurrentIndex == len - 1) {
  6078. return fail('missing closing `*/`', currentChunkStartIndex);
  6079. }
  6080. chunkerCurrentIndex++;
  6081. }
  6082. continue;
  6083. case 42: // *, check for unmatched */
  6084. if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) {
  6085. return fail('unmatched `/*`', chunkerCurrentIndex);
  6086. }
  6087. continue;
  6088. }
  6089. }
  6090. if (level !== 0) {
  6091. if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
  6092. return fail('missing closing `}` or `*/`', lastOpening);
  6093. }
  6094. else {
  6095. return fail('missing closing `}`', lastOpening);
  6096. }
  6097. }
  6098. else if (parenLevel !== 0) {
  6099. return fail('missing closing `)`', lastOpeningParen);
  6100. }
  6101. emitChunk(true);
  6102. return chunks;
  6103. }
  6104. var getParserInput = (function () {
  6105. var // Less input string
  6106. input;
  6107. var // current chunk
  6108. j;
  6109. var // holds state for backtracking
  6110. saveStack = [];
  6111. var // furthest index the parser has gone to
  6112. furthest;
  6113. var // if this is furthest we got to, this is the probably cause
  6114. furthestPossibleErrorMessage;
  6115. var // chunkified input
  6116. chunks;
  6117. var // current chunk
  6118. current;
  6119. var // index of current chunk, in `input`
  6120. currentPos;
  6121. var parserInput = {};
  6122. var CHARCODE_SPACE = 32;
  6123. var CHARCODE_TAB = 9;
  6124. var CHARCODE_LF = 10;
  6125. var CHARCODE_CR = 13;
  6126. var CHARCODE_PLUS = 43;
  6127. var CHARCODE_COMMA = 44;
  6128. var CHARCODE_FORWARD_SLASH = 47;
  6129. var CHARCODE_9 = 57;
  6130. function skipWhitespace(length) {
  6131. var oldi = parserInput.i;
  6132. var oldj = j;
  6133. var curr = parserInput.i - currentPos;
  6134. var endIndex = parserInput.i + current.length - curr;
  6135. var mem = (parserInput.i += length);
  6136. var inp = input;
  6137. var c;
  6138. var nextChar;
  6139. var comment;
  6140. for (; parserInput.i < endIndex; parserInput.i++) {
  6141. c = inp.charCodeAt(parserInput.i);
  6142. if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
  6143. nextChar = inp.charAt(parserInput.i + 1);
  6144. if (nextChar === '/') {
  6145. comment = { index: parserInput.i, isLineComment: true };
  6146. var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
  6147. if (nextNewLine < 0) {
  6148. nextNewLine = endIndex;
  6149. }
  6150. parserInput.i = nextNewLine;
  6151. comment.text = inp.substr(comment.index, parserInput.i - comment.index);
  6152. parserInput.commentStore.push(comment);
  6153. continue;
  6154. }
  6155. else if (nextChar === '*') {
  6156. var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
  6157. if (nextStarSlash >= 0) {
  6158. comment = {
  6159. index: parserInput.i,
  6160. text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
  6161. isLineComment: false
  6162. };
  6163. parserInput.i += comment.text.length - 1;
  6164. parserInput.commentStore.push(comment);
  6165. continue;
  6166. }
  6167. }
  6168. break;
  6169. }
  6170. if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
  6171. break;
  6172. }
  6173. }
  6174. current = current.slice(length + parserInput.i - mem + curr);
  6175. currentPos = parserInput.i;
  6176. if (!current.length) {
  6177. if (j < chunks.length - 1) {
  6178. current = chunks[++j];
  6179. skipWhitespace(0); // skip space at the beginning of a chunk
  6180. return true; // things changed
  6181. }
  6182. parserInput.finished = true;
  6183. }
  6184. return oldi !== parserInput.i || oldj !== j;
  6185. }
  6186. parserInput.save = function () {
  6187. currentPos = parserInput.i;
  6188. saveStack.push({ current: current, i: parserInput.i, j: j });
  6189. };
  6190. parserInput.restore = function (possibleErrorMessage) {
  6191. if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
  6192. furthest = parserInput.i;
  6193. furthestPossibleErrorMessage = possibleErrorMessage;
  6194. }
  6195. var state = saveStack.pop();
  6196. current = state.current;
  6197. currentPos = parserInput.i = state.i;
  6198. j = state.j;
  6199. };
  6200. parserInput.forget = function () {
  6201. saveStack.pop();
  6202. };
  6203. parserInput.isWhitespace = function (offset) {
  6204. var pos = parserInput.i + (offset || 0);
  6205. var code = input.charCodeAt(pos);
  6206. return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
  6207. };
  6208. // Specialization of $(tok)
  6209. parserInput.$re = function (tok) {
  6210. if (parserInput.i > currentPos) {
  6211. current = current.slice(parserInput.i - currentPos);
  6212. currentPos = parserInput.i;
  6213. }
  6214. var m = tok.exec(current);
  6215. if (!m) {
  6216. return null;
  6217. }
  6218. skipWhitespace(m[0].length);
  6219. if (typeof m === 'string') {
  6220. return m;
  6221. }
  6222. return m.length === 1 ? m[0] : m;
  6223. };
  6224. parserInput.$char = function (tok) {
  6225. if (input.charAt(parserInput.i) !== tok) {
  6226. return null;
  6227. }
  6228. skipWhitespace(1);
  6229. return tok;
  6230. };
  6231. parserInput.$str = function (tok) {
  6232. var tokLength = tok.length;
  6233. // https://jsperf.com/string-startswith/21
  6234. for (var i = 0; i < tokLength; i++) {
  6235. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  6236. return null;
  6237. }
  6238. }
  6239. skipWhitespace(tokLength);
  6240. return tok;
  6241. };
  6242. parserInput.$quoted = function (loc) {
  6243. var pos = loc || parserInput.i;
  6244. var startChar = input.charAt(pos);
  6245. if (startChar !== '\'' && startChar !== '"') {
  6246. return;
  6247. }
  6248. var length = input.length;
  6249. var currentPosition = pos;
  6250. for (var i = 1; i + currentPosition < length; i++) {
  6251. var nextChar = input.charAt(i + currentPosition);
  6252. switch (nextChar) {
  6253. case '\\':
  6254. i++;
  6255. continue;
  6256. case '\r':
  6257. case '\n':
  6258. break;
  6259. case startChar:
  6260. var str = input.substr(currentPosition, i + 1);
  6261. if (!loc && loc !== 0) {
  6262. skipWhitespace(i + 1);
  6263. return str;
  6264. }
  6265. return [startChar, str];
  6266. }
  6267. }
  6268. return null;
  6269. };
  6270. /**
  6271. * Permissive parsing. Ignores everything except matching {} [] () and quotes
  6272. * until matching token (outside of blocks)
  6273. */
  6274. parserInput.$parseUntil = function (tok) {
  6275. var quote = '';
  6276. var returnVal = null;
  6277. var inComment = false;
  6278. var blockDepth = 0;
  6279. var blockStack = [];
  6280. var parseGroups = [];
  6281. var length = input.length;
  6282. var startPos = parserInput.i;
  6283. var lastPos = parserInput.i;
  6284. var i = parserInput.i;
  6285. var loop = true;
  6286. var testChar;
  6287. if (typeof tok === 'string') {
  6288. testChar = function (char) { return char === tok; };
  6289. }
  6290. else {
  6291. testChar = function (char) { return tok.test(char); };
  6292. }
  6293. do {
  6294. var nextChar = input.charAt(i);
  6295. if (blockDepth === 0 && testChar(nextChar)) {
  6296. returnVal = input.substr(lastPos, i - lastPos);
  6297. if (returnVal) {
  6298. parseGroups.push(returnVal);
  6299. }
  6300. else {
  6301. parseGroups.push(' ');
  6302. }
  6303. returnVal = parseGroups;
  6304. skipWhitespace(i - startPos);
  6305. loop = false;
  6306. }
  6307. else {
  6308. if (inComment) {
  6309. if (nextChar === '*' &&
  6310. input.charAt(i + 1) === '/') {
  6311. i++;
  6312. blockDepth--;
  6313. inComment = false;
  6314. }
  6315. i++;
  6316. continue;
  6317. }
  6318. switch (nextChar) {
  6319. case '\\':
  6320. i++;
  6321. nextChar = input.charAt(i);
  6322. parseGroups.push(input.substr(lastPos, i - lastPos + 1));
  6323. lastPos = i + 1;
  6324. break;
  6325. case '/':
  6326. if (input.charAt(i + 1) === '*') {
  6327. i++;
  6328. inComment = true;
  6329. blockDepth++;
  6330. }
  6331. break;
  6332. case '\'':
  6333. case '"':
  6334. quote = parserInput.$quoted(i);
  6335. if (quote) {
  6336. parseGroups.push(input.substr(lastPos, i - lastPos), quote);
  6337. i += quote[1].length - 1;
  6338. lastPos = i + 1;
  6339. }
  6340. else {
  6341. skipWhitespace(i - startPos);
  6342. returnVal = nextChar;
  6343. loop = false;
  6344. }
  6345. break;
  6346. case '{':
  6347. blockStack.push('}');
  6348. blockDepth++;
  6349. break;
  6350. case '(':
  6351. blockStack.push(')');
  6352. blockDepth++;
  6353. break;
  6354. case '[':
  6355. blockStack.push(']');
  6356. blockDepth++;
  6357. break;
  6358. case '}':
  6359. case ')':
  6360. case ']':
  6361. var expected = blockStack.pop();
  6362. if (nextChar === expected) {
  6363. blockDepth--;
  6364. }
  6365. else {
  6366. // move the parser to the error and return expected
  6367. skipWhitespace(i - startPos);
  6368. returnVal = expected;
  6369. loop = false;
  6370. }
  6371. }
  6372. i++;
  6373. if (i > length) {
  6374. loop = false;
  6375. }
  6376. }
  6377. } while (loop);
  6378. return returnVal ? returnVal : null;
  6379. };
  6380. parserInput.autoCommentAbsorb = true;
  6381. parserInput.commentStore = [];
  6382. parserInput.finished = false;
  6383. // Same as $(), but don't change the state of the parser,
  6384. // just return the match.
  6385. parserInput.peek = function (tok) {
  6386. if (typeof tok === 'string') {
  6387. // https://jsperf.com/string-startswith/21
  6388. for (var i = 0; i < tok.length; i++) {
  6389. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  6390. return false;
  6391. }
  6392. }
  6393. return true;
  6394. }
  6395. else {
  6396. return tok.test(current);
  6397. }
  6398. };
  6399. // Specialization of peek()
  6400. // TODO remove or change some currentChar calls to peekChar
  6401. parserInput.peekChar = function (tok) { return input.charAt(parserInput.i) === tok; };
  6402. parserInput.currentChar = function () { return input.charAt(parserInput.i); };
  6403. parserInput.prevChar = function () { return input.charAt(parserInput.i - 1); };
  6404. parserInput.getInput = function () { return input; };
  6405. parserInput.peekNotNumeric = function () {
  6406. var c = input.charCodeAt(parserInput.i);
  6407. // Is the first char of the dimension 0-9, '.', '+' or '-'
  6408. return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
  6409. };
  6410. parserInput.start = function (str, chunkInput, failFunction) {
  6411. input = str;
  6412. parserInput.i = j = currentPos = furthest = 0;
  6413. // chunking apparently makes things quicker (but my tests indicate
  6414. // it might actually make things slower in node at least)
  6415. // and it is a non-perfect parse - it can't recognise
  6416. // unquoted urls, meaning it can't distinguish comments
  6417. // meaning comments with quotes or {}() in them get 'counted'
  6418. // and then lead to parse errors.
  6419. // In addition if the chunking chunks in the wrong place we might
  6420. // not be able to parse a parser statement in one go
  6421. // this is officially deprecated but can be switched on via an option
  6422. // in the case it causes too much performance issues.
  6423. if (chunkInput) {
  6424. chunks = chunker(str, failFunction);
  6425. }
  6426. else {
  6427. chunks = [str];
  6428. }
  6429. current = chunks[0];
  6430. skipWhitespace(0);
  6431. };
  6432. parserInput.end = function () {
  6433. var message;
  6434. var isFinished = parserInput.i >= input.length;
  6435. if (parserInput.i < furthest) {
  6436. message = furthestPossibleErrorMessage;
  6437. parserInput.i = furthest;
  6438. }
  6439. return {
  6440. isFinished: isFinished,
  6441. furthest: parserInput.i,
  6442. furthestPossibleErrorMessage: message,
  6443. furthestReachedEnd: parserInput.i >= input.length - 1,
  6444. furthestChar: input[parserInput.i]
  6445. };
  6446. };
  6447. return parserInput;
  6448. });
  6449. //
  6450. // less.js - parser
  6451. //
  6452. // A relatively straight-forward predictive parser.
  6453. // There is no tokenization/lexing stage, the input is parsed
  6454. // in one sweep.
  6455. //
  6456. // To make the parser fast enough to run in the browser, several
  6457. // optimization had to be made:
  6458. //
  6459. // - Matching and slicing on a huge input is often cause of slowdowns.
  6460. // The solution is to chunkify the input into smaller strings.
  6461. // The chunks are stored in the `chunks` var,
  6462. // `j` holds the current chunk index, and `currentPos` holds
  6463. // the index of the current chunk in relation to `input`.
  6464. // This gives us an almost 4x speed-up.
  6465. //
  6466. // - In many cases, we don't need to match individual tokens;
  6467. // for example, if a value doesn't hold any variables, operations
  6468. // or dynamic references, the parser can effectively 'skip' it,
  6469. // treating it as a literal.
  6470. // An example would be '1px solid #000' - which evaluates to itself,
  6471. // we don't need to know what the individual components are.
  6472. // The drawback, of course is that you don't get the benefits of
  6473. // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
  6474. // and a smaller speed-up in the code-gen.
  6475. //
  6476. //
  6477. // Token matching is done with the `$` function, which either takes
  6478. // a terminal string or regexp, or a non-terminal function to call.
  6479. // It also takes care of moving all the indices forwards.
  6480. //
  6481. var Parser = function Parser(context, imports, fileInfo) {
  6482. var parsers;
  6483. var parserInput = getParserInput();
  6484. function error(msg, type) {
  6485. throw new LessError({
  6486. index: parserInput.i,
  6487. filename: fileInfo.filename,
  6488. type: type || 'Syntax',
  6489. message: msg
  6490. }, imports);
  6491. }
  6492. function expect(arg, msg) {
  6493. // some older browsers return typeof 'function' for RegExp
  6494. var result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
  6495. if (result) {
  6496. return result;
  6497. }
  6498. error(msg || (typeof arg === 'string'
  6499. ? "expected '" + arg + "' got '" + parserInput.currentChar() + "'"
  6500. : 'unexpected token'));
  6501. }
  6502. // Specialization of expect()
  6503. function expectChar(arg, msg) {
  6504. if (parserInput.$char(arg)) {
  6505. return arg;
  6506. }
  6507. error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'");
  6508. }
  6509. function getDebugInfo(index) {
  6510. var filename = fileInfo.filename;
  6511. return {
  6512. lineNumber: getLocation(index, parserInput.getInput()).line + 1,
  6513. fileName: filename
  6514. };
  6515. }
  6516. /**
  6517. * Used after initial parsing to create nodes on the fly
  6518. *
  6519. * @param {String} str - string to parse
  6520. * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
  6521. * @param {Number} currentIndex - start number to begin indexing
  6522. * @param {Object} fileInfo - fileInfo to attach to created nodes
  6523. */
  6524. function parseNode(str, parseList, currentIndex, fileInfo, callback) {
  6525. var result;
  6526. var returnNodes = [];
  6527. var parser = parserInput;
  6528. try {
  6529. parser.start(str, false, function fail(msg, index) {
  6530. callback({
  6531. message: msg,
  6532. index: index + currentIndex
  6533. });
  6534. });
  6535. for (var x = 0, p = void 0, i = void 0; (p = parseList[x]); x++) {
  6536. i = parser.i;
  6537. result = parsers[p]();
  6538. if (result) {
  6539. try {
  6540. result._index = i + currentIndex;
  6541. result._fileInfo = fileInfo;
  6542. }
  6543. catch (e) { }
  6544. returnNodes.push(result);
  6545. }
  6546. else {
  6547. returnNodes.push(null);
  6548. }
  6549. }
  6550. var endInfo = parser.end();
  6551. if (endInfo.isFinished) {
  6552. callback(null, returnNodes);
  6553. }
  6554. else {
  6555. callback(true, null);
  6556. }
  6557. }
  6558. catch (e) {
  6559. throw new LessError({
  6560. index: e.index + currentIndex,
  6561. message: e.message
  6562. }, imports, fileInfo.filename);
  6563. }
  6564. }
  6565. //
  6566. // The Parser
  6567. //
  6568. return {
  6569. parserInput: parserInput,
  6570. imports: imports,
  6571. fileInfo: fileInfo,
  6572. parseNode: parseNode,
  6573. //
  6574. // Parse an input string into an abstract syntax tree,
  6575. // @param str A string containing 'less' markup
  6576. // @param callback call `callback` when done.
  6577. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
  6578. //
  6579. parse: function (str, callback, additionalData) {
  6580. var root;
  6581. var err = null;
  6582. var globalVars;
  6583. var modifyVars;
  6584. var ignored;
  6585. var preText = '';
  6586. // Optionally disable @plugin parsing
  6587. if (additionalData && additionalData.disablePluginRule) {
  6588. parsers.plugin = function () {
  6589. var dir = parserInput.$re(/^@plugin?\s+/);
  6590. if (dir) {
  6591. error('@plugin statements are not allowed when disablePluginRule is set to true');
  6592. }
  6593. };
  6594. }
  6595. globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + "\n" : '';
  6596. modifyVars = (additionalData && additionalData.modifyVars) ? "\n" + Parser.serializeVars(additionalData.modifyVars) : '';
  6597. if (context.pluginManager) {
  6598. var preProcessors = context.pluginManager.getPreProcessors();
  6599. for (var i = 0; i < preProcessors.length; i++) {
  6600. str = preProcessors[i].process(str, { context: context, imports: imports, fileInfo: fileInfo });
  6601. }
  6602. }
  6603. if (globalVars || (additionalData && additionalData.banner)) {
  6604. preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars;
  6605. ignored = imports.contentsIgnoredChars;
  6606. ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
  6607. ignored[fileInfo.filename] += preText.length;
  6608. }
  6609. str = str.replace(/\r\n?/g, '\n');
  6610. // Remove potential UTF Byte Order Mark
  6611. str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
  6612. imports.contents[fileInfo.filename] = str;
  6613. // Start with the primary rule.
  6614. // The whole syntax tree is held under a Ruleset node,
  6615. // with the `root` property set to true, so no `{}` are
  6616. // output. The callback is called when the input is parsed.
  6617. try {
  6618. parserInput.start(str, context.chunkInput, function fail(msg, index) {
  6619. throw new LessError({
  6620. index: index,
  6621. type: 'Parse',
  6622. message: msg,
  6623. filename: fileInfo.filename
  6624. }, imports);
  6625. });
  6626. tree.Node.prototype.parse = this;
  6627. root = new tree.Ruleset(null, this.parsers.primary());
  6628. tree.Node.prototype.rootNode = root;
  6629. root.root = true;
  6630. root.firstRoot = true;
  6631. root.functionRegistry = functionRegistry.inherit();
  6632. }
  6633. catch (e) {
  6634. return callback(new LessError(e, imports, fileInfo.filename));
  6635. }
  6636. // If `i` is smaller than the `input.length - 1`,
  6637. // it means the parser wasn't able to parse the whole
  6638. // string, so we've got a parsing error.
  6639. //
  6640. // We try to extract a \n delimited string,
  6641. // showing the line where the parse error occurred.
  6642. // We split it up into two parts (the part which parsed,
  6643. // and the part which didn't), so we can color them differently.
  6644. var endInfo = parserInput.end();
  6645. if (!endInfo.isFinished) {
  6646. var message = endInfo.furthestPossibleErrorMessage;
  6647. if (!message) {
  6648. message = 'Unrecognised input';
  6649. if (endInfo.furthestChar === '}') {
  6650. message += '. Possibly missing opening \'{\'';
  6651. }
  6652. else if (endInfo.furthestChar === ')') {
  6653. message += '. Possibly missing opening \'(\'';
  6654. }
  6655. else if (endInfo.furthestReachedEnd) {
  6656. message += '. Possibly missing something';
  6657. }
  6658. }
  6659. err = new LessError({
  6660. type: 'Parse',
  6661. message: message,
  6662. index: endInfo.furthest,
  6663. filename: fileInfo.filename
  6664. }, imports);
  6665. }
  6666. var finish = function (e) {
  6667. e = err || e || imports.error;
  6668. if (e) {
  6669. if (!(e instanceof LessError)) {
  6670. e = new LessError(e, imports, fileInfo.filename);
  6671. }
  6672. return callback(e);
  6673. }
  6674. else {
  6675. return callback(null, root);
  6676. }
  6677. };
  6678. if (context.processImports !== false) {
  6679. new visitors.ImportVisitor(imports, finish)
  6680. .run(root);
  6681. }
  6682. else {
  6683. return finish();
  6684. }
  6685. },
  6686. //
  6687. // Here in, the parsing rules/functions
  6688. //
  6689. // The basic structure of the syntax tree generated is as follows:
  6690. //
  6691. // Ruleset -> Declaration -> Value -> Expression -> Entity
  6692. //
  6693. // Here's some Less code:
  6694. //
  6695. // .class {
  6696. // color: #fff;
  6697. // border: 1px solid #000;
  6698. // width: @w + 4px;
  6699. // > .child {...}
  6700. // }
  6701. //
  6702. // And here's what the parse tree might look like:
  6703. //
  6704. // Ruleset (Selector '.class', [
  6705. // Declaration ("color", Value ([Expression [Color #fff]]))
  6706. // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
  6707. // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
  6708. // Ruleset (Selector [Element '>', '.child'], [...])
  6709. // ])
  6710. //
  6711. // In general, most rules will try to parse a token with the `$re()` function, and if the return
  6712. // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
  6713. // first, before parsing, that's when we use `peek()`.
  6714. //
  6715. parsers: parsers = {
  6716. //
  6717. // The `primary` rule is the *entry* and *exit* point of the parser.
  6718. // The rules here can appear at any level of the parse tree.
  6719. //
  6720. // The recursive nature of the grammar is an interplay between the `block`
  6721. // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
  6722. // as represented by this simplified grammar:
  6723. //
  6724. // primary → (ruleset | declaration)+
  6725. // ruleset → selector+ block
  6726. // block → '{' primary '}'
  6727. //
  6728. // Only at one point is the primary rule not called from the
  6729. // block rule: at the root level.
  6730. //
  6731. primary: function () {
  6732. var mixin = this.mixin;
  6733. var root = [];
  6734. var node;
  6735. while (true) {
  6736. while (true) {
  6737. node = this.comment();
  6738. if (!node) {
  6739. break;
  6740. }
  6741. root.push(node);
  6742. }
  6743. // always process comments before deciding if finished
  6744. if (parserInput.finished) {
  6745. break;
  6746. }
  6747. if (parserInput.peek('}')) {
  6748. break;
  6749. }
  6750. node = this.extendRule();
  6751. if (node) {
  6752. root = root.concat(node);
  6753. continue;
  6754. }
  6755. node = mixin.definition() || this.declaration() || mixin.call(false, false) ||
  6756. this.ruleset() || this.variableCall() || this.entities.call() || this.atrule();
  6757. if (node) {
  6758. root.push(node);
  6759. }
  6760. else {
  6761. var foundSemiColon = false;
  6762. while (parserInput.$char(';')) {
  6763. foundSemiColon = true;
  6764. }
  6765. if (!foundSemiColon) {
  6766. break;
  6767. }
  6768. }
  6769. }
  6770. return root;
  6771. },
  6772. // comments are collected by the main parsing mechanism and then assigned to nodes
  6773. // where the current structure allows it
  6774. comment: function () {
  6775. if (parserInput.commentStore.length) {
  6776. var comment = parserInput.commentStore.shift();
  6777. return new (tree.Comment)(comment.text, comment.isLineComment, comment.index, fileInfo);
  6778. }
  6779. },
  6780. //
  6781. // Entities are tokens which can be found inside an Expression
  6782. //
  6783. entities: {
  6784. mixinLookup: function () {
  6785. return parsers.mixin.call(true, true);
  6786. },
  6787. //
  6788. // A string, which supports escaping " and '
  6789. //
  6790. // "milky way" 'he\'s the one!'
  6791. //
  6792. quoted: function (forceEscaped) {
  6793. var str;
  6794. var index = parserInput.i;
  6795. var isEscaped = false;
  6796. parserInput.save();
  6797. if (parserInput.$char('~')) {
  6798. isEscaped = true;
  6799. }
  6800. else if (forceEscaped) {
  6801. parserInput.restore();
  6802. return;
  6803. }
  6804. str = parserInput.$quoted();
  6805. if (!str) {
  6806. parserInput.restore();
  6807. return;
  6808. }
  6809. parserInput.forget();
  6810. return new (tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
  6811. },
  6812. //
  6813. // A catch-all word, such as:
  6814. //
  6815. // black border-collapse
  6816. //
  6817. keyword: function () {
  6818. var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
  6819. if (k) {
  6820. return tree.Color.fromKeyword(k) || new (tree.Keyword)(k);
  6821. }
  6822. },
  6823. //
  6824. // A function call
  6825. //
  6826. // rgb(255, 0, 255)
  6827. //
  6828. // The arguments are parsed with the `entities.arguments` parser.
  6829. //
  6830. call: function () {
  6831. var name;
  6832. var args;
  6833. var func;
  6834. var index = parserInput.i;
  6835. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  6836. if (parserInput.peek(/^url\(/i)) {
  6837. return;
  6838. }
  6839. parserInput.save();
  6840. name = parserInput.$re(/^([\w-]+|%|~|progid:[\w\.]+)\(/);
  6841. if (!name) {
  6842. parserInput.forget();
  6843. return;
  6844. }
  6845. name = name[1];
  6846. func = this.customFuncCall(name);
  6847. if (func) {
  6848. args = func.parse();
  6849. if (args && func.stop) {
  6850. parserInput.forget();
  6851. return args;
  6852. }
  6853. }
  6854. args = this.arguments(args);
  6855. if (!parserInput.$char(')')) {
  6856. parserInput.restore('Could not parse call arguments or missing \')\'');
  6857. return;
  6858. }
  6859. parserInput.forget();
  6860. return new (tree.Call)(name, args, index, fileInfo);
  6861. },
  6862. //
  6863. // Parsing rules for functions with non-standard args, e.g.:
  6864. //
  6865. // boolean(not(2 > 1))
  6866. //
  6867. // This is a quick prototype, to be modified/improved when
  6868. // more custom-parsed funcs come (e.g. `selector(...)`)
  6869. //
  6870. customFuncCall: function (name) {
  6871. /* Ideally the table is to be moved out of here for faster perf.,
  6872. but it's quite tricky since it relies on all these `parsers`
  6873. and `expect` available only here */
  6874. return {
  6875. alpha: f(parsers.ieAlpha, true),
  6876. boolean: f(condition),
  6877. 'if': f(condition)
  6878. }[name.toLowerCase()];
  6879. function f(parse, stop) {
  6880. return {
  6881. parse: parse,
  6882. stop: stop // when true - stop after parse() and return its result,
  6883. // otherwise continue for plain args
  6884. };
  6885. }
  6886. function condition() {
  6887. return [expect(parsers.condition, 'expected condition')];
  6888. }
  6889. },
  6890. arguments: function (prevArgs) {
  6891. var argsComma = prevArgs || [];
  6892. var argsSemiColon = [];
  6893. var isSemiColonSeparated;
  6894. var value;
  6895. parserInput.save();
  6896. while (true) {
  6897. if (prevArgs) {
  6898. prevArgs = false;
  6899. }
  6900. else {
  6901. value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
  6902. if (!value) {
  6903. break;
  6904. }
  6905. if (value.value && value.value.length == 1) {
  6906. value = value.value[0];
  6907. }
  6908. argsComma.push(value);
  6909. }
  6910. if (parserInput.$char(',')) {
  6911. continue;
  6912. }
  6913. if (parserInput.$char(';') || isSemiColonSeparated) {
  6914. isSemiColonSeparated = true;
  6915. value = (argsComma.length < 1) ? argsComma[0]
  6916. : new tree.Value(argsComma);
  6917. argsSemiColon.push(value);
  6918. argsComma = [];
  6919. }
  6920. }
  6921. parserInput.forget();
  6922. return isSemiColonSeparated ? argsSemiColon : argsComma;
  6923. },
  6924. literal: function () {
  6925. return this.dimension() ||
  6926. this.color() ||
  6927. this.quoted() ||
  6928. this.unicodeDescriptor();
  6929. },
  6930. // Assignments are argument entities for calls.
  6931. // They are present in ie filter properties as shown below.
  6932. //
  6933. // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
  6934. //
  6935. assignment: function () {
  6936. var key;
  6937. var value;
  6938. parserInput.save();
  6939. key = parserInput.$re(/^\w+(?=\s?=)/i);
  6940. if (!key) {
  6941. parserInput.restore();
  6942. return;
  6943. }
  6944. if (!parserInput.$char('=')) {
  6945. parserInput.restore();
  6946. return;
  6947. }
  6948. value = parsers.entity();
  6949. if (value) {
  6950. parserInput.forget();
  6951. return new (tree.Assignment)(key, value);
  6952. }
  6953. else {
  6954. parserInput.restore();
  6955. }
  6956. },
  6957. //
  6958. // Parse url() tokens
  6959. //
  6960. // We use a specific rule for urls, because they don't really behave like
  6961. // standard function calls. The difference is that the argument doesn't have
  6962. // to be enclosed within a string, so it can't be parsed as an Expression.
  6963. //
  6964. url: function () {
  6965. var value;
  6966. var index = parserInput.i;
  6967. parserInput.autoCommentAbsorb = false;
  6968. if (!parserInput.$str('url(')) {
  6969. parserInput.autoCommentAbsorb = true;
  6970. return;
  6971. }
  6972. value = this.quoted() || this.variable() || this.property() ||
  6973. parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
  6974. parserInput.autoCommentAbsorb = true;
  6975. expectChar(')');
  6976. return new (tree.URL)((value.value != null ||
  6977. value instanceof tree.Variable ||
  6978. value instanceof tree.Property) ?
  6979. value : new (tree.Anonymous)(value, index), index, fileInfo);
  6980. },
  6981. //
  6982. // A Variable entity, such as `@fink`, in
  6983. //
  6984. // width: @fink + 2px
  6985. //
  6986. // We use a different parser for variable definitions,
  6987. // see `parsers.variable`.
  6988. //
  6989. variable: function () {
  6990. var ch;
  6991. var name;
  6992. var index = parserInput.i;
  6993. parserInput.save();
  6994. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
  6995. ch = parserInput.currentChar();
  6996. if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
  6997. // this may be a VariableCall lookup
  6998. var result = parsers.variableCall(name);
  6999. if (result) {
  7000. parserInput.forget();
  7001. return result;
  7002. }
  7003. }
  7004. parserInput.forget();
  7005. return new (tree.Variable)(name, index, fileInfo);
  7006. }
  7007. parserInput.restore();
  7008. },
  7009. // A variable entity using the protective {} e.g. @{var}
  7010. variableCurly: function () {
  7011. var curly;
  7012. var index = parserInput.i;
  7013. if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
  7014. return new (tree.Variable)("@" + curly[1], index, fileInfo);
  7015. }
  7016. },
  7017. //
  7018. // A Property accessor, such as `$color`, in
  7019. //
  7020. // background-color: $color
  7021. //
  7022. property: function () {
  7023. var name;
  7024. var index = parserInput.i;
  7025. if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
  7026. return new (tree.Property)(name, index, fileInfo);
  7027. }
  7028. },
  7029. // A property entity useing the protective {} e.g. ${prop}
  7030. propertyCurly: function () {
  7031. var curly;
  7032. var index = parserInput.i;
  7033. if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
  7034. return new (tree.Property)("$" + curly[1], index, fileInfo);
  7035. }
  7036. },
  7037. //
  7038. // A Hexadecimal color
  7039. //
  7040. // #4F3C2F
  7041. //
  7042. // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
  7043. //
  7044. color: function () {
  7045. var rgb;
  7046. parserInput.save();
  7047. if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/))) {
  7048. if (!rgb[2]) {
  7049. parserInput.forget();
  7050. return new (tree.Color)(rgb[1], undefined, rgb[0]);
  7051. }
  7052. }
  7053. parserInput.restore();
  7054. },
  7055. colorKeyword: function () {
  7056. parserInput.save();
  7057. var autoCommentAbsorb = parserInput.autoCommentAbsorb;
  7058. parserInput.autoCommentAbsorb = false;
  7059. var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
  7060. parserInput.autoCommentAbsorb = autoCommentAbsorb;
  7061. if (!k) {
  7062. parserInput.forget();
  7063. return;
  7064. }
  7065. parserInput.restore();
  7066. var color = tree.Color.fromKeyword(k);
  7067. if (color) {
  7068. parserInput.$str(k);
  7069. return color;
  7070. }
  7071. },
  7072. //
  7073. // A Dimension, that is, a number and a unit
  7074. //
  7075. // 0.5em 95%
  7076. //
  7077. dimension: function () {
  7078. if (parserInput.peekNotNumeric()) {
  7079. return;
  7080. }
  7081. var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
  7082. if (value) {
  7083. return new (tree.Dimension)(value[1], value[2]);
  7084. }
  7085. },
  7086. //
  7087. // A unicode descriptor, as is used in unicode-range
  7088. //
  7089. // U+0?? or U+00A1-00A9
  7090. //
  7091. unicodeDescriptor: function () {
  7092. var ud;
  7093. ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
  7094. if (ud) {
  7095. return new (tree.UnicodeDescriptor)(ud[0]);
  7096. }
  7097. },
  7098. //
  7099. // JavaScript code to be evaluated
  7100. //
  7101. // `window.location.href`
  7102. //
  7103. javascript: function () {
  7104. var js;
  7105. var index = parserInput.i;
  7106. parserInput.save();
  7107. var escape = parserInput.$char('~');
  7108. var jsQuote = parserInput.$char('`');
  7109. if (!jsQuote) {
  7110. parserInput.restore();
  7111. return;
  7112. }
  7113. js = parserInput.$re(/^[^`]*`/);
  7114. if (js) {
  7115. parserInput.forget();
  7116. return new (tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
  7117. }
  7118. parserInput.restore('invalid javascript definition');
  7119. }
  7120. },
  7121. //
  7122. // The variable part of a variable definition. Used in the `rule` parser
  7123. //
  7124. // @fink:
  7125. //
  7126. variable: function () {
  7127. var name;
  7128. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
  7129. return name[1];
  7130. }
  7131. },
  7132. //
  7133. // Call a variable value to retrieve a detached ruleset
  7134. // or a value from a detached ruleset's rules.
  7135. //
  7136. // @fink();
  7137. // @fink;
  7138. // color: @fink[@color];
  7139. //
  7140. variableCall: function (parsedName) {
  7141. var lookups;
  7142. var i = parserInput.i;
  7143. var inValue = !!parsedName;
  7144. var name = parsedName;
  7145. parserInput.save();
  7146. if (name || (parserInput.currentChar() === '@'
  7147. && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) {
  7148. lookups = this.mixin.ruleLookups();
  7149. if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) {
  7150. parserInput.restore('Missing \'[...]\' lookup in variable call');
  7151. return;
  7152. }
  7153. if (!inValue) {
  7154. name = name[1];
  7155. }
  7156. var call = new tree.VariableCall(name, i, fileInfo);
  7157. if (!inValue && parsers.end()) {
  7158. parserInput.forget();
  7159. return call;
  7160. }
  7161. else {
  7162. parserInput.forget();
  7163. return new tree.NamespaceValue(call, lookups, i, fileInfo);
  7164. }
  7165. }
  7166. parserInput.restore();
  7167. },
  7168. //
  7169. // extend syntax - used to extend selectors
  7170. //
  7171. extend: function (isRule) {
  7172. var elements;
  7173. var e;
  7174. var index = parserInput.i;
  7175. var option;
  7176. var extendList;
  7177. var extend;
  7178. if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
  7179. return;
  7180. }
  7181. do {
  7182. option = null;
  7183. elements = null;
  7184. while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
  7185. e = this.element();
  7186. if (!e) {
  7187. break;
  7188. }
  7189. if (elements) {
  7190. elements.push(e);
  7191. }
  7192. else {
  7193. elements = [e];
  7194. }
  7195. }
  7196. option = option && option[1];
  7197. if (!elements) {
  7198. error('Missing target selector for :extend().');
  7199. }
  7200. extend = new (tree.Extend)(new (tree.Selector)(elements), option, index, fileInfo);
  7201. if (extendList) {
  7202. extendList.push(extend);
  7203. }
  7204. else {
  7205. extendList = [extend];
  7206. }
  7207. } while (parserInput.$char(','));
  7208. expect(/^\)/);
  7209. if (isRule) {
  7210. expect(/^;/);
  7211. }
  7212. return extendList;
  7213. },
  7214. //
  7215. // extendRule - used in a rule to extend all the parent selectors
  7216. //
  7217. extendRule: function () {
  7218. return this.extend(true);
  7219. },
  7220. //
  7221. // Mixins
  7222. //
  7223. mixin: {
  7224. //
  7225. // A Mixin call, with an optional argument list
  7226. //
  7227. // #mixins > .square(#fff);
  7228. // #mixins.square(#fff);
  7229. // .rounded(4px, black);
  7230. // .button;
  7231. //
  7232. // We can lookup / return a value using the lookup syntax:
  7233. //
  7234. // color: #mixin.square(#fff)[@color];
  7235. //
  7236. // The `while` loop is there because mixins can be
  7237. // namespaced, but we only support the child and descendant
  7238. // selector for now.
  7239. //
  7240. call: function (inValue, getLookup) {
  7241. var s = parserInput.currentChar();
  7242. var important = false;
  7243. var lookups;
  7244. var index = parserInput.i;
  7245. var elements;
  7246. var args;
  7247. var hasParens;
  7248. if (s !== '.' && s !== '#') {
  7249. return;
  7250. }
  7251. parserInput.save(); // stop us absorbing part of an invalid selector
  7252. elements = this.elements();
  7253. if (elements) {
  7254. if (parserInput.$char('(')) {
  7255. args = this.args(true).args;
  7256. expectChar(')');
  7257. hasParens = true;
  7258. }
  7259. if (getLookup !== false) {
  7260. lookups = this.ruleLookups();
  7261. }
  7262. if (getLookup === true && !lookups) {
  7263. parserInput.restore();
  7264. return;
  7265. }
  7266. if (inValue && !lookups && !hasParens) {
  7267. // This isn't a valid in-value mixin call
  7268. parserInput.restore();
  7269. return;
  7270. }
  7271. if (!inValue && parsers.important()) {
  7272. important = true;
  7273. }
  7274. if (inValue || parsers.end()) {
  7275. parserInput.forget();
  7276. var mixin = new (tree.mixin.Call)(elements, args, index, fileInfo, !lookups && important);
  7277. if (lookups) {
  7278. return new tree.NamespaceValue(mixin, lookups);
  7279. }
  7280. else {
  7281. return mixin;
  7282. }
  7283. }
  7284. }
  7285. parserInput.restore();
  7286. },
  7287. /**
  7288. * Matching elements for mixins
  7289. * (Start with . or # and can have > )
  7290. */
  7291. elements: function () {
  7292. var elements;
  7293. var e;
  7294. var c;
  7295. var elem;
  7296. var elemIndex;
  7297. var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
  7298. while (true) {
  7299. elemIndex = parserInput.i;
  7300. e = parserInput.$re(re);
  7301. if (!e) {
  7302. break;
  7303. }
  7304. elem = new (tree.Element)(c, e, false, elemIndex, fileInfo);
  7305. if (elements) {
  7306. elements.push(elem);
  7307. }
  7308. else {
  7309. elements = [elem];
  7310. }
  7311. c = parserInput.$char('>');
  7312. }
  7313. return elements;
  7314. },
  7315. args: function (isCall) {
  7316. var entities = parsers.entities;
  7317. var returner = { args: null, variadic: false };
  7318. var expressions = [];
  7319. var argsSemiColon = [];
  7320. var argsComma = [];
  7321. var isSemiColonSeparated;
  7322. var expressionContainsNamed;
  7323. var name;
  7324. var nameLoop;
  7325. var value;
  7326. var arg;
  7327. var expand;
  7328. var hasSep = true;
  7329. parserInput.save();
  7330. while (true) {
  7331. if (isCall) {
  7332. arg = parsers.detachedRuleset() || parsers.expression();
  7333. }
  7334. else {
  7335. parserInput.commentStore.length = 0;
  7336. if (parserInput.$str('...')) {
  7337. returner.variadic = true;
  7338. if (parserInput.$char(';') && !isSemiColonSeparated) {
  7339. isSemiColonSeparated = true;
  7340. }
  7341. (isSemiColonSeparated ? argsSemiColon : argsComma)
  7342. .push({ variadic: true });
  7343. break;
  7344. }
  7345. arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
  7346. }
  7347. if (!arg || !hasSep) {
  7348. break;
  7349. }
  7350. nameLoop = null;
  7351. if (arg.throwAwayComments) {
  7352. arg.throwAwayComments();
  7353. }
  7354. value = arg;
  7355. var val = null;
  7356. if (isCall) {
  7357. // Variable
  7358. if (arg.value && arg.value.length == 1) {
  7359. val = arg.value[0];
  7360. }
  7361. }
  7362. else {
  7363. val = arg;
  7364. }
  7365. if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
  7366. if (parserInput.$char(':')) {
  7367. if (expressions.length > 0) {
  7368. if (isSemiColonSeparated) {
  7369. error('Cannot mix ; and , as delimiter types');
  7370. }
  7371. expressionContainsNamed = true;
  7372. }
  7373. value = parsers.detachedRuleset() || parsers.expression();
  7374. if (!value) {
  7375. if (isCall) {
  7376. error('could not understand value for named argument');
  7377. }
  7378. else {
  7379. parserInput.restore();
  7380. returner.args = [];
  7381. return returner;
  7382. }
  7383. }
  7384. nameLoop = (name = val.name);
  7385. }
  7386. else if (parserInput.$str('...')) {
  7387. if (!isCall) {
  7388. returner.variadic = true;
  7389. if (parserInput.$char(';') && !isSemiColonSeparated) {
  7390. isSemiColonSeparated = true;
  7391. }
  7392. (isSemiColonSeparated ? argsSemiColon : argsComma)
  7393. .push({ name: arg.name, variadic: true });
  7394. break;
  7395. }
  7396. else {
  7397. expand = true;
  7398. }
  7399. }
  7400. else if (!isCall) {
  7401. name = nameLoop = val.name;
  7402. value = null;
  7403. }
  7404. }
  7405. if (value) {
  7406. expressions.push(value);
  7407. }
  7408. argsComma.push({ name: nameLoop, value: value, expand: expand });
  7409. if (parserInput.$char(',')) {
  7410. hasSep = true;
  7411. continue;
  7412. }
  7413. hasSep = parserInput.$char(';') === ';';
  7414. if (hasSep || isSemiColonSeparated) {
  7415. if (expressionContainsNamed) {
  7416. error('Cannot mix ; and , as delimiter types');
  7417. }
  7418. isSemiColonSeparated = true;
  7419. if (expressions.length > 1) {
  7420. value = new (tree.Value)(expressions);
  7421. }
  7422. argsSemiColon.push({ name: name, value: value, expand: expand });
  7423. name = null;
  7424. expressions = [];
  7425. expressionContainsNamed = false;
  7426. }
  7427. }
  7428. parserInput.forget();
  7429. returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
  7430. return returner;
  7431. },
  7432. //
  7433. // A Mixin definition, with a list of parameters
  7434. //
  7435. // .rounded (@radius: 2px, @color) {
  7436. // ...
  7437. // }
  7438. //
  7439. // Until we have a finer grained state-machine, we have to
  7440. // do a look-ahead, to make sure we don't have a mixin call.
  7441. // See the `rule` function for more information.
  7442. //
  7443. // We start by matching `.rounded (`, and then proceed on to
  7444. // the argument list, which has optional default values.
  7445. // We store the parameters in `params`, with a `value` key,
  7446. // if there is a value, such as in the case of `@radius`.
  7447. //
  7448. // Once we've got our params list, and a closing `)`, we parse
  7449. // the `{...}` block.
  7450. //
  7451. definition: function () {
  7452. var name;
  7453. var params = [];
  7454. var match;
  7455. var ruleset;
  7456. var cond;
  7457. var variadic = false;
  7458. if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') ||
  7459. parserInput.peek(/^[^{]*\}/)) {
  7460. return;
  7461. }
  7462. parserInput.save();
  7463. match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
  7464. if (match) {
  7465. name = match[1];
  7466. var argInfo = this.args(false);
  7467. params = argInfo.args;
  7468. variadic = argInfo.variadic;
  7469. // .mixincall("@{a}");
  7470. // looks a bit like a mixin definition..
  7471. // also
  7472. // .mixincall(@a: {rule: set;});
  7473. // so we have to be nice and restore
  7474. if (!parserInput.$char(')')) {
  7475. parserInput.restore('Missing closing \')\'');
  7476. return;
  7477. }
  7478. parserInput.commentStore.length = 0;
  7479. if (parserInput.$str('when')) { // Guard
  7480. cond = expect(parsers.conditions, 'expected condition');
  7481. }
  7482. ruleset = parsers.block();
  7483. if (ruleset) {
  7484. parserInput.forget();
  7485. return new (tree.mixin.Definition)(name, params, ruleset, cond, variadic);
  7486. }
  7487. else {
  7488. parserInput.restore();
  7489. }
  7490. }
  7491. else {
  7492. parserInput.restore();
  7493. }
  7494. },
  7495. ruleLookups: function () {
  7496. var rule;
  7497. var lookups = [];
  7498. if (parserInput.currentChar() !== '[') {
  7499. return;
  7500. }
  7501. while (true) {
  7502. parserInput.save();
  7503. rule = this.lookupValue();
  7504. if (!rule && rule !== '') {
  7505. parserInput.restore();
  7506. break;
  7507. }
  7508. lookups.push(rule);
  7509. parserInput.forget();
  7510. }
  7511. if (lookups.length > 0) {
  7512. return lookups;
  7513. }
  7514. },
  7515. lookupValue: function () {
  7516. parserInput.save();
  7517. if (!parserInput.$char('[')) {
  7518. parserInput.restore();
  7519. return;
  7520. }
  7521. var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
  7522. if (!parserInput.$char(']')) {
  7523. parserInput.restore();
  7524. return;
  7525. }
  7526. if (name || name === '') {
  7527. parserInput.forget();
  7528. return name;
  7529. }
  7530. parserInput.restore();
  7531. }
  7532. },
  7533. //
  7534. // Entities are the smallest recognized token,
  7535. // and can be found inside a rule's value.
  7536. //
  7537. entity: function () {
  7538. var entities = this.entities;
  7539. return this.comment() || entities.literal() || entities.variable() || entities.url() ||
  7540. entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) ||
  7541. entities.javascript();
  7542. },
  7543. //
  7544. // A Declaration terminator. Note that we use `peek()` to check for '}',
  7545. // because the `block` rule will be expecting it, but we still need to make sure
  7546. // it's there, if ';' was omitted.
  7547. //
  7548. end: function () {
  7549. return parserInput.$char(';') || parserInput.peek('}');
  7550. },
  7551. //
  7552. // IE's alpha function
  7553. //
  7554. // alpha(opacity=88)
  7555. //
  7556. ieAlpha: function () {
  7557. var value;
  7558. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  7559. if (!parserInput.$re(/^opacity=/i)) {
  7560. return;
  7561. }
  7562. value = parserInput.$re(/^\d+/);
  7563. if (!value) {
  7564. value = expect(parsers.entities.variable, 'Could not parse alpha');
  7565. value = "@{" + value.name.slice(1) + "}";
  7566. }
  7567. expectChar(')');
  7568. return new tree.Quoted('', "alpha(opacity=" + value + ")");
  7569. },
  7570. //
  7571. // A Selector Element
  7572. //
  7573. // div
  7574. // + h1
  7575. // #socks
  7576. // input[type="text"]
  7577. //
  7578. // Elements are the building blocks for Selectors,
  7579. // they are made out of a `Combinator` (see combinator rule),
  7580. // and an element name, such as a tag a class, or `*`.
  7581. //
  7582. element: function () {
  7583. var e;
  7584. var c;
  7585. var v;
  7586. var index = parserInput.i;
  7587. c = this.combinator();
  7588. e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) ||
  7589. parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
  7590. parserInput.$char('*') || parserInput.$char('&') || this.attribute() ||
  7591. parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) ||
  7592. this.entities.variableCurly();
  7593. if (!e) {
  7594. parserInput.save();
  7595. if (parserInput.$char('(')) {
  7596. if ((v = this.selector(false)) && parserInput.$char(')')) {
  7597. e = new (tree.Paren)(v);
  7598. parserInput.forget();
  7599. }
  7600. else {
  7601. parserInput.restore('Missing closing \')\'');
  7602. }
  7603. }
  7604. else {
  7605. parserInput.forget();
  7606. }
  7607. }
  7608. if (e) {
  7609. return new (tree.Element)(c, e, e instanceof tree.Variable, index, fileInfo);
  7610. }
  7611. },
  7612. //
  7613. // Combinators combine elements together, in a Selector.
  7614. //
  7615. // Because our parser isn't white-space sensitive, special care
  7616. // has to be taken, when parsing the descendant combinator, ` `,
  7617. // as it's an empty space. We have to check the previous character
  7618. // in the input, to see if it's a ` ` character. More info on how
  7619. // we deal with this in *combinator.js*.
  7620. //
  7621. combinator: function () {
  7622. var c = parserInput.currentChar();
  7623. if (c === '/') {
  7624. parserInput.save();
  7625. var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
  7626. if (slashedCombinator) {
  7627. parserInput.forget();
  7628. return new (tree.Combinator)(slashedCombinator);
  7629. }
  7630. parserInput.restore();
  7631. }
  7632. if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
  7633. parserInput.i++;
  7634. if (c === '^' && parserInput.currentChar() === '^') {
  7635. c = '^^';
  7636. parserInput.i++;
  7637. }
  7638. while (parserInput.isWhitespace()) {
  7639. parserInput.i++;
  7640. }
  7641. return new (tree.Combinator)(c);
  7642. }
  7643. else if (parserInput.isWhitespace(-1)) {
  7644. return new (tree.Combinator)(' ');
  7645. }
  7646. else {
  7647. return new (tree.Combinator)(null);
  7648. }
  7649. },
  7650. //
  7651. // A CSS Selector
  7652. // with less extensions e.g. the ability to extend and guard
  7653. //
  7654. // .class > div + h1
  7655. // li a:hover
  7656. //
  7657. // Selectors are made out of one or more Elements, see above.
  7658. //
  7659. selector: function (isLess) {
  7660. var index = parserInput.i;
  7661. var elements;
  7662. var extendList;
  7663. var c;
  7664. var e;
  7665. var allExtends;
  7666. var when;
  7667. var condition;
  7668. isLess = isLess !== false;
  7669. while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str('when'))) || (e = this.element())) {
  7670. if (when) {
  7671. condition = expect(this.conditions, 'expected condition');
  7672. }
  7673. else if (condition) {
  7674. error('CSS guard can only be used at the end of selector');
  7675. }
  7676. else if (extendList) {
  7677. if (allExtends) {
  7678. allExtends = allExtends.concat(extendList);
  7679. }
  7680. else {
  7681. allExtends = extendList;
  7682. }
  7683. }
  7684. else {
  7685. if (allExtends) {
  7686. error('Extend can only be used at the end of selector');
  7687. }
  7688. c = parserInput.currentChar();
  7689. if (elements) {
  7690. elements.push(e);
  7691. }
  7692. else {
  7693. elements = [e];
  7694. }
  7695. e = null;
  7696. }
  7697. if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
  7698. break;
  7699. }
  7700. }
  7701. if (elements) {
  7702. return new (tree.Selector)(elements, allExtends, condition, index, fileInfo);
  7703. }
  7704. if (allExtends) {
  7705. error('Extend must be used to extend a selector, it cannot be used on its own');
  7706. }
  7707. },
  7708. selectors: function () {
  7709. var s;
  7710. var selectors;
  7711. while (true) {
  7712. s = this.selector();
  7713. if (!s) {
  7714. break;
  7715. }
  7716. if (selectors) {
  7717. selectors.push(s);
  7718. }
  7719. else {
  7720. selectors = [s];
  7721. }
  7722. parserInput.commentStore.length = 0;
  7723. if (s.condition && selectors.length > 1) {
  7724. error("Guards are only currently allowed on a single selector.");
  7725. }
  7726. if (!parserInput.$char(',')) {
  7727. break;
  7728. }
  7729. if (s.condition) {
  7730. error("Guards are only currently allowed on a single selector.");
  7731. }
  7732. parserInput.commentStore.length = 0;
  7733. }
  7734. return selectors;
  7735. },
  7736. attribute: function () {
  7737. if (!parserInput.$char('[')) {
  7738. return;
  7739. }
  7740. var entities = this.entities;
  7741. var key;
  7742. var val;
  7743. var op;
  7744. //
  7745. // case-insensitive flag
  7746. // e.g. [attr operator value i]
  7747. //
  7748. var cif;
  7749. if (!(key = entities.variableCurly())) {
  7750. key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
  7751. }
  7752. op = parserInput.$re(/^[|~*$^]?=/);
  7753. if (op) {
  7754. val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
  7755. if (val) {
  7756. cif = parserInput.$re(/^[iIsS]/);
  7757. }
  7758. }
  7759. expectChar(']');
  7760. return new (tree.Attribute)(key, op, val, cif);
  7761. },
  7762. //
  7763. // The `block` rule is used by `ruleset` and `mixin.definition`.
  7764. // It's a wrapper around the `primary` rule, with added `{}`.
  7765. //
  7766. block: function () {
  7767. var content;
  7768. if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
  7769. return content;
  7770. }
  7771. },
  7772. blockRuleset: function () {
  7773. var block = this.block();
  7774. if (block) {
  7775. block = new tree.Ruleset(null, block);
  7776. }
  7777. return block;
  7778. },
  7779. detachedRuleset: function () {
  7780. var argInfo;
  7781. var params;
  7782. var variadic;
  7783. parserInput.save();
  7784. if (parserInput.$re(/^[.#]\(/)) {
  7785. /**
  7786. * DR args currently only implemented for each() function, and not
  7787. * yet settable as `@dr: #(@arg) {}`
  7788. * This should be done when DRs are merged with mixins.
  7789. * See: https://github.com/less/less-meta/issues/16
  7790. */
  7791. argInfo = this.mixin.args(false);
  7792. params = argInfo.args;
  7793. variadic = argInfo.variadic;
  7794. if (!parserInput.$char(')')) {
  7795. parserInput.restore();
  7796. return;
  7797. }
  7798. }
  7799. var blockRuleset = this.blockRuleset();
  7800. if (blockRuleset) {
  7801. parserInput.forget();
  7802. if (params) {
  7803. return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
  7804. }
  7805. return new tree.DetachedRuleset(blockRuleset);
  7806. }
  7807. parserInput.restore();
  7808. },
  7809. //
  7810. // div, .class, body > p {...}
  7811. //
  7812. ruleset: function () {
  7813. var selectors;
  7814. var rules;
  7815. var debugInfo;
  7816. parserInput.save();
  7817. if (context.dumpLineNumbers) {
  7818. debugInfo = getDebugInfo(parserInput.i);
  7819. }
  7820. selectors = this.selectors();
  7821. if (selectors && (rules = this.block())) {
  7822. parserInput.forget();
  7823. var ruleset = new (tree.Ruleset)(selectors, rules, context.strictImports);
  7824. if (context.dumpLineNumbers) {
  7825. ruleset.debugInfo = debugInfo;
  7826. }
  7827. return ruleset;
  7828. }
  7829. else {
  7830. parserInput.restore();
  7831. }
  7832. },
  7833. declaration: function () {
  7834. var name;
  7835. var value;
  7836. var index = parserInput.i;
  7837. var hasDR;
  7838. var c = parserInput.currentChar();
  7839. var important;
  7840. var merge;
  7841. var isVariable;
  7842. if (c === '.' || c === '#' || c === '&' || c === ':') {
  7843. return;
  7844. }
  7845. parserInput.save();
  7846. name = this.variable() || this.ruleProperty();
  7847. if (name) {
  7848. isVariable = typeof name === 'string';
  7849. if (isVariable) {
  7850. value = this.detachedRuleset();
  7851. if (value) {
  7852. hasDR = true;
  7853. }
  7854. }
  7855. parserInput.commentStore.length = 0;
  7856. if (!value) {
  7857. // a name returned by this.ruleProperty() is always an array of the form:
  7858. // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
  7859. // where each item is a tree.Keyword or tree.Variable
  7860. merge = !isVariable && name.length > 1 && name.pop().value;
  7861. // Custom property values get permissive parsing
  7862. if (name[0].value && name[0].value.slice(0, 2) === '--') {
  7863. value = this.permissiveValue();
  7864. }
  7865. // Try to store values as anonymous
  7866. // If we need the value later we'll re-parse it in ruleset.parseValue
  7867. else {
  7868. value = this.anonymousValue();
  7869. }
  7870. if (value) {
  7871. parserInput.forget();
  7872. // anonymous values absorb the end ';' which is required for them to work
  7873. return new (tree.Declaration)(name, value, false, merge, index, fileInfo);
  7874. }
  7875. if (!value) {
  7876. value = this.value();
  7877. }
  7878. if (value) {
  7879. important = this.important();
  7880. }
  7881. else if (isVariable) {
  7882. // As a last resort, try permissiveValue
  7883. value = this.permissiveValue();
  7884. }
  7885. }
  7886. if (value && (this.end() || hasDR)) {
  7887. parserInput.forget();
  7888. return new (tree.Declaration)(name, value, important, merge, index, fileInfo);
  7889. }
  7890. else {
  7891. parserInput.restore();
  7892. }
  7893. }
  7894. else {
  7895. parserInput.restore();
  7896. }
  7897. },
  7898. anonymousValue: function () {
  7899. var index = parserInput.i;
  7900. var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
  7901. if (match) {
  7902. return new (tree.Anonymous)(match[1], index);
  7903. }
  7904. },
  7905. /**
  7906. * Used for custom properties, at-rules, and variables (as fallback)
  7907. * Parses almost anything inside of {} [] () "" blocks
  7908. * until it reaches outer-most tokens.
  7909. *
  7910. * First, it will try to parse comments and entities to reach
  7911. * the end. This is mostly like the Expression parser except no
  7912. * math is allowed.
  7913. */
  7914. permissiveValue: function (untilTokens) {
  7915. var i;
  7916. var e;
  7917. var done;
  7918. var value;
  7919. var tok = untilTokens || ';';
  7920. var index = parserInput.i;
  7921. var result = [];
  7922. function testCurrentChar() {
  7923. var char = parserInput.currentChar();
  7924. if (typeof tok === 'string') {
  7925. return char === tok;
  7926. }
  7927. else {
  7928. return tok.test(char);
  7929. }
  7930. }
  7931. if (testCurrentChar()) {
  7932. return;
  7933. }
  7934. value = [];
  7935. do {
  7936. e = this.comment();
  7937. if (e) {
  7938. value.push(e);
  7939. continue;
  7940. }
  7941. e = this.entity();
  7942. if (e) {
  7943. value.push(e);
  7944. }
  7945. } while (e);
  7946. done = testCurrentChar();
  7947. if (value.length > 0) {
  7948. value = new (tree.Expression)(value);
  7949. if (done) {
  7950. return value;
  7951. }
  7952. else {
  7953. result.push(value);
  7954. }
  7955. // Preserve space before $parseUntil as it will not
  7956. if (parserInput.prevChar() === ' ') {
  7957. result.push(new tree.Anonymous(' ', index));
  7958. }
  7959. }
  7960. parserInput.save();
  7961. value = parserInput.$parseUntil(tok);
  7962. if (value) {
  7963. if (typeof value === 'string') {
  7964. error("Expected '" + value + "'", 'Parse');
  7965. }
  7966. if (value.length === 1 && value[0] === ' ') {
  7967. parserInput.forget();
  7968. return new tree.Anonymous('', index);
  7969. }
  7970. var item = void 0;
  7971. for (i = 0; i < value.length; i++) {
  7972. item = value[i];
  7973. if (Array.isArray(item)) {
  7974. // Treat actual quotes as normal quoted values
  7975. result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
  7976. }
  7977. else {
  7978. if (i === value.length - 1) {
  7979. item = item.trim();
  7980. }
  7981. // Treat like quoted values, but replace vars like unquoted expressions
  7982. var quote = new tree.Quoted('\'', item, true, index, fileInfo);
  7983. quote.variableRegex = /@([\w-]+)/g;
  7984. quote.propRegex = /\$([\w-]+)/g;
  7985. result.push(quote);
  7986. }
  7987. }
  7988. parserInput.forget();
  7989. return new tree.Expression(result, true);
  7990. }
  7991. parserInput.restore();
  7992. },
  7993. //
  7994. // An @import atrule
  7995. //
  7996. // @import "lib";
  7997. //
  7998. // Depending on our environment, importing is done differently:
  7999. // In the browser, it's an XHR request, in Node, it would be a
  8000. // file-system operation. The function used for importing is
  8001. // stored in `import`, which we pass to the Import constructor.
  8002. //
  8003. 'import': function () {
  8004. var path;
  8005. var features;
  8006. var index = parserInput.i;
  8007. var dir = parserInput.$re(/^@import\s+/);
  8008. if (dir) {
  8009. var options = (dir ? this.importOptions() : null) || {};
  8010. if ((path = this.entities.quoted() || this.entities.url())) {
  8011. features = this.mediaFeatures();
  8012. if (!parserInput.$char(';')) {
  8013. parserInput.i = index;
  8014. error('missing semi-colon or unrecognised media features on import');
  8015. }
  8016. features = features && new (tree.Value)(features);
  8017. return new (tree.Import)(path, features, options, index, fileInfo);
  8018. }
  8019. else {
  8020. parserInput.i = index;
  8021. error('malformed import statement');
  8022. }
  8023. }
  8024. },
  8025. importOptions: function () {
  8026. var o;
  8027. var options = {};
  8028. var optionName;
  8029. var value;
  8030. // list of options, surrounded by parens
  8031. if (!parserInput.$char('(')) {
  8032. return null;
  8033. }
  8034. do {
  8035. o = this.importOption();
  8036. if (o) {
  8037. optionName = o;
  8038. value = true;
  8039. switch (optionName) {
  8040. case 'css':
  8041. optionName = 'less';
  8042. value = false;
  8043. break;
  8044. case 'once':
  8045. optionName = 'multiple';
  8046. value = false;
  8047. break;
  8048. }
  8049. options[optionName] = value;
  8050. if (!parserInput.$char(',')) {
  8051. break;
  8052. }
  8053. }
  8054. } while (o);
  8055. expectChar(')');
  8056. return options;
  8057. },
  8058. importOption: function () {
  8059. var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
  8060. if (opt) {
  8061. return opt[1];
  8062. }
  8063. },
  8064. mediaFeature: function () {
  8065. var entities = this.entities;
  8066. var nodes = [];
  8067. var e;
  8068. var p;
  8069. parserInput.save();
  8070. do {
  8071. e = entities.keyword() || entities.variable() || entities.mixinLookup();
  8072. if (e) {
  8073. nodes.push(e);
  8074. }
  8075. else if (parserInput.$char('(')) {
  8076. p = this.property();
  8077. e = this.value();
  8078. if (parserInput.$char(')')) {
  8079. if (p && e) {
  8080. nodes.push(new (tree.Paren)(new (tree.Declaration)(p, e, null, null, parserInput.i, fileInfo, true)));
  8081. }
  8082. else if (e) {
  8083. nodes.push(new (tree.Paren)(e));
  8084. }
  8085. else {
  8086. error('badly formed media feature definition');
  8087. }
  8088. }
  8089. else {
  8090. error('Missing closing \')\'', 'Parse');
  8091. }
  8092. }
  8093. } while (e);
  8094. parserInput.forget();
  8095. if (nodes.length > 0) {
  8096. return new (tree.Expression)(nodes);
  8097. }
  8098. },
  8099. mediaFeatures: function () {
  8100. var entities = this.entities;
  8101. var features = [];
  8102. var e;
  8103. do {
  8104. e = this.mediaFeature();
  8105. if (e) {
  8106. features.push(e);
  8107. if (!parserInput.$char(',')) {
  8108. break;
  8109. }
  8110. }
  8111. else {
  8112. e = entities.variable() || entities.mixinLookup();
  8113. if (e) {
  8114. features.push(e);
  8115. if (!parserInput.$char(',')) {
  8116. break;
  8117. }
  8118. }
  8119. }
  8120. } while (e);
  8121. return features.length > 0 ? features : null;
  8122. },
  8123. media: function () {
  8124. var features;
  8125. var rules;
  8126. var media;
  8127. var debugInfo;
  8128. var index = parserInput.i;
  8129. if (context.dumpLineNumbers) {
  8130. debugInfo = getDebugInfo(index);
  8131. }
  8132. parserInput.save();
  8133. if (parserInput.$str('@media')) {
  8134. features = this.mediaFeatures();
  8135. rules = this.block();
  8136. if (!rules) {
  8137. error('media definitions require block statements after any features');
  8138. }
  8139. parserInput.forget();
  8140. media = new (tree.Media)(rules, features, index, fileInfo);
  8141. if (context.dumpLineNumbers) {
  8142. media.debugInfo = debugInfo;
  8143. }
  8144. return media;
  8145. }
  8146. parserInput.restore();
  8147. },
  8148. //
  8149. // A @plugin directive, used to import plugins dynamically.
  8150. //
  8151. // @plugin (args) "lib";
  8152. //
  8153. plugin: function () {
  8154. var path;
  8155. var args;
  8156. var options;
  8157. var index = parserInput.i;
  8158. var dir = parserInput.$re(/^@plugin\s+/);
  8159. if (dir) {
  8160. args = this.pluginArgs();
  8161. if (args) {
  8162. options = {
  8163. pluginArgs: args,
  8164. isPlugin: true
  8165. };
  8166. }
  8167. else {
  8168. options = { isPlugin: true };
  8169. }
  8170. if ((path = this.entities.quoted() || this.entities.url())) {
  8171. if (!parserInput.$char(';')) {
  8172. parserInput.i = index;
  8173. error('missing semi-colon on @plugin');
  8174. }
  8175. return new (tree.Import)(path, null, options, index, fileInfo);
  8176. }
  8177. else {
  8178. parserInput.i = index;
  8179. error('malformed @plugin statement');
  8180. }
  8181. }
  8182. },
  8183. pluginArgs: function () {
  8184. // list of options, surrounded by parens
  8185. parserInput.save();
  8186. if (!parserInput.$char('(')) {
  8187. parserInput.restore();
  8188. return null;
  8189. }
  8190. var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
  8191. if (args[1]) {
  8192. parserInput.forget();
  8193. return args[1].trim();
  8194. }
  8195. else {
  8196. parserInput.restore();
  8197. return null;
  8198. }
  8199. },
  8200. //
  8201. // A CSS AtRule
  8202. //
  8203. // @charset "utf-8";
  8204. //
  8205. atrule: function () {
  8206. var index = parserInput.i;
  8207. var name;
  8208. var value;
  8209. var rules;
  8210. var nonVendorSpecificName;
  8211. var hasIdentifier;
  8212. var hasExpression;
  8213. var hasUnknown;
  8214. var hasBlock = true;
  8215. var isRooted = true;
  8216. if (parserInput.currentChar() !== '@') {
  8217. return;
  8218. }
  8219. value = this['import']() || this.plugin() || this.media();
  8220. if (value) {
  8221. return value;
  8222. }
  8223. parserInput.save();
  8224. name = parserInput.$re(/^@[a-z-]+/);
  8225. if (!name) {
  8226. return;
  8227. }
  8228. nonVendorSpecificName = name;
  8229. if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
  8230. nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1);
  8231. }
  8232. switch (nonVendorSpecificName) {
  8233. case '@charset':
  8234. hasIdentifier = true;
  8235. hasBlock = false;
  8236. break;
  8237. case '@namespace':
  8238. hasExpression = true;
  8239. hasBlock = false;
  8240. break;
  8241. case '@keyframes':
  8242. case '@counter-style':
  8243. hasIdentifier = true;
  8244. break;
  8245. case '@document':
  8246. case '@supports':
  8247. hasUnknown = true;
  8248. isRooted = false;
  8249. break;
  8250. default:
  8251. hasUnknown = true;
  8252. break;
  8253. }
  8254. parserInput.commentStore.length = 0;
  8255. if (hasIdentifier) {
  8256. value = this.entity();
  8257. if (!value) {
  8258. error("expected " + name + " identifier");
  8259. }
  8260. }
  8261. else if (hasExpression) {
  8262. value = this.expression();
  8263. if (!value) {
  8264. error("expected " + name + " expression");
  8265. }
  8266. }
  8267. else if (hasUnknown) {
  8268. value = this.permissiveValue(/^[{;]/);
  8269. hasBlock = (parserInput.currentChar() === '{');
  8270. if (!value) {
  8271. if (!hasBlock && parserInput.currentChar() !== ';') {
  8272. error(name + " rule is missing block or ending semi-colon");
  8273. }
  8274. }
  8275. else if (!value.value) {
  8276. value = null;
  8277. }
  8278. }
  8279. if (hasBlock) {
  8280. rules = this.blockRuleset();
  8281. }
  8282. if (rules || (!hasBlock && value && parserInput.$char(';'))) {
  8283. parserInput.forget();
  8284. return new (tree.AtRule)(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
  8285. }
  8286. parserInput.restore('at-rule options not recognised');
  8287. },
  8288. //
  8289. // A Value is a comma-delimited list of Expressions
  8290. //
  8291. // font-family: Baskerville, Georgia, serif;
  8292. //
  8293. // In a Rule, a Value represents everything after the `:`,
  8294. // and before the `;`.
  8295. //
  8296. value: function () {
  8297. var e;
  8298. var expressions = [];
  8299. var index = parserInput.i;
  8300. do {
  8301. e = this.expression();
  8302. if (e) {
  8303. expressions.push(e);
  8304. if (!parserInput.$char(',')) {
  8305. break;
  8306. }
  8307. }
  8308. } while (e);
  8309. if (expressions.length > 0) {
  8310. return new (tree.Value)(expressions, index);
  8311. }
  8312. },
  8313. important: function () {
  8314. if (parserInput.currentChar() === '!') {
  8315. return parserInput.$re(/^! *important/);
  8316. }
  8317. },
  8318. sub: function () {
  8319. var a;
  8320. var e;
  8321. parserInput.save();
  8322. if (parserInput.$char('(')) {
  8323. a = this.addition();
  8324. if (a && parserInput.$char(')')) {
  8325. parserInput.forget();
  8326. e = new (tree.Expression)([a]);
  8327. e.parens = true;
  8328. return e;
  8329. }
  8330. parserInput.restore('Expected \')\'');
  8331. return;
  8332. }
  8333. parserInput.restore();
  8334. },
  8335. multiplication: function () {
  8336. var m;
  8337. var a;
  8338. var op;
  8339. var operation;
  8340. var isSpaced;
  8341. m = this.operand();
  8342. if (m) {
  8343. isSpaced = parserInput.isWhitespace(-1);
  8344. while (true) {
  8345. if (parserInput.peek(/^\/[*\/]/)) {
  8346. break;
  8347. }
  8348. parserInput.save();
  8349. op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
  8350. if (!op) {
  8351. parserInput.forget();
  8352. break;
  8353. }
  8354. a = this.operand();
  8355. if (!a) {
  8356. parserInput.restore();
  8357. break;
  8358. }
  8359. parserInput.forget();
  8360. m.parensInOp = true;
  8361. a.parensInOp = true;
  8362. operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
  8363. isSpaced = parserInput.isWhitespace(-1);
  8364. }
  8365. return operation || m;
  8366. }
  8367. },
  8368. addition: function () {
  8369. var m;
  8370. var a;
  8371. var op;
  8372. var operation;
  8373. var isSpaced;
  8374. m = this.multiplication();
  8375. if (m) {
  8376. isSpaced = parserInput.isWhitespace(-1);
  8377. while (true) {
  8378. op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-')));
  8379. if (!op) {
  8380. break;
  8381. }
  8382. a = this.multiplication();
  8383. if (!a) {
  8384. break;
  8385. }
  8386. m.parensInOp = true;
  8387. a.parensInOp = true;
  8388. operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
  8389. isSpaced = parserInput.isWhitespace(-1);
  8390. }
  8391. return operation || m;
  8392. }
  8393. },
  8394. conditions: function () {
  8395. var a;
  8396. var b;
  8397. var index = parserInput.i;
  8398. var condition;
  8399. a = this.condition(true);
  8400. if (a) {
  8401. while (true) {
  8402. if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
  8403. break;
  8404. }
  8405. b = this.condition(true);
  8406. if (!b) {
  8407. break;
  8408. }
  8409. condition = new (tree.Condition)('or', condition || a, b, index);
  8410. }
  8411. return condition || a;
  8412. }
  8413. },
  8414. condition: function (needsParens) {
  8415. var result;
  8416. var logical;
  8417. var next;
  8418. function or() {
  8419. return parserInput.$str('or');
  8420. }
  8421. result = this.conditionAnd(needsParens);
  8422. if (!result) {
  8423. return;
  8424. }
  8425. logical = or();
  8426. if (logical) {
  8427. next = this.condition(needsParens);
  8428. if (next) {
  8429. result = new (tree.Condition)(logical, result, next);
  8430. }
  8431. else {
  8432. return;
  8433. }
  8434. }
  8435. return result;
  8436. },
  8437. conditionAnd: function (needsParens) {
  8438. var result;
  8439. var logical;
  8440. var next;
  8441. var self = this;
  8442. function insideCondition() {
  8443. var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
  8444. if (!cond && !needsParens) {
  8445. return self.atomicCondition(needsParens);
  8446. }
  8447. return cond;
  8448. }
  8449. function and() {
  8450. return parserInput.$str('and');
  8451. }
  8452. result = insideCondition();
  8453. if (!result) {
  8454. return;
  8455. }
  8456. logical = and();
  8457. if (logical) {
  8458. next = this.conditionAnd(needsParens);
  8459. if (next) {
  8460. result = new (tree.Condition)(logical, result, next);
  8461. }
  8462. else {
  8463. return;
  8464. }
  8465. }
  8466. return result;
  8467. },
  8468. negatedCondition: function (needsParens) {
  8469. if (parserInput.$str('not')) {
  8470. var result = this.parenthesisCondition(needsParens);
  8471. if (result) {
  8472. result.negate = !result.negate;
  8473. }
  8474. return result;
  8475. }
  8476. },
  8477. parenthesisCondition: function (needsParens) {
  8478. function tryConditionFollowedByParenthesis(me) {
  8479. var body;
  8480. parserInput.save();
  8481. body = me.condition(needsParens);
  8482. if (!body) {
  8483. parserInput.restore();
  8484. return;
  8485. }
  8486. if (!parserInput.$char(')')) {
  8487. parserInput.restore();
  8488. return;
  8489. }
  8490. parserInput.forget();
  8491. return body;
  8492. }
  8493. var body;
  8494. parserInput.save();
  8495. if (!parserInput.$str('(')) {
  8496. parserInput.restore();
  8497. return;
  8498. }
  8499. body = tryConditionFollowedByParenthesis(this);
  8500. if (body) {
  8501. parserInput.forget();
  8502. return body;
  8503. }
  8504. body = this.atomicCondition(needsParens);
  8505. if (!body) {
  8506. parserInput.restore();
  8507. return;
  8508. }
  8509. if (!parserInput.$char(')')) {
  8510. parserInput.restore("expected ')' got '" + parserInput.currentChar() + "'");
  8511. return;
  8512. }
  8513. parserInput.forget();
  8514. return body;
  8515. },
  8516. atomicCondition: function (needsParens) {
  8517. var entities = this.entities;
  8518. var index = parserInput.i;
  8519. var a;
  8520. var b;
  8521. var c;
  8522. var op;
  8523. function cond() {
  8524. return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
  8525. }
  8526. cond = cond.bind(this);
  8527. a = cond();
  8528. if (a) {
  8529. if (parserInput.$char('>')) {
  8530. if (parserInput.$char('=')) {
  8531. op = '>=';
  8532. }
  8533. else {
  8534. op = '>';
  8535. }
  8536. }
  8537. else if (parserInput.$char('<')) {
  8538. if (parserInput.$char('=')) {
  8539. op = '<=';
  8540. }
  8541. else {
  8542. op = '<';
  8543. }
  8544. }
  8545. else if (parserInput.$char('=')) {
  8546. if (parserInput.$char('>')) {
  8547. op = '=>';
  8548. }
  8549. else if (parserInput.$char('<')) {
  8550. op = '=<';
  8551. }
  8552. else {
  8553. op = '=';
  8554. }
  8555. }
  8556. if (op) {
  8557. b = cond();
  8558. if (b) {
  8559. c = new (tree.Condition)(op, a, b, index, false);
  8560. }
  8561. else {
  8562. error('expected expression');
  8563. }
  8564. }
  8565. else {
  8566. c = new (tree.Condition)('=', a, new (tree.Keyword)('true'), index, false);
  8567. }
  8568. return c;
  8569. }
  8570. },
  8571. //
  8572. // An operand is anything that can be part of an operation,
  8573. // such as a Color, or a Variable
  8574. //
  8575. operand: function () {
  8576. var entities = this.entities;
  8577. var negate;
  8578. if (parserInput.peek(/^-[@\$\(]/)) {
  8579. negate = parserInput.$char('-');
  8580. }
  8581. var o = this.sub() || entities.dimension() ||
  8582. entities.color() || entities.variable() ||
  8583. entities.property() || entities.call() ||
  8584. entities.quoted(true) || entities.colorKeyword() ||
  8585. entities.mixinLookup();
  8586. if (negate) {
  8587. o.parensInOp = true;
  8588. o = new (tree.Negative)(o);
  8589. }
  8590. return o;
  8591. },
  8592. //
  8593. // Expressions either represent mathematical operations,
  8594. // or white-space delimited Entities.
  8595. //
  8596. // 1px solid black
  8597. // @var * 2
  8598. //
  8599. expression: function () {
  8600. var entities = [];
  8601. var e;
  8602. var delim;
  8603. var index = parserInput.i;
  8604. do {
  8605. e = this.comment();
  8606. if (e) {
  8607. entities.push(e);
  8608. continue;
  8609. }
  8610. e = this.addition() || this.entity();
  8611. if (e instanceof tree.Comment) {
  8612. e = null;
  8613. }
  8614. if (e) {
  8615. entities.push(e);
  8616. // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
  8617. if (!parserInput.peek(/^\/[\/*]/)) {
  8618. delim = parserInput.$char('/');
  8619. if (delim) {
  8620. entities.push(new (tree.Anonymous)(delim, index));
  8621. }
  8622. }
  8623. }
  8624. } while (e);
  8625. if (entities.length > 0) {
  8626. return new (tree.Expression)(entities);
  8627. }
  8628. },
  8629. property: function () {
  8630. var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
  8631. if (name) {
  8632. return name[1];
  8633. }
  8634. },
  8635. ruleProperty: function () {
  8636. var name = [];
  8637. var index = [];
  8638. var s;
  8639. var k;
  8640. parserInput.save();
  8641. var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
  8642. if (simpleProperty) {
  8643. name = [new (tree.Keyword)(simpleProperty[1])];
  8644. parserInput.forget();
  8645. return name;
  8646. }
  8647. function match(re) {
  8648. var i = parserInput.i;
  8649. var chunk = parserInput.$re(re);
  8650. if (chunk) {
  8651. index.push(i);
  8652. return name.push(chunk[1]);
  8653. }
  8654. }
  8655. match(/^(\*?)/);
  8656. while (true) {
  8657. if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
  8658. break;
  8659. }
  8660. }
  8661. if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) {
  8662. parserInput.forget();
  8663. // at last, we have the complete match now. move forward,
  8664. // convert name particles to tree objects and return:
  8665. if (name[0] === '') {
  8666. name.shift();
  8667. index.shift();
  8668. }
  8669. for (k = 0; k < name.length; k++) {
  8670. s = name[k];
  8671. name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ?
  8672. new (tree.Keyword)(s) :
  8673. (s.charAt(0) === '@' ?
  8674. new (tree.Variable)("@" + s.slice(2, -1), index[k], fileInfo) :
  8675. new (tree.Property)("$" + s.slice(2, -1), index[k], fileInfo));
  8676. }
  8677. return name;
  8678. }
  8679. parserInput.restore();
  8680. }
  8681. }
  8682. };
  8683. };
  8684. Parser.serializeVars = function (vars) {
  8685. var s = '';
  8686. for (var name_1 in vars) {
  8687. if (Object.hasOwnProperty.call(vars, name_1)) {
  8688. var value = vars[name_1];
  8689. s += ((name_1[0] === '@') ? '' : '@') + name_1 + ": " + value + ((String(value).slice(-1) === ';') ? '' : ';');
  8690. }
  8691. }
  8692. return s;
  8693. };
  8694. function boolean(condition) {
  8695. return condition ? Keyword.True : Keyword.False;
  8696. }
  8697. /**
  8698. * Functions with evalArgs set to false are sent context
  8699. * as the first argument.
  8700. */
  8701. function If(context, condition, trueValue, falseValue) {
  8702. return condition.eval(context) ? trueValue.eval(context)
  8703. : (falseValue ? falseValue.eval(context) : new Anonymous);
  8704. }
  8705. If.evalArgs = false;
  8706. function isdefined(context, variable) {
  8707. try {
  8708. variable.eval(context);
  8709. return Keyword.True;
  8710. }
  8711. catch (e) {
  8712. return Keyword.False;
  8713. }
  8714. }
  8715. isdefined.evalArgs = false;
  8716. var boolean$1 = { isdefined: isdefined, boolean: boolean, 'if': If };
  8717. var colorFunctions;
  8718. function clamp(val) {
  8719. return Math.min(1, Math.max(0, val));
  8720. }
  8721. function hsla(origColor, hsl) {
  8722. var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
  8723. if (color) {
  8724. if (origColor.value &&
  8725. /^(rgb|hsl)/.test(origColor.value)) {
  8726. color.value = origColor.value;
  8727. }
  8728. else {
  8729. color.value = 'rgb';
  8730. }
  8731. return color;
  8732. }
  8733. }
  8734. function toHSL(color) {
  8735. if (color.toHSL) {
  8736. return color.toHSL();
  8737. }
  8738. else {
  8739. throw new Error('Argument cannot be evaluated to a color');
  8740. }
  8741. }
  8742. function toHSV(color) {
  8743. if (color.toHSV) {
  8744. return color.toHSV();
  8745. }
  8746. else {
  8747. throw new Error('Argument cannot be evaluated to a color');
  8748. }
  8749. }
  8750. function number$1(n) {
  8751. if (n instanceof Dimension) {
  8752. return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
  8753. }
  8754. else if (typeof n === 'number') {
  8755. return n;
  8756. }
  8757. else {
  8758. throw {
  8759. type: 'Argument',
  8760. message: 'color functions take numbers as parameters'
  8761. };
  8762. }
  8763. }
  8764. function scaled(n, size) {
  8765. if (n instanceof Dimension && n.unit.is('%')) {
  8766. return parseFloat(n.value * size / 100);
  8767. }
  8768. else {
  8769. return number$1(n);
  8770. }
  8771. }
  8772. colorFunctions = {
  8773. rgb: function (r, g, b) {
  8774. var a = 1;
  8775. /**
  8776. * Comma-less syntax
  8777. * e.g. rgb(0 128 255 / 50%)
  8778. */
  8779. if (r instanceof Expression) {
  8780. var val = r.value;
  8781. r = val[0];
  8782. g = val[1];
  8783. b = val[2];
  8784. /**
  8785. * @todo - should this be normalized in
  8786. * function caller? Or parsed differently?
  8787. */
  8788. if (b instanceof Operation) {
  8789. var op = b;
  8790. b = op.operands[0];
  8791. a = op.operands[1];
  8792. }
  8793. }
  8794. var color = colorFunctions.rgba(r, g, b, a);
  8795. if (color) {
  8796. color.value = 'rgb';
  8797. return color;
  8798. }
  8799. },
  8800. rgba: function (r, g, b, a) {
  8801. try {
  8802. if (r instanceof Color) {
  8803. if (g) {
  8804. a = number$1(g);
  8805. }
  8806. else {
  8807. a = r.alpha;
  8808. }
  8809. return new Color(r.rgb, a, 'rgba');
  8810. }
  8811. var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
  8812. a = number$1(a);
  8813. return new Color(rgb, a, 'rgba');
  8814. }
  8815. catch (e) { }
  8816. },
  8817. hsl: function (h, s, l) {
  8818. var a = 1;
  8819. if (h instanceof Expression) {
  8820. var val = h.value;
  8821. h = val[0];
  8822. s = val[1];
  8823. l = val[2];
  8824. if (l instanceof Operation) {
  8825. var op = l;
  8826. l = op.operands[0];
  8827. a = op.operands[1];
  8828. }
  8829. }
  8830. var color = colorFunctions.hsla(h, s, l, a);
  8831. if (color) {
  8832. color.value = 'hsl';
  8833. return color;
  8834. }
  8835. },
  8836. hsla: function (h, s, l, a) {
  8837. try {
  8838. if (h instanceof Color) {
  8839. if (s) {
  8840. a = number$1(s);
  8841. }
  8842. else {
  8843. a = h.alpha;
  8844. }
  8845. return new Color(h.rgb, a, 'hsla');
  8846. }
  8847. var m1_1;
  8848. var m2_1;
  8849. function hue(h) {
  8850. h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
  8851. if (h * 6 < 1) {
  8852. return m1_1 + (m2_1 - m1_1) * h * 6;
  8853. }
  8854. else if (h * 2 < 1) {
  8855. return m2_1;
  8856. }
  8857. else if (h * 3 < 2) {
  8858. return m1_1 + (m2_1 - m1_1) * (2 / 3 - h) * 6;
  8859. }
  8860. else {
  8861. return m1_1;
  8862. }
  8863. }
  8864. h = (number$1(h) % 360) / 360;
  8865. s = clamp(number$1(s));
  8866. l = clamp(number$1(l));
  8867. a = clamp(number$1(a));
  8868. m2_1 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  8869. m1_1 = l * 2 - m2_1;
  8870. var rgb = [
  8871. hue(h + 1 / 3) * 255,
  8872. hue(h) * 255,
  8873. hue(h - 1 / 3) * 255
  8874. ];
  8875. a = number$1(a);
  8876. return new Color(rgb, a, 'hsla');
  8877. }
  8878. catch (e) { }
  8879. },
  8880. hsv: function (h, s, v) {
  8881. return colorFunctions.hsva(h, s, v, 1.0);
  8882. },
  8883. hsva: function (h, s, v, a) {
  8884. h = ((number$1(h) % 360) / 360) * 360;
  8885. s = number$1(s);
  8886. v = number$1(v);
  8887. a = number$1(a);
  8888. var i;
  8889. var f;
  8890. i = Math.floor((h / 60) % 6);
  8891. f = (h / 60) - i;
  8892. var vs = [v,
  8893. v * (1 - s),
  8894. v * (1 - f * s),
  8895. v * (1 - (1 - f) * s)];
  8896. var perm = [[0, 3, 1],
  8897. [2, 0, 1],
  8898. [1, 0, 3],
  8899. [1, 2, 0],
  8900. [3, 1, 0],
  8901. [0, 1, 2]];
  8902. return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
  8903. },
  8904. hue: function (color) {
  8905. return new Dimension(toHSL(color).h);
  8906. },
  8907. saturation: function (color) {
  8908. return new Dimension(toHSL(color).s * 100, '%');
  8909. },
  8910. lightness: function (color) {
  8911. return new Dimension(toHSL(color).l * 100, '%');
  8912. },
  8913. hsvhue: function (color) {
  8914. return new Dimension(toHSV(color).h);
  8915. },
  8916. hsvsaturation: function (color) {
  8917. return new Dimension(toHSV(color).s * 100, '%');
  8918. },
  8919. hsvvalue: function (color) {
  8920. return new Dimension(toHSV(color).v * 100, '%');
  8921. },
  8922. red: function (color) {
  8923. return new Dimension(color.rgb[0]);
  8924. },
  8925. green: function (color) {
  8926. return new Dimension(color.rgb[1]);
  8927. },
  8928. blue: function (color) {
  8929. return new Dimension(color.rgb[2]);
  8930. },
  8931. alpha: function (color) {
  8932. return new Dimension(toHSL(color).a);
  8933. },
  8934. luma: function (color) {
  8935. return new Dimension(color.luma() * color.alpha * 100, '%');
  8936. },
  8937. luminance: function (color) {
  8938. var luminance = (0.2126 * color.rgb[0] / 255) +
  8939. (0.7152 * color.rgb[1] / 255) +
  8940. (0.0722 * color.rgb[2] / 255);
  8941. return new Dimension(luminance * color.alpha * 100, '%');
  8942. },
  8943. saturate: function (color, amount, method) {
  8944. // filter: saturate(3.2);
  8945. // should be kept as is, so check for color
  8946. if (!color.rgb) {
  8947. return null;
  8948. }
  8949. var hsl = toHSL(color);
  8950. if (typeof method !== 'undefined' && method.value === 'relative') {
  8951. hsl.s += hsl.s * amount.value / 100;
  8952. }
  8953. else {
  8954. hsl.s += amount.value / 100;
  8955. }
  8956. hsl.s = clamp(hsl.s);
  8957. return hsla(color, hsl);
  8958. },
  8959. desaturate: function (color, amount, method) {
  8960. var hsl = toHSL(color);
  8961. if (typeof method !== 'undefined' && method.value === 'relative') {
  8962. hsl.s -= hsl.s * amount.value / 100;
  8963. }
  8964. else {
  8965. hsl.s -= amount.value / 100;
  8966. }
  8967. hsl.s = clamp(hsl.s);
  8968. return hsla(color, hsl);
  8969. },
  8970. lighten: function (color, amount, method) {
  8971. var hsl = toHSL(color);
  8972. if (typeof method !== 'undefined' && method.value === 'relative') {
  8973. hsl.l += hsl.l * amount.value / 100;
  8974. }
  8975. else {
  8976. hsl.l += amount.value / 100;
  8977. }
  8978. hsl.l = clamp(hsl.l);
  8979. return hsla(color, hsl);
  8980. },
  8981. darken: function (color, amount, method) {
  8982. var hsl = toHSL(color);
  8983. if (typeof method !== 'undefined' && method.value === 'relative') {
  8984. hsl.l -= hsl.l * amount.value / 100;
  8985. }
  8986. else {
  8987. hsl.l -= amount.value / 100;
  8988. }
  8989. hsl.l = clamp(hsl.l);
  8990. return hsla(color, hsl);
  8991. },
  8992. fadein: function (color, amount, method) {
  8993. var hsl = toHSL(color);
  8994. if (typeof method !== 'undefined' && method.value === 'relative') {
  8995. hsl.a += hsl.a * amount.value / 100;
  8996. }
  8997. else {
  8998. hsl.a += amount.value / 100;
  8999. }
  9000. hsl.a = clamp(hsl.a);
  9001. return hsla(color, hsl);
  9002. },
  9003. fadeout: function (color, amount, method) {
  9004. var hsl = toHSL(color);
  9005. if (typeof method !== 'undefined' && method.value === 'relative') {
  9006. hsl.a -= hsl.a * amount.value / 100;
  9007. }
  9008. else {
  9009. hsl.a -= amount.value / 100;
  9010. }
  9011. hsl.a = clamp(hsl.a);
  9012. return hsla(color, hsl);
  9013. },
  9014. fade: function (color, amount) {
  9015. var hsl = toHSL(color);
  9016. hsl.a = amount.value / 100;
  9017. hsl.a = clamp(hsl.a);
  9018. return hsla(color, hsl);
  9019. },
  9020. spin: function (color, amount) {
  9021. var hsl = toHSL(color);
  9022. var hue = (hsl.h + amount.value) % 360;
  9023. hsl.h = hue < 0 ? 360 + hue : hue;
  9024. return hsla(color, hsl);
  9025. },
  9026. //
  9027. // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
  9028. // http://sass-lang.com
  9029. //
  9030. mix: function (color1, color2, weight) {
  9031. if (!weight) {
  9032. weight = new Dimension(50);
  9033. }
  9034. var p = weight.value / 100.0;
  9035. var w = p * 2 - 1;
  9036. var a = toHSL(color1).a - toHSL(color2).a;
  9037. var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  9038. var w2 = 1 - w1;
  9039. var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
  9040. color1.rgb[1] * w1 + color2.rgb[1] * w2,
  9041. color1.rgb[2] * w1 + color2.rgb[2] * w2];
  9042. var alpha = color1.alpha * p + color2.alpha * (1 - p);
  9043. return new Color(rgb, alpha);
  9044. },
  9045. greyscale: function (color) {
  9046. return colorFunctions.desaturate(color, new Dimension(100));
  9047. },
  9048. contrast: function (color, dark, light, threshold) {
  9049. // filter: contrast(3.2);
  9050. // should be kept as is, so check for color
  9051. if (!color.rgb) {
  9052. return null;
  9053. }
  9054. if (typeof light === 'undefined') {
  9055. light = colorFunctions.rgba(255, 255, 255, 1.0);
  9056. }
  9057. if (typeof dark === 'undefined') {
  9058. dark = colorFunctions.rgba(0, 0, 0, 1.0);
  9059. }
  9060. // Figure out which is actually light and dark:
  9061. if (dark.luma() > light.luma()) {
  9062. var t = light;
  9063. light = dark;
  9064. dark = t;
  9065. }
  9066. if (typeof threshold === 'undefined') {
  9067. threshold = 0.43;
  9068. }
  9069. else {
  9070. threshold = number$1(threshold);
  9071. }
  9072. if (color.luma() < threshold) {
  9073. return light;
  9074. }
  9075. else {
  9076. return dark;
  9077. }
  9078. },
  9079. // Changes made in 2.7.0 - Reverted in 3.0.0
  9080. // contrast: function (color, color1, color2, threshold) {
  9081. // // Return which of `color1` and `color2` has the greatest contrast with `color`
  9082. // // according to the standard WCAG contrast ratio calculation.
  9083. // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  9084. // // The threshold param is no longer used, in line with SASS.
  9085. // // filter: contrast(3.2);
  9086. // // should be kept as is, so check for color
  9087. // if (!color.rgb) {
  9088. // return null;
  9089. // }
  9090. // if (typeof color1 === 'undefined') {
  9091. // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
  9092. // }
  9093. // if (typeof color2 === 'undefined') {
  9094. // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
  9095. // }
  9096. // var contrast1, contrast2;
  9097. // var luma = color.luma();
  9098. // var luma1 = color1.luma();
  9099. // var luma2 = color2.luma();
  9100. // // Calculate contrast ratios for each color
  9101. // if (luma > luma1) {
  9102. // contrast1 = (luma + 0.05) / (luma1 + 0.05);
  9103. // } else {
  9104. // contrast1 = (luma1 + 0.05) / (luma + 0.05);
  9105. // }
  9106. // if (luma > luma2) {
  9107. // contrast2 = (luma + 0.05) / (luma2 + 0.05);
  9108. // } else {
  9109. // contrast2 = (luma2 + 0.05) / (luma + 0.05);
  9110. // }
  9111. // if (contrast1 > contrast2) {
  9112. // return color1;
  9113. // } else {
  9114. // return color2;
  9115. // }
  9116. // },
  9117. argb: function (color) {
  9118. return new Anonymous(color.toARGB());
  9119. },
  9120. color: function (c) {
  9121. if ((c instanceof Quoted) &&
  9122. (/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value))) {
  9123. var val = c.value.slice(1);
  9124. return new Color(val, undefined, "#" + val);
  9125. }
  9126. if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
  9127. c.value = undefined;
  9128. return c;
  9129. }
  9130. throw {
  9131. type: 'Argument',
  9132. message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
  9133. };
  9134. },
  9135. tint: function (color, amount) {
  9136. return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
  9137. },
  9138. shade: function (color, amount) {
  9139. return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
  9140. }
  9141. };
  9142. var color = colorFunctions;
  9143. // Color Blending
  9144. // ref: http://www.w3.org/TR/compositing-1
  9145. function colorBlend(mode, color1, color2) {
  9146. var ab = color1.alpha; // result
  9147. var // backdrop
  9148. cb;
  9149. var as = color2.alpha;
  9150. var // source
  9151. cs;
  9152. var ar;
  9153. var cr;
  9154. var r = [];
  9155. ar = as + ab * (1 - as);
  9156. for (var i = 0; i < 3; i++) {
  9157. cb = color1.rgb[i] / 255;
  9158. cs = color2.rgb[i] / 255;
  9159. cr = mode(cb, cs);
  9160. if (ar) {
  9161. cr = (as * cs + ab * (cb -
  9162. as * (cb + cs - cr))) / ar;
  9163. }
  9164. r[i] = cr * 255;
  9165. }
  9166. return new Color(r, ar);
  9167. }
  9168. var colorBlendModeFunctions = {
  9169. multiply: function (cb, cs) {
  9170. return cb * cs;
  9171. },
  9172. screen: function (cb, cs) {
  9173. return cb + cs - cb * cs;
  9174. },
  9175. overlay: function (cb, cs) {
  9176. cb *= 2;
  9177. return (cb <= 1) ?
  9178. colorBlendModeFunctions.multiply(cb, cs) :
  9179. colorBlendModeFunctions.screen(cb - 1, cs);
  9180. },
  9181. softlight: function (cb, cs) {
  9182. var d = 1;
  9183. var e = cb;
  9184. if (cs > 0.5) {
  9185. e = 1;
  9186. d = (cb > 0.25) ? Math.sqrt(cb)
  9187. : ((16 * cb - 12) * cb + 4) * cb;
  9188. }
  9189. return cb - (1 - 2 * cs) * e * (d - cb);
  9190. },
  9191. hardlight: function (cb, cs) {
  9192. return colorBlendModeFunctions.overlay(cs, cb);
  9193. },
  9194. difference: function (cb, cs) {
  9195. return Math.abs(cb - cs);
  9196. },
  9197. exclusion: function (cb, cs) {
  9198. return cb + cs - 2 * cb * cs;
  9199. },
  9200. // non-w3c functions:
  9201. average: function (cb, cs) {
  9202. return (cb + cs) / 2;
  9203. },
  9204. negation: function (cb, cs) {
  9205. return 1 - Math.abs(cb + cs - 1);
  9206. }
  9207. };
  9208. for (var f$1 in colorBlendModeFunctions) {
  9209. if (colorBlendModeFunctions.hasOwnProperty(f$1)) {
  9210. colorBlend[f$1] = colorBlend.bind(null, colorBlendModeFunctions[f$1]);
  9211. }
  9212. }
  9213. var dataUri = (function (environment) {
  9214. var fallback = function (functionThis, node) { return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context); };
  9215. return { 'data-uri': function (mimetypeNode, filePathNode) {
  9216. if (!filePathNode) {
  9217. filePathNode = mimetypeNode;
  9218. mimetypeNode = null;
  9219. }
  9220. var mimetype = mimetypeNode && mimetypeNode.value;
  9221. var filePath = filePathNode.value;
  9222. var currentFileInfo = this.currentFileInfo;
  9223. var currentDirectory = currentFileInfo.rewriteUrls ?
  9224. currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  9225. var fragmentStart = filePath.indexOf('#');
  9226. var fragment = '';
  9227. if (fragmentStart !== -1) {
  9228. fragment = filePath.slice(fragmentStart);
  9229. filePath = filePath.slice(0, fragmentStart);
  9230. }
  9231. var context = clone(this.context);
  9232. context.rawBuffer = true;
  9233. var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
  9234. if (!fileManager) {
  9235. return fallback(this, filePathNode);
  9236. }
  9237. var useBase64 = false;
  9238. // detect the mimetype if not given
  9239. if (!mimetypeNode) {
  9240. mimetype = environment.mimeLookup(filePath);
  9241. if (mimetype === 'image/svg+xml') {
  9242. useBase64 = false;
  9243. }
  9244. else {
  9245. // use base 64 unless it's an ASCII or UTF-8 format
  9246. var charset = environment.charsetLookup(mimetype);
  9247. useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
  9248. }
  9249. if (useBase64) {
  9250. mimetype += ';base64';
  9251. }
  9252. }
  9253. else {
  9254. useBase64 = /;base64$/.test(mimetype);
  9255. }
  9256. var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
  9257. if (!fileSync.contents) {
  9258. logger$1.warn("Skipped data-uri embedding of " + filePath + " because file not found");
  9259. return fallback(this, filePathNode || mimetypeNode);
  9260. }
  9261. var buf = fileSync.contents;
  9262. if (useBase64 && !environment.encodeBase64) {
  9263. return fallback(this, filePathNode);
  9264. }
  9265. buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
  9266. var uri = "data:" + mimetype + "," + buf + fragment;
  9267. return new URL(new Quoted("\"" + uri + "\"", uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  9268. } };
  9269. });
  9270. var getItemsFromNode = function (node) {
  9271. // handle non-array values as an array of length 1
  9272. // return 'undefined' if index is invalid
  9273. var items = Array.isArray(node.value) ?
  9274. node.value : Array(node);
  9275. return items;
  9276. };
  9277. var list = {
  9278. _SELF: function (n) {
  9279. return n;
  9280. },
  9281. '~': function () {
  9282. var expr = [];
  9283. for (var _i = 0; _i < arguments.length; _i++) {
  9284. expr[_i] = arguments[_i];
  9285. }
  9286. if (expr.length === 1) {
  9287. return expr[0];
  9288. }
  9289. return new Value(expr);
  9290. },
  9291. extract: function (values, index) {
  9292. // (1-based index)
  9293. index = index.value - 1;
  9294. return getItemsFromNode(values)[index];
  9295. },
  9296. length: function (values) {
  9297. return new Dimension(getItemsFromNode(values).length);
  9298. },
  9299. /**
  9300. * Creates a Less list of incremental values.
  9301. * Modeled after Lodash's range function, also exists natively in PHP
  9302. *
  9303. * @param {Dimension} [start=1]
  9304. * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
  9305. * @param {Dimension} [step=1]
  9306. */
  9307. range: function (start, end, step) {
  9308. var from;
  9309. var to;
  9310. var stepValue = 1;
  9311. var list = [];
  9312. if (end) {
  9313. to = end;
  9314. from = start.value;
  9315. if (step) {
  9316. stepValue = step.value;
  9317. }
  9318. }
  9319. else {
  9320. from = 1;
  9321. to = start;
  9322. }
  9323. for (var i = from; i <= to.value; i += stepValue) {
  9324. list.push(new Dimension(i, to.unit));
  9325. }
  9326. return new Expression(list);
  9327. },
  9328. each: function (list, rs) {
  9329. var _this = this;
  9330. var rules = [];
  9331. var newRules;
  9332. var iterator;
  9333. var tryEval = function (val) {
  9334. if (val instanceof Node) {
  9335. return val.eval(_this.context);
  9336. }
  9337. return val;
  9338. };
  9339. if (list.value && !(list instanceof Quoted)) {
  9340. if (Array.isArray(list.value)) {
  9341. iterator = list.value.map(tryEval);
  9342. }
  9343. else {
  9344. iterator = [tryEval(list.value)];
  9345. }
  9346. }
  9347. else if (list.ruleset) {
  9348. iterator = tryEval(list.ruleset).rules;
  9349. }
  9350. else if (list.rules) {
  9351. iterator = list.rules.map(tryEval);
  9352. }
  9353. else if (Array.isArray(list)) {
  9354. iterator = list.map(tryEval);
  9355. }
  9356. else {
  9357. iterator = [tryEval(list)];
  9358. }
  9359. var valueName = '@value';
  9360. var keyName = '@key';
  9361. var indexName = '@index';
  9362. if (rs.params) {
  9363. valueName = rs.params[0] && rs.params[0].name;
  9364. keyName = rs.params[1] && rs.params[1].name;
  9365. indexName = rs.params[2] && rs.params[2].name;
  9366. rs = rs.rules;
  9367. }
  9368. else {
  9369. rs = rs.ruleset;
  9370. }
  9371. for (var i = 0; i < iterator.length; i++) {
  9372. var key = void 0;
  9373. var value = void 0;
  9374. var item = iterator[i];
  9375. if (item instanceof Declaration) {
  9376. key = typeof item.name === 'string' ? item.name : item.name[0].value;
  9377. value = item.value;
  9378. }
  9379. else {
  9380. key = new Dimension(i + 1);
  9381. value = item;
  9382. }
  9383. if (item instanceof Comment) {
  9384. continue;
  9385. }
  9386. newRules = rs.rules.slice(0);
  9387. if (valueName) {
  9388. newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
  9389. }
  9390. if (indexName) {
  9391. newRules.push(new Declaration(indexName, new Dimension(i + 1), false, false, this.index, this.currentFileInfo));
  9392. }
  9393. if (keyName) {
  9394. newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
  9395. }
  9396. rules.push(new Ruleset([new (Selector)([new Element("", '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
  9397. }
  9398. return new Ruleset([new (Selector)([new Element("", '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
  9399. }
  9400. };
  9401. var MathHelper = function (fn, unit, n) {
  9402. if (!(n instanceof Dimension)) {
  9403. throw { type: 'Argument', message: 'argument must be a number' };
  9404. }
  9405. if (unit == null) {
  9406. unit = n.unit;
  9407. }
  9408. else {
  9409. n = n.unify();
  9410. }
  9411. return new Dimension(fn(parseFloat(n.value)), unit);
  9412. };
  9413. var mathFunctions = {
  9414. // name, unit
  9415. ceil: null,
  9416. floor: null,
  9417. sqrt: null,
  9418. abs: null,
  9419. tan: '',
  9420. sin: '',
  9421. cos: '',
  9422. atan: 'rad',
  9423. asin: 'rad',
  9424. acos: 'rad'
  9425. };
  9426. for (var f in mathFunctions) {
  9427. if (mathFunctions.hasOwnProperty(f)) {
  9428. mathFunctions[f] = MathHelper.bind(null, Math[f], mathFunctions[f]);
  9429. }
  9430. }
  9431. mathFunctions.round = function (n, f) {
  9432. var fraction = typeof f === 'undefined' ? 0 : f.value;
  9433. return MathHelper(function (num) { return num.toFixed(fraction); }, null, n);
  9434. };
  9435. var minMax = function (isMin, args) {
  9436. args = Array.prototype.slice.call(args);
  9437. switch (args.length) {
  9438. case 0: throw { type: 'Argument', message: 'one or more arguments required' };
  9439. }
  9440. var i; // key is the unit.toString() for unified Dimension values,
  9441. var j;
  9442. var current;
  9443. var currentUnified;
  9444. var referenceUnified;
  9445. var unit;
  9446. var unitStatic;
  9447. var unitClone;
  9448. var // elems only contains original argument values.
  9449. order = [];
  9450. var values = {};
  9451. // value is the index into the order array.
  9452. for (i = 0; i < args.length; i++) {
  9453. current = args[i];
  9454. if (!(current instanceof Dimension)) {
  9455. if (Array.isArray(args[i].value)) {
  9456. Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
  9457. }
  9458. continue;
  9459. }
  9460. currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
  9461. unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
  9462. unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
  9463. unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
  9464. j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
  9465. if (j === undefined) {
  9466. if (unitStatic !== undefined && unit !== unitStatic) {
  9467. throw { type: 'Argument', message: 'incompatible types' };
  9468. }
  9469. values[unit] = order.length;
  9470. order.push(current);
  9471. continue;
  9472. }
  9473. referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
  9474. if (isMin && currentUnified.value < referenceUnified.value ||
  9475. !isMin && currentUnified.value > referenceUnified.value) {
  9476. order[j] = current;
  9477. }
  9478. }
  9479. if (order.length == 1) {
  9480. return order[0];
  9481. }
  9482. args = order.map(function (a) { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
  9483. return new Anonymous((isMin ? 'min' : 'max') + "(" + args + ")");
  9484. };
  9485. var number = {
  9486. min: function () {
  9487. var args = [];
  9488. for (var _i = 0; _i < arguments.length; _i++) {
  9489. args[_i] = arguments[_i];
  9490. }
  9491. try {
  9492. return minMax(true, args);
  9493. }
  9494. catch (e) { }
  9495. },
  9496. max: function () {
  9497. var args = [];
  9498. for (var _i = 0; _i < arguments.length; _i++) {
  9499. args[_i] = arguments[_i];
  9500. }
  9501. try {
  9502. return minMax(false, args);
  9503. }
  9504. catch (e) { }
  9505. },
  9506. convert: function (val, unit) {
  9507. return val.convertTo(unit.value);
  9508. },
  9509. pi: function () {
  9510. return new Dimension(Math.PI);
  9511. },
  9512. mod: function (a, b) {
  9513. return new Dimension(a.value % b.value, a.unit);
  9514. },
  9515. pow: function (x, y) {
  9516. if (typeof x === 'number' && typeof y === 'number') {
  9517. x = new Dimension(x);
  9518. y = new Dimension(y);
  9519. }
  9520. else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
  9521. throw { type: 'Argument', message: 'arguments must be numbers' };
  9522. }
  9523. return new Dimension(Math.pow(x.value, y.value), x.unit);
  9524. },
  9525. percentage: function (n) {
  9526. var result = MathHelper(function (num) { return num * 100; }, '%', n);
  9527. return result;
  9528. }
  9529. };
  9530. var string = {
  9531. e: function (str) {
  9532. return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
  9533. },
  9534. escape: function (str) {
  9535. return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
  9536. .replace(/\(/g, '%28').replace(/\)/g, '%29'));
  9537. },
  9538. replace: function (string, pattern, replacement, flags) {
  9539. var result = string.value;
  9540. replacement = (replacement.type === 'Quoted') ?
  9541. replacement.value : replacement.toCSS();
  9542. result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
  9543. return new Quoted(string.quote || '', result, string.escaped);
  9544. },
  9545. '%': function (string /* arg, arg, ... */) {
  9546. var args = Array.prototype.slice.call(arguments, 1);
  9547. var result = string.value;
  9548. var _loop_1 = function (i) {
  9549. /* jshint loopfunc:true */
  9550. result = result.replace(/%[sda]/i, function (token) {
  9551. var value = ((args[i].type === 'Quoted') &&
  9552. token.match(/s/i)) ? args[i].value : args[i].toCSS();
  9553. return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
  9554. });
  9555. };
  9556. for (var i = 0; i < args.length; i++) {
  9557. _loop_1(i);
  9558. }
  9559. result = result.replace(/%%/g, '%');
  9560. return new Quoted(string.quote || '', result, string.escaped);
  9561. }
  9562. };
  9563. var svg = (function (environment) {
  9564. return { 'svg-gradient': function (direction) {
  9565. var stops;
  9566. var gradientDirectionSvg;
  9567. var gradientType = 'linear';
  9568. var rectangleDimension = 'x="0" y="0" width="1" height="1"';
  9569. var renderEnv = { compress: false };
  9570. var returner;
  9571. var directionValue = direction.toCSS(renderEnv);
  9572. var i;
  9573. var color;
  9574. var position;
  9575. var positionValue;
  9576. var alpha;
  9577. function throwArgumentDescriptor() {
  9578. throw { type: 'Argument',
  9579. message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
  9580. ' end_color [end_position] or direction, color list' };
  9581. }
  9582. if (arguments.length == 2) {
  9583. if (arguments[1].value.length < 2) {
  9584. throwArgumentDescriptor();
  9585. }
  9586. stops = arguments[1].value;
  9587. }
  9588. else if (arguments.length < 3) {
  9589. throwArgumentDescriptor();
  9590. }
  9591. else {
  9592. stops = Array.prototype.slice.call(arguments, 1);
  9593. }
  9594. switch (directionValue) {
  9595. case 'to bottom':
  9596. gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
  9597. break;
  9598. case 'to right':
  9599. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
  9600. break;
  9601. case 'to bottom right':
  9602. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
  9603. break;
  9604. case 'to top right':
  9605. gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
  9606. break;
  9607. case 'ellipse':
  9608. case 'ellipse at center':
  9609. gradientType = 'radial';
  9610. gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
  9611. rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
  9612. break;
  9613. default:
  9614. throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
  9615. ' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
  9616. }
  9617. returner = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1 1\"><" + gradientType + "Gradient id=\"g\" " + gradientDirectionSvg + ">";
  9618. for (i = 0; i < stops.length; i += 1) {
  9619. if (stops[i] instanceof Expression) {
  9620. color = stops[i].value[0];
  9621. position = stops[i].value[1];
  9622. }
  9623. else {
  9624. color = stops[i];
  9625. position = undefined;
  9626. }
  9627. if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) {
  9628. throwArgumentDescriptor();
  9629. }
  9630. positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
  9631. alpha = color.alpha;
  9632. returner += "<stop offset=\"" + positionValue + "\" stop-color=\"" + color.toRGB() + "\"" + (alpha < 1 ? " stop-opacity=\"" + alpha + "\"" : '') + "/>";
  9633. }
  9634. returner += "</" + gradientType + "Gradient><rect " + rectangleDimension + " fill=\"url(#g)\" /></svg>";
  9635. returner = encodeURIComponent(returner);
  9636. returner = "data:image/svg+xml," + returner;
  9637. return new URL(new Quoted("'" + returner + "'", returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  9638. } };
  9639. });
  9640. var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; };
  9641. var isunit = function (n, unit) {
  9642. if (unit === undefined) {
  9643. throw { type: 'Argument', message: 'missing the required second argument to isunit.' };
  9644. }
  9645. unit = typeof unit.value === 'string' ? unit.value : unit;
  9646. if (typeof unit !== 'string') {
  9647. throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' };
  9648. }
  9649. return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
  9650. };
  9651. var types = {
  9652. isruleset: function (n) {
  9653. return isa(n, DetachedRuleset);
  9654. },
  9655. iscolor: function (n) {
  9656. return isa(n, Color);
  9657. },
  9658. isnumber: function (n) {
  9659. return isa(n, Dimension);
  9660. },
  9661. isstring: function (n) {
  9662. return isa(n, Quoted);
  9663. },
  9664. iskeyword: function (n) {
  9665. return isa(n, Keyword);
  9666. },
  9667. isurl: function (n) {
  9668. return isa(n, URL);
  9669. },
  9670. ispixel: function (n) {
  9671. return isunit(n, 'px');
  9672. },
  9673. ispercentage: function (n) {
  9674. return isunit(n, '%');
  9675. },
  9676. isem: function (n) {
  9677. return isunit(n, 'em');
  9678. },
  9679. isunit: isunit,
  9680. unit: function (val, unit) {
  9681. if (!(val instanceof Dimension)) {
  9682. throw { type: 'Argument',
  9683. message: "the first argument to unit must be a number" + (val instanceof Operation ? '. Have you forgotten parenthesis?' : '') };
  9684. }
  9685. if (unit) {
  9686. if (unit instanceof Keyword) {
  9687. unit = unit.value;
  9688. }
  9689. else {
  9690. unit = unit.toCSS();
  9691. }
  9692. }
  9693. else {
  9694. unit = '';
  9695. }
  9696. return new Dimension(val.value, unit);
  9697. },
  9698. 'get-unit': function (n) {
  9699. return new Anonymous(n.unit);
  9700. }
  9701. };
  9702. var functions = (function (environment) {
  9703. var functions = { functionRegistry: functionRegistry, functionCaller: functionCaller };
  9704. // register functions
  9705. functionRegistry.addMultiple(boolean$1);
  9706. functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
  9707. functionRegistry.addMultiple(color);
  9708. functionRegistry.addMultiple(colorBlend);
  9709. functionRegistry.addMultiple(dataUri(environment));
  9710. functionRegistry.addMultiple(list);
  9711. functionRegistry.addMultiple(mathFunctions);
  9712. functionRegistry.addMultiple(number);
  9713. functionRegistry.addMultiple(string);
  9714. functionRegistry.addMultiple(svg());
  9715. functionRegistry.addMultiple(types);
  9716. return functions;
  9717. });
  9718. function transformTree (root, options) {
  9719. options = options || {};
  9720. var evaldRoot;
  9721. var variables = options.variables;
  9722. var evalEnv = new contexts.Eval(options);
  9723. //
  9724. // Allows setting variables with a hash, so:
  9725. //
  9726. // `{ color: new tree.Color('#f01') }` will become:
  9727. //
  9728. // new tree.Declaration('@color',
  9729. // new tree.Value([
  9730. // new tree.Expression([
  9731. // new tree.Color('#f01')
  9732. // ])
  9733. // ])
  9734. // )
  9735. //
  9736. if (typeof variables === 'object' && !Array.isArray(variables)) {
  9737. variables = Object.keys(variables).map(function (k) {
  9738. var value = variables[k];
  9739. if (!(value instanceof tree.Value)) {
  9740. if (!(value instanceof tree.Expression)) {
  9741. value = new tree.Expression([value]);
  9742. }
  9743. value = new tree.Value([value]);
  9744. }
  9745. return new tree.Declaration("@" + k, value, false, null, 0);
  9746. });
  9747. evalEnv.frames = [new tree.Ruleset(null, variables)];
  9748. }
  9749. var visitors$1 = [
  9750. new visitors.JoinSelectorVisitor(),
  9751. new visitors.MarkVisibleSelectorsVisitor(true),
  9752. new visitors.ExtendVisitor(),
  9753. new visitors.ToCSSVisitor({ compress: Boolean(options.compress) })
  9754. ];
  9755. var preEvalVisitors = [];
  9756. var v;
  9757. var visitorIterator;
  9758. /**
  9759. * first() / get() allows visitors to be added while visiting
  9760. *
  9761. * @todo Add scoping for visitors just like functions for @plugin; right now they're global
  9762. */
  9763. if (options.pluginManager) {
  9764. visitorIterator = options.pluginManager.visitor();
  9765. for (var i = 0; i < 2; i++) {
  9766. visitorIterator.first();
  9767. while ((v = visitorIterator.get())) {
  9768. if (v.isPreEvalVisitor) {
  9769. if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
  9770. preEvalVisitors.push(v);
  9771. v.run(root);
  9772. }
  9773. }
  9774. else {
  9775. if (i === 0 || visitors$1.indexOf(v) === -1) {
  9776. if (v.isPreVisitor) {
  9777. visitors$1.unshift(v);
  9778. }
  9779. else {
  9780. visitors$1.push(v);
  9781. }
  9782. }
  9783. }
  9784. }
  9785. }
  9786. }
  9787. evaldRoot = root.eval(evalEnv);
  9788. for (var i = 0; i < visitors$1.length; i++) {
  9789. visitors$1[i].run(evaldRoot);
  9790. }
  9791. // Run any remaining visitors added after eval pass
  9792. if (options.pluginManager) {
  9793. visitorIterator.first();
  9794. while ((v = visitorIterator.get())) {
  9795. if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
  9796. v.run(evaldRoot);
  9797. }
  9798. }
  9799. }
  9800. return evaldRoot;
  9801. }
  9802. /**
  9803. * Plugin Manager
  9804. */
  9805. var PluginManager = /** @class */ (function () {
  9806. function PluginManager(less) {
  9807. this.less = less;
  9808. this.visitors = [];
  9809. this.preProcessors = [];
  9810. this.postProcessors = [];
  9811. this.installedPlugins = [];
  9812. this.fileManagers = [];
  9813. this.iterator = -1;
  9814. this.pluginCache = {};
  9815. this.Loader = new less.PluginLoader(less);
  9816. }
  9817. /**
  9818. * Adds all the plugins in the array
  9819. * @param {Array} plugins
  9820. */
  9821. PluginManager.prototype.addPlugins = function (plugins) {
  9822. if (plugins) {
  9823. for (var i = 0; i < plugins.length; i++) {
  9824. this.addPlugin(plugins[i]);
  9825. }
  9826. }
  9827. };
  9828. /**
  9829. *
  9830. * @param plugin
  9831. * @param {String} filename
  9832. */
  9833. PluginManager.prototype.addPlugin = function (plugin, filename, functionRegistry) {
  9834. this.installedPlugins.push(plugin);
  9835. if (filename) {
  9836. this.pluginCache[filename] = plugin;
  9837. }
  9838. if (plugin.install) {
  9839. plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
  9840. }
  9841. };
  9842. /**
  9843. *
  9844. * @param filename
  9845. */
  9846. PluginManager.prototype.get = function (filename) {
  9847. return this.pluginCache[filename];
  9848. };
  9849. /**
  9850. * Adds a visitor. The visitor object has options on itself to determine
  9851. * when it should run.
  9852. * @param visitor
  9853. */
  9854. PluginManager.prototype.addVisitor = function (visitor) {
  9855. this.visitors.push(visitor);
  9856. };
  9857. /**
  9858. * Adds a pre processor object
  9859. * @param {object} preProcessor
  9860. * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
  9861. */
  9862. PluginManager.prototype.addPreProcessor = function (preProcessor, priority) {
  9863. var indexToInsertAt;
  9864. for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
  9865. if (this.preProcessors[indexToInsertAt].priority >= priority) {
  9866. break;
  9867. }
  9868. }
  9869. this.preProcessors.splice(indexToInsertAt, 0, { preProcessor: preProcessor, priority: priority });
  9870. };
  9871. /**
  9872. * Adds a post processor object
  9873. * @param {object} postProcessor
  9874. * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
  9875. */
  9876. PluginManager.prototype.addPostProcessor = function (postProcessor, priority) {
  9877. var indexToInsertAt;
  9878. for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
  9879. if (this.postProcessors[indexToInsertAt].priority >= priority) {
  9880. break;
  9881. }
  9882. }
  9883. this.postProcessors.splice(indexToInsertAt, 0, { postProcessor: postProcessor, priority: priority });
  9884. };
  9885. /**
  9886. *
  9887. * @param manager
  9888. */
  9889. PluginManager.prototype.addFileManager = function (manager) {
  9890. this.fileManagers.push(manager);
  9891. };
  9892. /**
  9893. *
  9894. * @returns {Array}
  9895. * @private
  9896. */
  9897. PluginManager.prototype.getPreProcessors = function () {
  9898. var preProcessors = [];
  9899. for (var i = 0; i < this.preProcessors.length; i++) {
  9900. preProcessors.push(this.preProcessors[i].preProcessor);
  9901. }
  9902. return preProcessors;
  9903. };
  9904. /**
  9905. *
  9906. * @returns {Array}
  9907. * @private
  9908. */
  9909. PluginManager.prototype.getPostProcessors = function () {
  9910. var postProcessors = [];
  9911. for (var i = 0; i < this.postProcessors.length; i++) {
  9912. postProcessors.push(this.postProcessors[i].postProcessor);
  9913. }
  9914. return postProcessors;
  9915. };
  9916. /**
  9917. *
  9918. * @returns {Array}
  9919. * @private
  9920. */
  9921. PluginManager.prototype.getVisitors = function () {
  9922. return this.visitors;
  9923. };
  9924. PluginManager.prototype.visitor = function () {
  9925. var self = this;
  9926. return {
  9927. first: function () {
  9928. self.iterator = -1;
  9929. return self.visitors[self.iterator];
  9930. },
  9931. get: function () {
  9932. self.iterator += 1;
  9933. return self.visitors[self.iterator];
  9934. }
  9935. };
  9936. };
  9937. /**
  9938. *
  9939. * @returns {Array}
  9940. * @private
  9941. */
  9942. PluginManager.prototype.getFileManagers = function () {
  9943. return this.fileManagers;
  9944. };
  9945. return PluginManager;
  9946. }());
  9947. var pm;
  9948. var PluginManagerFactory = function (less, newFactory) {
  9949. if (newFactory || !pm) {
  9950. pm = new PluginManager(less);
  9951. }
  9952. return pm;
  9953. };
  9954. function SourceMapOutput (environment) {
  9955. var SourceMapOutput = /** @class */ (function () {
  9956. function SourceMapOutput(options) {
  9957. this._css = [];
  9958. this._rootNode = options.rootNode;
  9959. this._contentsMap = options.contentsMap;
  9960. this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
  9961. if (options.sourceMapFilename) {
  9962. this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
  9963. }
  9964. this._outputFilename = options.outputFilename;
  9965. this.sourceMapURL = options.sourceMapURL;
  9966. if (options.sourceMapBasepath) {
  9967. this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
  9968. }
  9969. if (options.sourceMapRootpath) {
  9970. this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
  9971. if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
  9972. this._sourceMapRootpath += '/';
  9973. }
  9974. }
  9975. else {
  9976. this._sourceMapRootpath = '';
  9977. }
  9978. this._outputSourceFiles = options.outputSourceFiles;
  9979. this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
  9980. this._lineNumber = 0;
  9981. this._column = 0;
  9982. }
  9983. SourceMapOutput.prototype.removeBasepath = function (path) {
  9984. if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
  9985. path = path.substring(this._sourceMapBasepath.length);
  9986. if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
  9987. path = path.substring(1);
  9988. }
  9989. }
  9990. return path;
  9991. };
  9992. SourceMapOutput.prototype.normalizeFilename = function (filename) {
  9993. filename = filename.replace(/\\/g, '/');
  9994. filename = this.removeBasepath(filename);
  9995. return (this._sourceMapRootpath || '') + filename;
  9996. };
  9997. SourceMapOutput.prototype.add = function (chunk, fileInfo, index, mapLines) {
  9998. // ignore adding empty strings
  9999. if (!chunk) {
  10000. return;
  10001. }
  10002. var lines, sourceLines, columns, sourceColumns, i;
  10003. if (fileInfo && fileInfo.filename) {
  10004. var inputSource = this._contentsMap[fileInfo.filename];
  10005. // remove vars/banner added to the top of the file
  10006. if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
  10007. // adjust the index
  10008. index -= this._contentsIgnoredCharsMap[fileInfo.filename];
  10009. if (index < 0) {
  10010. index = 0;
  10011. }
  10012. // adjust the source
  10013. inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
  10014. }
  10015. /**
  10016. * ignore empty content, or failsafe
  10017. * if contents map is incorrect
  10018. */
  10019. if (inputSource === undefined) {
  10020. this._css.push(chunk);
  10021. return;
  10022. }
  10023. inputSource = inputSource.substring(0, index);
  10024. sourceLines = inputSource.split('\n');
  10025. sourceColumns = sourceLines[sourceLines.length - 1];
  10026. }
  10027. lines = chunk.split('\n');
  10028. columns = lines[lines.length - 1];
  10029. if (fileInfo && fileInfo.filename) {
  10030. if (!mapLines) {
  10031. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column },
  10032. original: { line: sourceLines.length, column: sourceColumns.length },
  10033. source: this.normalizeFilename(fileInfo.filename) });
  10034. }
  10035. else {
  10036. for (i = 0; i < lines.length; i++) {
  10037. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0 },
  10038. original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0 },
  10039. source: this.normalizeFilename(fileInfo.filename) });
  10040. }
  10041. }
  10042. }
  10043. if (lines.length === 1) {
  10044. this._column += columns.length;
  10045. }
  10046. else {
  10047. this._lineNumber += lines.length - 1;
  10048. this._column = columns.length;
  10049. }
  10050. this._css.push(chunk);
  10051. };
  10052. SourceMapOutput.prototype.isEmpty = function () {
  10053. return this._css.length === 0;
  10054. };
  10055. SourceMapOutput.prototype.toCSS = function (context) {
  10056. this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
  10057. if (this._outputSourceFiles) {
  10058. for (var filename in this._contentsMap) {
  10059. if (this._contentsMap.hasOwnProperty(filename)) {
  10060. var source = this._contentsMap[filename];
  10061. if (this._contentsIgnoredCharsMap[filename]) {
  10062. source = source.slice(this._contentsIgnoredCharsMap[filename]);
  10063. }
  10064. this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
  10065. }
  10066. }
  10067. }
  10068. this._rootNode.genCSS(context, this);
  10069. if (this._css.length > 0) {
  10070. var sourceMapURL = void 0;
  10071. var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
  10072. if (this.sourceMapURL) {
  10073. sourceMapURL = this.sourceMapURL;
  10074. }
  10075. else if (this._sourceMapFilename) {
  10076. sourceMapURL = this._sourceMapFilename;
  10077. }
  10078. this.sourceMapURL = sourceMapURL;
  10079. this.sourceMap = sourceMapContent;
  10080. }
  10081. return this._css.join('');
  10082. };
  10083. return SourceMapOutput;
  10084. }());
  10085. return SourceMapOutput;
  10086. }
  10087. function SourceMapBuilder (SourceMapOutput, environment) {
  10088. var SourceMapBuilder = /** @class */ (function () {
  10089. function SourceMapBuilder(options) {
  10090. this.options = options;
  10091. }
  10092. SourceMapBuilder.prototype.toCSS = function (rootNode, options, imports) {
  10093. var sourceMapOutput = new SourceMapOutput({
  10094. contentsIgnoredCharsMap: imports.contentsIgnoredChars,
  10095. rootNode: rootNode,
  10096. contentsMap: imports.contents,
  10097. sourceMapFilename: this.options.sourceMapFilename,
  10098. sourceMapURL: this.options.sourceMapURL,
  10099. outputFilename: this.options.sourceMapOutputFilename,
  10100. sourceMapBasepath: this.options.sourceMapBasepath,
  10101. sourceMapRootpath: this.options.sourceMapRootpath,
  10102. outputSourceFiles: this.options.outputSourceFiles,
  10103. sourceMapGenerator: this.options.sourceMapGenerator,
  10104. sourceMapFileInline: this.options.sourceMapFileInline,
  10105. disableSourcemapAnnotation: this.options.disableSourcemapAnnotation
  10106. });
  10107. var css = sourceMapOutput.toCSS(options);
  10108. this.sourceMap = sourceMapOutput.sourceMap;
  10109. this.sourceMapURL = sourceMapOutput.sourceMapURL;
  10110. if (this.options.sourceMapInputFilename) {
  10111. this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
  10112. }
  10113. if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
  10114. this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
  10115. }
  10116. return css + this.getCSSAppendage();
  10117. };
  10118. SourceMapBuilder.prototype.getCSSAppendage = function () {
  10119. var sourceMapURL = this.sourceMapURL;
  10120. if (this.options.sourceMapFileInline) {
  10121. if (this.sourceMap === undefined) {
  10122. return '';
  10123. }
  10124. sourceMapURL = "data:application/json;base64," + environment.encodeBase64(this.sourceMap);
  10125. }
  10126. if (this.options.disableSourcemapAnnotation) {
  10127. return '';
  10128. }
  10129. if (sourceMapURL) {
  10130. return "/*# sourceMappingURL=" + sourceMapURL + " */";
  10131. }
  10132. return '';
  10133. };
  10134. SourceMapBuilder.prototype.getExternalSourceMap = function () {
  10135. return this.sourceMap;
  10136. };
  10137. SourceMapBuilder.prototype.setExternalSourceMap = function (sourceMap) {
  10138. this.sourceMap = sourceMap;
  10139. };
  10140. SourceMapBuilder.prototype.isInline = function () {
  10141. return this.options.sourceMapFileInline;
  10142. };
  10143. SourceMapBuilder.prototype.getSourceMapURL = function () {
  10144. return this.sourceMapURL;
  10145. };
  10146. SourceMapBuilder.prototype.getOutputFilename = function () {
  10147. return this.options.sourceMapOutputFilename;
  10148. };
  10149. SourceMapBuilder.prototype.getInputFilename = function () {
  10150. return this.sourceMapInputFilename;
  10151. };
  10152. return SourceMapBuilder;
  10153. }());
  10154. return SourceMapBuilder;
  10155. }
  10156. function ParseTree (SourceMapBuilder) {
  10157. var ParseTree = /** @class */ (function () {
  10158. function ParseTree(root, imports) {
  10159. this.root = root;
  10160. this.imports = imports;
  10161. }
  10162. ParseTree.prototype.toCSS = function (options) {
  10163. var evaldRoot;
  10164. var result = {};
  10165. var sourceMapBuilder;
  10166. try {
  10167. evaldRoot = transformTree(this.root, options);
  10168. }
  10169. catch (e) {
  10170. throw new LessError(e, this.imports);
  10171. }
  10172. try {
  10173. var compress = Boolean(options.compress);
  10174. if (compress) {
  10175. logger$1.warn('The compress option has been deprecated. ' +
  10176. 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
  10177. }
  10178. var toCSSOptions = {
  10179. compress: compress,
  10180. dumpLineNumbers: options.dumpLineNumbers,
  10181. strictUnits: Boolean(options.strictUnits),
  10182. numPrecision: 8
  10183. };
  10184. if (options.sourceMap) {
  10185. sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
  10186. result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
  10187. }
  10188. else {
  10189. result.css = evaldRoot.toCSS(toCSSOptions);
  10190. }
  10191. }
  10192. catch (e) {
  10193. throw new LessError(e, this.imports);
  10194. }
  10195. if (options.pluginManager) {
  10196. var postProcessors = options.pluginManager.getPostProcessors();
  10197. for (var i = 0; i < postProcessors.length; i++) {
  10198. result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports });
  10199. }
  10200. }
  10201. if (options.sourceMap) {
  10202. result.map = sourceMapBuilder.getExternalSourceMap();
  10203. }
  10204. result.imports = [];
  10205. for (var file in this.imports.files) {
  10206. if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) {
  10207. result.imports.push(file);
  10208. }
  10209. }
  10210. return result;
  10211. };
  10212. return ParseTree;
  10213. }());
  10214. return ParseTree;
  10215. }
  10216. function ImportManager (environment) {
  10217. // FileInfo = {
  10218. // 'rewriteUrls' - option - whether to adjust URL's to be relative
  10219. // 'filename' - full resolved filename of current file
  10220. // 'rootpath' - path to append to normal URLs for this node
  10221. // 'currentDirectory' - path to the current file, absolute
  10222. // 'rootFilename' - filename of the base file
  10223. // 'entryPath' - absolute path to the entry file
  10224. // 'reference' - whether the file should not be output and only output parts that are referenced
  10225. var ImportManager = /** @class */ (function () {
  10226. function ImportManager(less, context, rootFileInfo) {
  10227. this.less = less;
  10228. this.rootFilename = rootFileInfo.filename;
  10229. this.paths = context.paths || []; // Search paths, when importing
  10230. this.contents = {}; // map - filename to contents of all the files
  10231. this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
  10232. this.mime = context.mime;
  10233. this.error = null;
  10234. this.context = context;
  10235. // Deprecated? Unused outside of here, could be useful.
  10236. this.queue = []; // Files which haven't been imported yet
  10237. this.files = {}; // Holds the imported parse trees.
  10238. }
  10239. /**
  10240. * Add an import to be imported
  10241. * @param path - the raw path
  10242. * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
  10243. * @param currentFileInfo - the current file info (used for instance to work out relative paths)
  10244. * @param importOptions - import options
  10245. * @param callback - callback for when it is imported
  10246. */
  10247. ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) {
  10248. var importManager = this, pluginLoader = this.context.pluginManager.Loader;
  10249. this.queue.push(path);
  10250. var fileParsedFunc = function (e, root, fullPath) {
  10251. importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
  10252. var importedEqualsRoot = fullPath === importManager.rootFilename;
  10253. if (importOptions.optional && e) {
  10254. callback(null, { rules: [] }, false, null);
  10255. logger$1.info("The file " + fullPath + " was skipped because it was not found and the import was marked optional.");
  10256. }
  10257. else {
  10258. // Inline imports aren't cached here.
  10259. // If we start to cache them, please make sure they won't conflict with non-inline imports of the
  10260. // same name as they used to do before this comment and the condition below have been added.
  10261. if (!importManager.files[fullPath] && !importOptions.inline) {
  10262. importManager.files[fullPath] = { root: root, options: importOptions };
  10263. }
  10264. if (e && !importManager.error) {
  10265. importManager.error = e;
  10266. }
  10267. callback(e, root, importedEqualsRoot, fullPath);
  10268. }
  10269. };
  10270. var newFileInfo = {
  10271. rewriteUrls: this.context.rewriteUrls,
  10272. entryPath: currentFileInfo.entryPath,
  10273. rootpath: currentFileInfo.rootpath,
  10274. rootFilename: currentFileInfo.rootFilename
  10275. };
  10276. var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
  10277. if (!fileManager) {
  10278. fileParsedFunc({ message: "Could not find a file-manager for " + path });
  10279. return;
  10280. }
  10281. var loadFileCallback = function (loadedFile) {
  10282. var plugin;
  10283. var resolvedFilename = loadedFile.filename;
  10284. var contents = loadedFile.contents.replace(/^\uFEFF/, '');
  10285. // Pass on an updated rootpath if path of imported file is relative and file
  10286. // is in a (sub|sup) directory
  10287. //
  10288. // Examples:
  10289. // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
  10290. // then rootpath should become 'less/module/nav/'
  10291. // - If path of imported file is '../mixins.less' and rootpath is 'less/',
  10292. // then rootpath should become 'less/../'
  10293. newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
  10294. if (newFileInfo.rewriteUrls) {
  10295. newFileInfo.rootpath = fileManager.join((importManager.context.rootpath || ''), fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
  10296. if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
  10297. newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
  10298. }
  10299. }
  10300. newFileInfo.filename = resolvedFilename;
  10301. var newEnv = new contexts.Parse(importManager.context);
  10302. newEnv.processImports = false;
  10303. importManager.contents[resolvedFilename] = contents;
  10304. if (currentFileInfo.reference || importOptions.reference) {
  10305. newFileInfo.reference = true;
  10306. }
  10307. if (importOptions.isPlugin) {
  10308. plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
  10309. if (plugin instanceof LessError) {
  10310. fileParsedFunc(plugin, null, resolvedFilename);
  10311. }
  10312. else {
  10313. fileParsedFunc(null, plugin, resolvedFilename);
  10314. }
  10315. }
  10316. else if (importOptions.inline) {
  10317. fileParsedFunc(null, contents, resolvedFilename);
  10318. }
  10319. else {
  10320. // import (multiple) parse trees apparently get altered and can't be cached.
  10321. // TODO: investigate why this is
  10322. if (importManager.files[resolvedFilename]
  10323. && !importManager.files[resolvedFilename].options.multiple
  10324. && !importOptions.multiple) {
  10325. fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
  10326. }
  10327. else {
  10328. new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
  10329. fileParsedFunc(e, root, resolvedFilename);
  10330. });
  10331. }
  10332. }
  10333. };
  10334. var loadedFile;
  10335. var promise;
  10336. var context = clone(this.context);
  10337. if (tryAppendExtension) {
  10338. context.ext = importOptions.isPlugin ? '.js' : '.less';
  10339. }
  10340. if (importOptions.isPlugin) {
  10341. context.mime = 'application/javascript';
  10342. if (context.syncImport) {
  10343. loadedFile = pluginLoader.loadPluginSync(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  10344. }
  10345. else {
  10346. promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  10347. }
  10348. }
  10349. else {
  10350. if (context.syncImport) {
  10351. loadedFile = fileManager.loadFileSync(path, currentFileInfo.currentDirectory, context, environment);
  10352. }
  10353. else {
  10354. promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
  10355. if (err) {
  10356. fileParsedFunc(err);
  10357. }
  10358. else {
  10359. loadFileCallback(loadedFile);
  10360. }
  10361. });
  10362. }
  10363. }
  10364. if (loadedFile) {
  10365. if (!loadedFile.filename) {
  10366. fileParsedFunc(loadedFile);
  10367. }
  10368. else {
  10369. loadFileCallback(loadedFile);
  10370. }
  10371. }
  10372. else if (promise) {
  10373. promise.then(loadFileCallback, fileParsedFunc);
  10374. }
  10375. };
  10376. return ImportManager;
  10377. }());
  10378. return ImportManager;
  10379. }
  10380. function Parse (environment, ParseTree, ImportManager) {
  10381. var parse = function (input, options, callback) {
  10382. if (typeof options === 'function') {
  10383. callback = options;
  10384. options = copyOptions(this.options, {});
  10385. }
  10386. else {
  10387. options = copyOptions(this.options, options || {});
  10388. }
  10389. if (!callback) {
  10390. var self_1 = this;
  10391. return new Promise(function (resolve, reject) {
  10392. parse.call(self_1, input, options, function (err, output) {
  10393. if (err) {
  10394. reject(err);
  10395. }
  10396. else {
  10397. resolve(output);
  10398. }
  10399. });
  10400. });
  10401. }
  10402. else {
  10403. var context_1;
  10404. var rootFileInfo = void 0;
  10405. var pluginManager_1 = new PluginManagerFactory(this, !options.reUsePluginManager);
  10406. options.pluginManager = pluginManager_1;
  10407. context_1 = new contexts.Parse(options);
  10408. if (options.rootFileInfo) {
  10409. rootFileInfo = options.rootFileInfo;
  10410. }
  10411. else {
  10412. var filename = options.filename || 'input';
  10413. var entryPath = filename.replace(/[^\/\\]*$/, '');
  10414. rootFileInfo = {
  10415. filename: filename,
  10416. rewriteUrls: context_1.rewriteUrls,
  10417. rootpath: context_1.rootpath || '',
  10418. currentDirectory: entryPath,
  10419. entryPath: entryPath,
  10420. rootFilename: filename
  10421. };
  10422. // add in a missing trailing slash
  10423. if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
  10424. rootFileInfo.rootpath += '/';
  10425. }
  10426. }
  10427. var imports_1 = new ImportManager(this, context_1, rootFileInfo);
  10428. this.importManager = imports_1;
  10429. // TODO: allow the plugins to be just a list of paths or names
  10430. // Do an async plugin queue like lessc
  10431. if (options.plugins) {
  10432. options.plugins.forEach(function (plugin) {
  10433. var evalResult, contents;
  10434. if (plugin.fileContent) {
  10435. contents = plugin.fileContent.replace(/^\uFEFF/, '');
  10436. evalResult = pluginManager_1.Loader.evalPlugin(contents, context_1, imports_1, plugin.options, plugin.filename);
  10437. if (evalResult instanceof LessError) {
  10438. return callback(evalResult);
  10439. }
  10440. }
  10441. else {
  10442. pluginManager_1.addPlugin(plugin);
  10443. }
  10444. });
  10445. }
  10446. new Parser(context_1, imports_1, rootFileInfo)
  10447. .parse(input, function (e, root) {
  10448. if (e) {
  10449. return callback(e);
  10450. }
  10451. callback(null, root, imports_1, options);
  10452. }, options);
  10453. }
  10454. };
  10455. return parse;
  10456. }
  10457. function Render (environment, ParseTree, ImportManager) {
  10458. var render = function (input, options, callback) {
  10459. if (typeof options === 'function') {
  10460. callback = options;
  10461. options = copyOptions(this.options, {});
  10462. }
  10463. else {
  10464. options = copyOptions(this.options, options || {});
  10465. }
  10466. if (!callback) {
  10467. var self_1 = this;
  10468. return new Promise(function (resolve, reject) {
  10469. render.call(self_1, input, options, function (err, output) {
  10470. if (err) {
  10471. reject(err);
  10472. }
  10473. else {
  10474. resolve(output);
  10475. }
  10476. });
  10477. });
  10478. }
  10479. else {
  10480. this.parse(input, options, function (err, root, imports, options) {
  10481. if (err) {
  10482. return callback(err);
  10483. }
  10484. var result;
  10485. try {
  10486. var parseTree = new ParseTree(root, imports);
  10487. result = parseTree.toCSS(options);
  10488. }
  10489. catch (err) {
  10490. return callback(err);
  10491. }
  10492. callback(null, result);
  10493. });
  10494. }
  10495. };
  10496. return render;
  10497. }
  10498. var version = "4.1.3";
  10499. function parseNodeVersion(version) {
  10500. var match = version.match(/^v(\d{1,2})\.(\d{1,2})\.(\d{1,2})(?:-([0-9A-Za-z-.]+))?(?:\+([0-9A-Za-z-.]+))?$/); // eslint-disable-line max-len
  10501. if (!match) {
  10502. throw new Error('Unable to parse: ' + version);
  10503. }
  10504. var res = {
  10505. major: parseInt(match[1], 10),
  10506. minor: parseInt(match[2], 10),
  10507. patch: parseInt(match[3], 10),
  10508. pre: match[4] || '',
  10509. build: match[5] || '',
  10510. };
  10511. return res;
  10512. }
  10513. var parseNodeVersion_1 = parseNodeVersion;
  10514. function lessRoot (environment, fileManagers) {
  10515. var sourceMapOutput, sourceMapBuilder, parseTree, importManager;
  10516. environment = new Environment(environment, fileManagers);
  10517. sourceMapOutput = SourceMapOutput(environment);
  10518. sourceMapBuilder = SourceMapBuilder(sourceMapOutput, environment);
  10519. parseTree = ParseTree(sourceMapBuilder);
  10520. importManager = ImportManager(environment);
  10521. var render = Render(environment, parseTree);
  10522. var parse = Parse(environment, parseTree, importManager);
  10523. var v = parseNodeVersion_1("v" + version);
  10524. var initial = {
  10525. version: [v.major, v.minor, v.patch],
  10526. data: data,
  10527. tree: tree,
  10528. Environment: Environment,
  10529. AbstractFileManager: AbstractFileManager,
  10530. AbstractPluginLoader: AbstractPluginLoader,
  10531. environment: environment,
  10532. visitors: visitors,
  10533. Parser: Parser,
  10534. functions: functions(environment),
  10535. contexts: contexts,
  10536. SourceMapOutput: sourceMapOutput,
  10537. SourceMapBuilder: sourceMapBuilder,
  10538. ParseTree: parseTree,
  10539. ImportManager: importManager,
  10540. render: render,
  10541. parse: parse,
  10542. LessError: LessError,
  10543. transformTree: transformTree,
  10544. utils: utils,
  10545. PluginManager: PluginManagerFactory,
  10546. logger: logger$1
  10547. };
  10548. // Create a public API
  10549. var ctor = function (t) {
  10550. return function () {
  10551. var obj = Object.create(t.prototype);
  10552. t.apply(obj, Array.prototype.slice.call(arguments, 0));
  10553. return obj;
  10554. };
  10555. };
  10556. var t;
  10557. var api = Object.create(initial);
  10558. for (var n in initial.tree) {
  10559. /* eslint guard-for-in: 0 */
  10560. t = initial.tree[n];
  10561. if (typeof t === 'function') {
  10562. api[n.toLowerCase()] = ctor(t);
  10563. }
  10564. else {
  10565. api[n] = Object.create(null);
  10566. for (var o in t) {
  10567. /* eslint guard-for-in: 0 */
  10568. api[n][o.toLowerCase()] = ctor(t[o]);
  10569. }
  10570. }
  10571. }
  10572. /**
  10573. * Some of the functions assume a `this` context of the API object,
  10574. * which causes it to fail when wrapped for ES6 imports.
  10575. *
  10576. * An assumed `this` should be removed in the future.
  10577. */
  10578. initial.parse = initial.parse.bind(api);
  10579. initial.render = initial.render.bind(api);
  10580. return api;
  10581. }
  10582. /* global window, XMLHttpRequest */
  10583. var options$1;
  10584. var logger;
  10585. var fileCache = {};
  10586. // TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load
  10587. var FileManager = function () { };
  10588. FileManager.prototype = Object.assign(new AbstractFileManager(), {
  10589. alwaysMakePathsAbsolute: function () {
  10590. return true;
  10591. },
  10592. join: function (basePath, laterPath) {
  10593. if (!basePath) {
  10594. return laterPath;
  10595. }
  10596. return this.extractUrlParts(laterPath, basePath).path;
  10597. },
  10598. doXHR: function (url, type, callback, errback) {
  10599. var xhr = new XMLHttpRequest();
  10600. var async = options$1.isFileProtocol ? options$1.fileAsync : true;
  10601. if (typeof xhr.overrideMimeType === 'function') {
  10602. xhr.overrideMimeType('text/css');
  10603. }
  10604. logger.debug("XHR: Getting '" + url + "'");
  10605. xhr.open('GET', url, async);
  10606. xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
  10607. xhr.send(null);
  10608. function handleResponse(xhr, callback, errback) {
  10609. if (xhr.status >= 200 && xhr.status < 300) {
  10610. callback(xhr.responseText, xhr.getResponseHeader('Last-Modified'));
  10611. }
  10612. else if (typeof errback === 'function') {
  10613. errback(xhr.status, url);
  10614. }
  10615. }
  10616. if (options$1.isFileProtocol && !options$1.fileAsync) {
  10617. if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
  10618. callback(xhr.responseText);
  10619. }
  10620. else {
  10621. errback(xhr.status, url);
  10622. }
  10623. }
  10624. else if (async) {
  10625. xhr.onreadystatechange = function () {
  10626. if (xhr.readyState == 4) {
  10627. handleResponse(xhr, callback, errback);
  10628. }
  10629. };
  10630. }
  10631. else {
  10632. handleResponse(xhr, callback, errback);
  10633. }
  10634. },
  10635. supports: function () {
  10636. return true;
  10637. },
  10638. clearFileCache: function () {
  10639. fileCache = {};
  10640. },
  10641. loadFile: function (filename, currentDirectory, options, environment) {
  10642. // TODO: Add prefix support like less-node?
  10643. // What about multiple paths?
  10644. if (currentDirectory && !this.isPathAbsolute(filename)) {
  10645. filename = currentDirectory + filename;
  10646. }
  10647. filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename;
  10648. options = options || {};
  10649. // sheet may be set to the stylesheet for the initial load or a collection of properties including
  10650. // some context variables for imports
  10651. var hrefParts = this.extractUrlParts(filename, window.location.href);
  10652. var href = hrefParts.url;
  10653. var self = this;
  10654. return new Promise(function (resolve, reject) {
  10655. if (options.useFileCache && fileCache[href]) {
  10656. try {
  10657. var lessText = fileCache[href];
  10658. return resolve({ contents: lessText, filename: href, webInfo: { lastModified: new Date() } });
  10659. }
  10660. catch (e) {
  10661. return reject({ filename: href, message: "Error loading file " + href + " error was " + e.message });
  10662. }
  10663. }
  10664. self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
  10665. // per file cache
  10666. fileCache[href] = data;
  10667. // Use remote copy (re-parse)
  10668. resolve({ contents: data, filename: href, webInfo: { lastModified: lastModified } });
  10669. }, function doXHRError(status, url) {
  10670. reject({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")", href: href });
  10671. });
  10672. });
  10673. }
  10674. });
  10675. var FM = (function (opts, log) {
  10676. options$1 = opts;
  10677. logger = log;
  10678. return FileManager;
  10679. });
  10680. // TODO: Add tests for browser @plugin
  10681. /**
  10682. * Browser Plugin Loader
  10683. */
  10684. var PluginLoader = function (less) {
  10685. this.less = less;
  10686. // Should we shim this.require for browser? Probably not?
  10687. };
  10688. PluginLoader.prototype = Object.assign(new AbstractPluginLoader(), {
  10689. loadPlugin: function (filename, basePath, context, environment, fileManager) {
  10690. return new Promise(function (fulfill, reject) {
  10691. fileManager.loadFile(filename, basePath, context, environment)
  10692. .then(fulfill).catch(reject);
  10693. });
  10694. }
  10695. });
  10696. var LogListener = (function (less, options) {
  10697. var logLevel_debug = 4;
  10698. var logLevel_info = 3;
  10699. var logLevel_warn = 2;
  10700. var logLevel_error = 1;
  10701. // The amount of logging in the javascript console.
  10702. // 3 - Debug, information and errors
  10703. // 2 - Information and errors
  10704. // 1 - Errors
  10705. // 0 - None
  10706. // Defaults to 2
  10707. options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
  10708. if (!options.loggers) {
  10709. options.loggers = [{
  10710. debug: function (msg) {
  10711. if (options.logLevel >= logLevel_debug) {
  10712. console.log(msg);
  10713. }
  10714. },
  10715. info: function (msg) {
  10716. if (options.logLevel >= logLevel_info) {
  10717. console.log(msg);
  10718. }
  10719. },
  10720. warn: function (msg) {
  10721. if (options.logLevel >= logLevel_warn) {
  10722. console.warn(msg);
  10723. }
  10724. },
  10725. error: function (msg) {
  10726. if (options.logLevel >= logLevel_error) {
  10727. console.error(msg);
  10728. }
  10729. }
  10730. }];
  10731. }
  10732. for (var i = 0; i < options.loggers.length; i++) {
  10733. less.logger.addListener(options.loggers[i]);
  10734. }
  10735. });
  10736. var ErrorReporting = (function (window, less, options) {
  10737. function errorHTML(e, rootHref) {
  10738. var id = "less-error-message:" + extractId(rootHref || '');
  10739. var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
  10740. var elem = window.document.createElement('div');
  10741. var timer;
  10742. var content;
  10743. var errors = [];
  10744. var filename = e.filename || rootHref;
  10745. var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
  10746. elem.id = id;
  10747. elem.className = 'less-error-message';
  10748. content = "<h3>" + (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') +
  10749. ("</h3><p>in <a href=\"" + filename + "\">" + filenameNoPath + "</a> ");
  10750. var errorline = function (e, i, classname) {
  10751. if (e.extract[i] !== undefined) {
  10752. errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
  10753. .replace(/\{class\}/, classname)
  10754. .replace(/\{content\}/, e.extract[i]));
  10755. }
  10756. };
  10757. if (e.line) {
  10758. errorline(e, 0, '');
  10759. errorline(e, 1, 'line');
  10760. errorline(e, 2, '');
  10761. content += "on line " + e.line + ", column " + (e.column + 1) + ":</p><ul>" + errors.join('') + "</ul>";
  10762. }
  10763. if (e.stack && (e.extract || options.logLevel >= 4)) {
  10764. content += "<br/>Stack Trace</br />" + e.stack.split('\n').slice(1).join('<br/>');
  10765. }
  10766. elem.innerHTML = content;
  10767. // CSS for error messages
  10768. browser.createCSS(window.document, [
  10769. '.less-error-message ul, .less-error-message li {',
  10770. 'list-style-type: none;',
  10771. 'margin-right: 15px;',
  10772. 'padding: 4px 0;',
  10773. 'margin: 0;',
  10774. '}',
  10775. '.less-error-message label {',
  10776. 'font-size: 12px;',
  10777. 'margin-right: 15px;',
  10778. 'padding: 4px 0;',
  10779. 'color: #cc7777;',
  10780. '}',
  10781. '.less-error-message pre {',
  10782. 'color: #dd6666;',
  10783. 'padding: 4px 0;',
  10784. 'margin: 0;',
  10785. 'display: inline-block;',
  10786. '}',
  10787. '.less-error-message pre.line {',
  10788. 'color: #ff0000;',
  10789. '}',
  10790. '.less-error-message h3 {',
  10791. 'font-size: 20px;',
  10792. 'font-weight: bold;',
  10793. 'padding: 15px 0 5px 0;',
  10794. 'margin: 0;',
  10795. '}',
  10796. '.less-error-message a {',
  10797. 'color: #10a',
  10798. '}',
  10799. '.less-error-message .error {',
  10800. 'color: red;',
  10801. 'font-weight: bold;',
  10802. 'padding-bottom: 2px;',
  10803. 'border-bottom: 1px dashed red;',
  10804. '}'
  10805. ].join('\n'), { title: 'error-message' });
  10806. elem.style.cssText = [
  10807. 'font-family: Arial, sans-serif',
  10808. 'border: 1px solid #e00',
  10809. 'background-color: #eee',
  10810. 'border-radius: 5px',
  10811. '-webkit-border-radius: 5px',
  10812. '-moz-border-radius: 5px',
  10813. 'color: #e00',
  10814. 'padding: 15px',
  10815. 'margin-bottom: 15px'
  10816. ].join(';');
  10817. if (options.env === 'development') {
  10818. timer = setInterval(function () {
  10819. var document = window.document;
  10820. var body = document.body;
  10821. if (body) {
  10822. if (document.getElementById(id)) {
  10823. body.replaceChild(elem, document.getElementById(id));
  10824. }
  10825. else {
  10826. body.insertBefore(elem, body.firstChild);
  10827. }
  10828. clearInterval(timer);
  10829. }
  10830. }, 10);
  10831. }
  10832. }
  10833. function removeErrorHTML(path) {
  10834. var node = window.document.getElementById("less-error-message:" + extractId(path));
  10835. if (node) {
  10836. node.parentNode.removeChild(node);
  10837. }
  10838. }
  10839. function removeError(path) {
  10840. if (!options.errorReporting || options.errorReporting === 'html') {
  10841. removeErrorHTML(path);
  10842. }
  10843. else if (options.errorReporting === 'console') ;
  10844. else if (typeof options.errorReporting === 'function') {
  10845. options.errorReporting('remove', path);
  10846. }
  10847. }
  10848. function errorConsole(e, rootHref) {
  10849. var template = '{line} {content}';
  10850. var filename = e.filename || rootHref;
  10851. var errors = [];
  10852. var content = (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') + " in " + filename;
  10853. var errorline = function (e, i, classname) {
  10854. if (e.extract[i] !== undefined) {
  10855. errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
  10856. .replace(/\{class\}/, classname)
  10857. .replace(/\{content\}/, e.extract[i]));
  10858. }
  10859. };
  10860. if (e.line) {
  10861. errorline(e, 0, '');
  10862. errorline(e, 1, 'line');
  10863. errorline(e, 2, '');
  10864. content += " on line " + e.line + ", column " + (e.column + 1) + ":\n" + errors.join('\n');
  10865. }
  10866. if (e.stack && (e.extract || options.logLevel >= 4)) {
  10867. content += "\nStack Trace\n" + e.stack;
  10868. }
  10869. less.logger.error(content);
  10870. }
  10871. function error(e, rootHref) {
  10872. if (!options.errorReporting || options.errorReporting === 'html') {
  10873. errorHTML(e, rootHref);
  10874. }
  10875. else if (options.errorReporting === 'console') {
  10876. errorConsole(e, rootHref);
  10877. }
  10878. else if (typeof options.errorReporting === 'function') {
  10879. options.errorReporting('add', e, rootHref);
  10880. }
  10881. }
  10882. return {
  10883. add: error,
  10884. remove: removeError
  10885. };
  10886. });
  10887. // Cache system is a bit outdated and could do with work
  10888. var Cache = (function (window, options, logger) {
  10889. var cache = null;
  10890. if (options.env !== 'development') {
  10891. try {
  10892. cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
  10893. }
  10894. catch (_) { }
  10895. }
  10896. return {
  10897. setCSS: function (path, lastModified, modifyVars, styles) {
  10898. if (cache) {
  10899. logger.info("saving " + path + " to cache.");
  10900. try {
  10901. cache.setItem(path, styles);
  10902. cache.setItem(path + ":timestamp", lastModified);
  10903. if (modifyVars) {
  10904. cache.setItem(path + ":vars", JSON.stringify(modifyVars));
  10905. }
  10906. }
  10907. catch (e) {
  10908. // TODO - could do with adding more robust error handling
  10909. logger.error("failed to save \"" + path + "\" to local storage for caching.");
  10910. }
  10911. }
  10912. },
  10913. getCSS: function (path, webInfo, modifyVars) {
  10914. var css = cache && cache.getItem(path);
  10915. var timestamp = cache && cache.getItem(path + ":timestamp");
  10916. var vars = cache && cache.getItem(path + ":vars");
  10917. modifyVars = modifyVars || {};
  10918. vars = vars || "{}"; // if not set, treat as the JSON representation of an empty object
  10919. if (timestamp && webInfo.lastModified &&
  10920. (new Date(webInfo.lastModified).valueOf() ===
  10921. new Date(timestamp).valueOf()) &&
  10922. JSON.stringify(modifyVars) === vars) {
  10923. // Use local copy
  10924. return css;
  10925. }
  10926. }
  10927. };
  10928. });
  10929. var ImageSize = (function () {
  10930. function imageSize() {
  10931. throw {
  10932. type: 'Runtime',
  10933. message: 'Image size functions are not supported in browser version of less'
  10934. };
  10935. }
  10936. var imageFunctions = {
  10937. 'image-size': function (filePathNode) {
  10938. imageSize();
  10939. return -1;
  10940. },
  10941. 'image-width': function (filePathNode) {
  10942. imageSize();
  10943. return -1;
  10944. },
  10945. 'image-height': function (filePathNode) {
  10946. imageSize();
  10947. return -1;
  10948. }
  10949. };
  10950. functionRegistry.addMultiple(imageFunctions);
  10951. });
  10952. //
  10953. var root = (function (window, options) {
  10954. var document = window.document;
  10955. var less = lessRoot();
  10956. less.options = options;
  10957. var environment = less.environment;
  10958. var FileManager = FM(options, less.logger);
  10959. var fileManager = new FileManager();
  10960. environment.addFileManager(fileManager);
  10961. less.FileManager = FileManager;
  10962. less.PluginLoader = PluginLoader;
  10963. LogListener(less, options);
  10964. var errors = ErrorReporting(window, less, options);
  10965. var cache = less.cache = options.cache || Cache(window, options, less.logger);
  10966. ImageSize(less.environment);
  10967. // Setup user functions - Deprecate?
  10968. if (options.functions) {
  10969. less.functions.functionRegistry.addMultiple(options.functions);
  10970. }
  10971. var typePattern = /^text\/(x-)?less$/;
  10972. function clone(obj) {
  10973. var cloned = {};
  10974. for (var prop in obj) {
  10975. if (obj.hasOwnProperty(prop)) {
  10976. cloned[prop] = obj[prop];
  10977. }
  10978. }
  10979. return cloned;
  10980. }
  10981. // only really needed for phantom
  10982. function bind(func, thisArg) {
  10983. var curryArgs = Array.prototype.slice.call(arguments, 2);
  10984. return function () {
  10985. var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
  10986. return func.apply(thisArg, args);
  10987. };
  10988. }
  10989. function loadStyles(modifyVars) {
  10990. var styles = document.getElementsByTagName('style');
  10991. var style;
  10992. for (var i = 0; i < styles.length; i++) {
  10993. style = styles[i];
  10994. if (style.type.match(typePattern)) {
  10995. var instanceOptions = clone(options);
  10996. instanceOptions.modifyVars = modifyVars;
  10997. var lessText = style.innerHTML || '';
  10998. instanceOptions.filename = document.location.href.replace(/#.*$/, '');
  10999. /* jshint loopfunc:true */
  11000. // use closure to store current style
  11001. less.render(lessText, instanceOptions, bind(function (style, e, result) {
  11002. if (e) {
  11003. errors.add(e, 'inline');
  11004. }
  11005. else {
  11006. style.type = 'text/css';
  11007. if (style.styleSheet) {
  11008. style.styleSheet.cssText = result.css;
  11009. }
  11010. else {
  11011. style.innerHTML = result.css;
  11012. }
  11013. }
  11014. }, null, style));
  11015. }
  11016. }
  11017. }
  11018. function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
  11019. var instanceOptions = clone(options);
  11020. addDataAttr(instanceOptions, sheet);
  11021. instanceOptions.mime = sheet.type;
  11022. if (modifyVars) {
  11023. instanceOptions.modifyVars = modifyVars;
  11024. }
  11025. function loadInitialFileCallback(loadedFile) {
  11026. var data = loadedFile.contents;
  11027. var path = loadedFile.filename;
  11028. var webInfo = loadedFile.webInfo;
  11029. var newFileInfo = {
  11030. currentDirectory: fileManager.getPath(path),
  11031. filename: path,
  11032. rootFilename: path,
  11033. rewriteUrls: instanceOptions.rewriteUrls
  11034. };
  11035. newFileInfo.entryPath = newFileInfo.currentDirectory;
  11036. newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
  11037. if (webInfo) {
  11038. webInfo.remaining = remaining;
  11039. var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
  11040. if (!reload && css) {
  11041. webInfo.local = true;
  11042. callback(null, css, data, sheet, webInfo, path);
  11043. return;
  11044. }
  11045. }
  11046. // TODO add tests around how this behaves when reloading
  11047. errors.remove(path);
  11048. instanceOptions.rootFileInfo = newFileInfo;
  11049. less.render(data, instanceOptions, function (e, result) {
  11050. if (e) {
  11051. e.href = path;
  11052. callback(e);
  11053. }
  11054. else {
  11055. cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
  11056. callback(null, result.css, data, sheet, webInfo, path);
  11057. }
  11058. });
  11059. }
  11060. fileManager.loadFile(sheet.href, null, instanceOptions, environment)
  11061. .then(function (loadedFile) {
  11062. loadInitialFileCallback(loadedFile);
  11063. }).catch(function (err) {
  11064. console.log(err);
  11065. callback(err);
  11066. });
  11067. }
  11068. function loadStyleSheets(callback, reload, modifyVars) {
  11069. for (var i = 0; i < less.sheets.length; i++) {
  11070. loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
  11071. }
  11072. }
  11073. function initRunningMode() {
  11074. if (less.env === 'development') {
  11075. less.watchTimer = setInterval(function () {
  11076. if (less.watchMode) {
  11077. fileManager.clearFileCache();
  11078. loadStyleSheets(function (e, css, _, sheet, webInfo) {
  11079. if (e) {
  11080. errors.add(e, e.href || sheet.href);
  11081. }
  11082. else if (css) {
  11083. browser.createCSS(window.document, css, sheet);
  11084. }
  11085. });
  11086. }
  11087. }, options.poll);
  11088. }
  11089. }
  11090. //
  11091. // Watch mode
  11092. //
  11093. less.watch = function () {
  11094. if (!less.watchMode) {
  11095. less.env = 'development';
  11096. initRunningMode();
  11097. }
  11098. this.watchMode = true;
  11099. return true;
  11100. };
  11101. less.unwatch = function () { clearInterval(less.watchTimer); this.watchMode = false; return false; };
  11102. //
  11103. // Synchronously get all <link> tags with the 'rel' attribute set to
  11104. // "stylesheet/less".
  11105. //
  11106. less.registerStylesheetsImmediately = function () {
  11107. var links = document.getElementsByTagName('link');
  11108. less.sheets = [];
  11109. for (var i = 0; i < links.length; i++) {
  11110. if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
  11111. (links[i].type.match(typePattern)))) {
  11112. less.sheets.push(links[i]);
  11113. }
  11114. }
  11115. };
  11116. //
  11117. // Asynchronously get all <link> tags with the 'rel' attribute set to
  11118. // "stylesheet/less", returning a Promise.
  11119. //
  11120. less.registerStylesheets = function () { return new Promise(function (resolve, reject) {
  11121. less.registerStylesheetsImmediately();
  11122. resolve();
  11123. }); };
  11124. //
  11125. // With this function, it's possible to alter variables and re-render
  11126. // CSS without reloading less-files
  11127. //
  11128. less.modifyVars = function (record) { return less.refresh(true, record, false); };
  11129. less.refresh = function (reload, modifyVars, clearFileCache) {
  11130. if ((reload || clearFileCache) && clearFileCache !== false) {
  11131. fileManager.clearFileCache();
  11132. }
  11133. return new Promise(function (resolve, reject) {
  11134. var startTime;
  11135. var endTime;
  11136. var totalMilliseconds;
  11137. var remainingSheets;
  11138. startTime = endTime = new Date();
  11139. // Set counter for remaining unprocessed sheets
  11140. remainingSheets = less.sheets.length;
  11141. if (remainingSheets === 0) {
  11142. endTime = new Date();
  11143. totalMilliseconds = endTime - startTime;
  11144. less.logger.info('Less has finished and no sheets were loaded.');
  11145. resolve({
  11146. startTime: startTime,
  11147. endTime: endTime,
  11148. totalMilliseconds: totalMilliseconds,
  11149. sheets: less.sheets.length
  11150. });
  11151. }
  11152. else {
  11153. // Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
  11154. loadStyleSheets(function (e, css, _, sheet, webInfo) {
  11155. if (e) {
  11156. errors.add(e, e.href || sheet.href);
  11157. reject(e);
  11158. return;
  11159. }
  11160. if (webInfo.local) {
  11161. less.logger.info("Loading " + sheet.href + " from cache.");
  11162. }
  11163. else {
  11164. less.logger.info("Rendered " + sheet.href + " successfully.");
  11165. }
  11166. browser.createCSS(window.document, css, sheet);
  11167. less.logger.info("CSS for " + sheet.href + " generated in " + (new Date() - endTime) + "ms");
  11168. // Count completed sheet
  11169. remainingSheets--;
  11170. // Check if the last remaining sheet was processed and then call the promise
  11171. if (remainingSheets === 0) {
  11172. totalMilliseconds = new Date() - startTime;
  11173. less.logger.info("Less has finished. CSS generated in " + totalMilliseconds + "ms");
  11174. resolve({
  11175. startTime: startTime,
  11176. endTime: endTime,
  11177. totalMilliseconds: totalMilliseconds,
  11178. sheets: less.sheets.length
  11179. });
  11180. }
  11181. endTime = new Date();
  11182. }, reload, modifyVars);
  11183. }
  11184. loadStyles(modifyVars);
  11185. });
  11186. };
  11187. less.refreshStyles = loadStyles;
  11188. return less;
  11189. });
  11190. /**
  11191. * Kicks off less and compiles any stylesheets
  11192. * used in the browser distributed version of less
  11193. * to kick-start less using the browser api
  11194. */
  11195. var options = defaultOptions();
  11196. if (window.less) {
  11197. for (var key in window.less) {
  11198. if (window.less.hasOwnProperty(key)) {
  11199. options[key] = window.less[key];
  11200. }
  11201. }
  11202. }
  11203. addDefaultOptions(window, options);
  11204. options.plugins = options.plugins || [];
  11205. if (window.LESS_PLUGINS) {
  11206. options.plugins = options.plugins.concat(window.LESS_PLUGINS);
  11207. }
  11208. var less = root(window, options);
  11209. window.less = less;
  11210. var css;
  11211. var head;
  11212. var style;
  11213. // Always restore page visibility
  11214. function resolveOrReject(data) {
  11215. if (data.filename) {
  11216. console.warn(data);
  11217. }
  11218. if (!options.async) {
  11219. head.removeChild(style);
  11220. }
  11221. }
  11222. if (options.onReady) {
  11223. if (/!watch/.test(window.location.hash)) {
  11224. less.watch();
  11225. }
  11226. // Simulate synchronous stylesheet loading by hiding page rendering
  11227. if (!options.async) {
  11228. css = 'body { display: none !important }';
  11229. head = document.head || document.getElementsByTagName('head')[0];
  11230. style = document.createElement('style');
  11231. style.type = 'text/css';
  11232. if (style.styleSheet) {
  11233. style.styleSheet.cssText = css;
  11234. }
  11235. else {
  11236. style.appendChild(document.createTextNode(css));
  11237. }
  11238. head.appendChild(style);
  11239. }
  11240. less.registerStylesheetsImmediately();
  11241. less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
  11242. }
  11243. return less;
  11244. })));