less-node.cjs 481 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066
  1. /**
  2. * Less - Leaner CSS v4.6.4
  3. * http://lesscss.org
  4. *
  5. * Copyright (c) 2009-2026, Alexis Sellier <self@cloudhead.net>
  6. * Licensed under the Apache-2.0 License.
  7. *
  8. * @license Apache-2.0
  9. */
  10. 'use strict';
  11. var path = require('path');
  12. var nodeFs = require('fs');
  13. var url = require('url');
  14. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  15. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  16. var nodeFs__default = /*#__PURE__*/_interopDefaultLegacy(nodeFs);
  17. var url__default = /*#__PURE__*/_interopDefaultLegacy(url);
  18. function createRequire() { return require; }
  19. const require$6 = createRequire();
  20. class SourceMapGeneratorFallback {
  21. addMapping(){}
  22. setSourceContent(){}
  23. toJSON(){
  24. return null;
  25. }
  26. }
  27. var environment = {
  28. encodeBase64: function encodeBase64(str) {
  29. // Avoid Buffer constructor on newer versions of Node.js.
  30. const buffer = (Buffer.from ? Buffer.from(str) : (new Buffer(str)));
  31. return buffer.toString('base64');
  32. },
  33. mimeLookup: function (filename) {
  34. try {
  35. const mimeModule = require$6('mime');
  36. return mimeModule ? mimeModule.lookup(filename) : "application/octet-stream";
  37. } catch (e) {
  38. return "application/octet-stream";
  39. }
  40. },
  41. charsetLookup: function (mime) {
  42. try {
  43. const mimeModule = require$6('mime');
  44. return mimeModule ? mimeModule.charsets.lookup(mime) : undefined;
  45. } catch (e) {
  46. return undefined;
  47. }
  48. },
  49. getSourceMapGenerator: function getSourceMapGenerator() {
  50. try {
  51. const sourceMapModule = require$6('source-map');
  52. return sourceMapModule ? sourceMapModule.SourceMapGenerator : SourceMapGeneratorFallback;
  53. } catch (e) {
  54. return SourceMapGeneratorFallback;
  55. }
  56. }
  57. };
  58. /** @typedef {import('fs')} FS */
  59. const require$5 = createRequire();
  60. /** @type {FS} */
  61. let fs;
  62. try {
  63. fs = require$5('graceful-fs');
  64. } catch (e) {
  65. fs = nodeFs__default["default"];
  66. }
  67. var fs$1 = fs;
  68. class AbstractFileManager {
  69. getPath(filename) {
  70. let j = filename.lastIndexOf('?');
  71. if (j > 0) {
  72. filename = filename.slice(0, j);
  73. }
  74. j = filename.lastIndexOf('/');
  75. if (j < 0) {
  76. j = filename.lastIndexOf('\\');
  77. }
  78. if (j < 0) {
  79. return '';
  80. }
  81. return filename.slice(0, j + 1);
  82. }
  83. tryAppendExtension(path, ext) {
  84. return /(\.[a-z]*$)|([?;].*)$/.test(path) ? path : path + ext;
  85. }
  86. tryAppendLessExtension(path) {
  87. return this.tryAppendExtension(path, '.less');
  88. }
  89. supportsSync() {
  90. return false;
  91. }
  92. alwaysMakePathsAbsolute() {
  93. return false;
  94. }
  95. isPathAbsolute(filename) {
  96. return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
  97. }
  98. // TODO: pull out / replace?
  99. join(basePath, laterPath) {
  100. if (!basePath) {
  101. return laterPath;
  102. }
  103. return basePath + laterPath;
  104. }
  105. pathDiff(url, baseUrl) {
  106. // diff between two paths to create a relative path
  107. const urlParts = this.extractUrlParts(url);
  108. const baseUrlParts = this.extractUrlParts(baseUrl);
  109. let i;
  110. let max;
  111. let urlDirectories;
  112. let baseUrlDirectories;
  113. let diff = '';
  114. if (urlParts.hostPart !== baseUrlParts.hostPart) {
  115. return '';
  116. }
  117. max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
  118. for (i = 0; i < max; i++) {
  119. if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; }
  120. }
  121. baseUrlDirectories = baseUrlParts.directories.slice(i);
  122. urlDirectories = urlParts.directories.slice(i);
  123. for (i = 0; i < baseUrlDirectories.length - 1; i++) {
  124. diff += '../';
  125. }
  126. for (i = 0; i < urlDirectories.length - 1; i++) {
  127. diff += `${urlDirectories[i]}/`;
  128. }
  129. return diff;
  130. }
  131. /**
  132. * Helper function, not part of API.
  133. * This should be replaceable by newer Node / Browser APIs
  134. *
  135. * @param {string} url
  136. * @param {string} baseUrl
  137. */
  138. extractUrlParts(url, baseUrl) {
  139. // urlParts[1] = protocol://hostname/ OR /
  140. // urlParts[2] = / if path relative to host base
  141. // urlParts[3] = directories
  142. // urlParts[4] = filename
  143. // urlParts[5] = parameters
  144. const urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^/?#]*\/)|([/\\]))?((?:[^/\\?#]*[/\\])*)([^/\\?#]*)([#?].*)?$/i;
  145. const urlParts = url.match(urlPartsRegex);
  146. const returner = {};
  147. let rawDirectories = [];
  148. const directories = [];
  149. let i;
  150. let baseUrlParts;
  151. if (!urlParts) {
  152. throw new Error(`Could not parse sheet href - '${url}'`);
  153. }
  154. // Stylesheets in IE don't always return the full path
  155. if (baseUrl && (!urlParts[1] || urlParts[2])) {
  156. baseUrlParts = baseUrl.match(urlPartsRegex);
  157. if (!baseUrlParts) {
  158. throw new Error(`Could not parse page url - '${baseUrl}'`);
  159. }
  160. urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
  161. if (!urlParts[2]) {
  162. urlParts[3] = baseUrlParts[3] + urlParts[3];
  163. }
  164. }
  165. if (urlParts[3]) {
  166. rawDirectories = urlParts[3].replace(/\\/g, '/').split('/');
  167. // collapse '..' and skip '.'
  168. for (i = 0; i < rawDirectories.length; i++) {
  169. if (rawDirectories[i] === '..') {
  170. directories.pop();
  171. }
  172. else if (rawDirectories[i] !== '.') {
  173. directories.push(rawDirectories[i]);
  174. }
  175. }
  176. }
  177. returner.hostPart = urlParts[1];
  178. returner.directories = directories;
  179. returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
  180. returner.path = (urlParts[1] || '') + directories.join('/');
  181. returner.filename = urlParts[4];
  182. returner.fileUrl = returner.path + (urlParts[4] || '');
  183. returner.url = returner.fileUrl + (urlParts[5] || '');
  184. return returner;
  185. }
  186. }
  187. const require$4 = createRequire();
  188. const FileManager = function() {};
  189. FileManager.prototype = Object.assign(new AbstractFileManager(), {
  190. supports() {
  191. return true;
  192. },
  193. supportsSync() {
  194. return true;
  195. },
  196. loadFile(filename, currentDirectory, options, environment, callback) {
  197. let fullFilename;
  198. const isAbsoluteFilename = this.isPathAbsolute(filename);
  199. const filenamesTried = [];
  200. const self = this;
  201. const prefix = filename.slice(0, 1);
  202. const explicit = prefix === '.' || prefix === '/';
  203. let result = null;
  204. let isNodeModule = false;
  205. const npmPrefix = 'npm://';
  206. options = options || {};
  207. const paths = isAbsoluteFilename ? [''] : [currentDirectory];
  208. if (options.paths) { paths.push.apply(paths, options.paths); }
  209. if (!isAbsoluteFilename && paths.indexOf('.') === -1) { paths.push('.'); }
  210. const prefixes = options.prefixes || [''];
  211. const fileParts = this.extractUrlParts(filename);
  212. if (options.syncImport) {
  213. getFileData(returnData, returnData);
  214. if (callback) {
  215. callback(result.error, result);
  216. }
  217. else {
  218. return result;
  219. }
  220. }
  221. else {
  222. // promise is guaranteed to be asyncronous
  223. // which helps as it allows the file handle
  224. // to be closed before it continues with the next file
  225. return new Promise(getFileData);
  226. }
  227. function returnData(data) {
  228. if (!data.filename) {
  229. result = { error: data };
  230. }
  231. else {
  232. result = data;
  233. }
  234. }
  235. function getFileData(fulfill, reject) {
  236. (function tryPathIndex(i) {
  237. function tryWithExtension() {
  238. const extFilename = options.ext ? self.tryAppendExtension(fullFilename, options.ext) : fullFilename;
  239. if (extFilename !== fullFilename && !explicit && paths[i] === '.') {
  240. try {
  241. fullFilename = require$4.resolve(extFilename);
  242. isNodeModule = true;
  243. }
  244. catch (e) {
  245. filenamesTried.push(npmPrefix + extFilename);
  246. fullFilename = extFilename;
  247. }
  248. }
  249. else {
  250. fullFilename = extFilename;
  251. }
  252. }
  253. if (i < paths.length) {
  254. (function tryPrefix(j) {
  255. if (j < prefixes.length) {
  256. isNodeModule = false;
  257. fullFilename = fileParts.rawPath + prefixes[j] + fileParts.filename;
  258. if (paths[i]) {
  259. if (paths[i].startsWith('#')) {
  260. // Handling paths starting with '#'
  261. fullFilename = paths[i].substr(1) + fullFilename;
  262. }else {
  263. fullFilename = path__default["default"].join(paths[i], fullFilename);
  264. }
  265. }
  266. if (!explicit && paths[i] === '.') {
  267. try {
  268. fullFilename = require$4.resolve(fullFilename);
  269. isNodeModule = true;
  270. }
  271. catch (e) {
  272. filenamesTried.push(npmPrefix + fullFilename);
  273. tryWithExtension();
  274. }
  275. }
  276. else {
  277. tryWithExtension();
  278. }
  279. const readFileArgs = [fullFilename];
  280. if (!options.rawBuffer) {
  281. readFileArgs.push('utf-8');
  282. }
  283. if (options.syncImport) {
  284. try {
  285. const data = fs$1.readFileSync.apply(this, readFileArgs);
  286. fulfill({ contents: data, filename: fullFilename});
  287. }
  288. catch (e) {
  289. filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
  290. return tryPrefix(j + 1);
  291. }
  292. }
  293. else {
  294. readFileArgs.push(function(e, data) {
  295. if (e) {
  296. filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
  297. return tryPrefix(j + 1);
  298. }
  299. fulfill({ contents: data, filename: fullFilename});
  300. });
  301. fs$1.readFile.apply(this, readFileArgs);
  302. }
  303. }
  304. else {
  305. tryPathIndex(i + 1);
  306. }
  307. })(0);
  308. } else {
  309. reject({ type: 'File', message: `'${filename}' wasn't found. Tried - ${filenamesTried.join(',')}` });
  310. }
  311. }(0));
  312. }
  313. },
  314. loadFileSync(filename, currentDirectory, options, environment) {
  315. options.syncImport = true;
  316. return this.loadFile(filename, currentDirectory, options, environment);
  317. }
  318. });
  319. var logger = {
  320. error: function(msg) {
  321. this._fireEvent('error', msg);
  322. },
  323. warn: function(msg) {
  324. this._fireEvent('warn', msg);
  325. },
  326. info: function(msg) {
  327. this._fireEvent('info', msg);
  328. },
  329. debug: function(msg) {
  330. this._fireEvent('debug', msg);
  331. },
  332. addListener: function(listener) {
  333. this._listeners.push(listener);
  334. },
  335. removeListener: function(listener) {
  336. for (let i = 0; i < this._listeners.length; i++) {
  337. if (this._listeners[i] === listener) {
  338. this._listeners.splice(i, 1);
  339. return;
  340. }
  341. }
  342. },
  343. _fireEvent: function(type, msg) {
  344. for (let i = 0; i < this._listeners.length; i++) {
  345. const logFunction = this._listeners[i][type];
  346. if (logFunction) {
  347. logFunction(msg);
  348. }
  349. }
  350. },
  351. _listeners: []
  352. };
  353. /* eslint-disable no-unused-vars */
  354. const require$3 = createRequire();
  355. const isUrlRe = /^(?:https?:)?\/\//i;
  356. let request;
  357. const UrlFileManager = function() {};
  358. UrlFileManager.prototype = Object.assign(new AbstractFileManager(), {
  359. supports(filename, currentDirectory, options, environment) {
  360. return isUrlRe.test( filename ) || isUrlRe.test(currentDirectory);
  361. },
  362. loadFile(filename, currentDirectory, options, environment) {
  363. return new Promise((fulfill, reject) => {
  364. if (request === undefined) {
  365. try { request = require$3('needle'); }
  366. catch (e) { request = null; }
  367. }
  368. if (!request) {
  369. reject({ type: 'File', message: 'optional dependency \'needle\' required to import over http(s)\n' });
  370. return;
  371. }
  372. let urlStr = isUrlRe.test( filename ) ? filename : url__default["default"].resolve(currentDirectory, filename);
  373. /** native-request currently has a bug */
  374. const hackUrlStr = urlStr.indexOf('?') === -1 ? urlStr + '?' : urlStr;
  375. request.get(hackUrlStr, { follow_max: 5 }, (err, resp, body) => {
  376. if (err || resp && resp.statusCode >= 400) {
  377. const message = resp && resp.statusCode === 404
  378. ? `resource '${urlStr}' was not found\n`
  379. : `resource '${urlStr}' gave this Error:\n ${err || resp.statusMessage || resp.statusCode}\n`;
  380. reject({ type: 'File', message });
  381. return;
  382. }
  383. if (resp.statusCode >= 300) {
  384. reject({ type: 'File', message: `resource '${urlStr}' caused too many redirects` });
  385. return;
  386. }
  387. body = body.toString('utf8');
  388. if (!body) {
  389. logger.warn(`Warning: Empty body (HTTP ${resp.statusCode}) returned by "${urlStr}"`);
  390. }
  391. fulfill({ contents: body || '', filename: urlStr });
  392. });
  393. });
  394. }
  395. });
  396. /**
  397. * @todo Document why this abstraction exists, and the relationship between
  398. * environment, file managers, and plugin manager
  399. */
  400. class Environment {
  401. constructor(externalEnvironment, fileManagers) {
  402. this.fileManagers = fileManagers || [];
  403. externalEnvironment = externalEnvironment || {};
  404. const optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
  405. const requiredFunctions = [];
  406. const functions = requiredFunctions.concat(optionalFunctions);
  407. for (let i = 0; i < functions.length; i++) {
  408. const propName = functions[i];
  409. const environmentFunc = externalEnvironment[propName];
  410. if (environmentFunc) {
  411. this[propName] = environmentFunc.bind(externalEnvironment);
  412. } else if (i < requiredFunctions.length) {
  413. this.warn(`missing required function in environment - ${propName}`);
  414. }
  415. }
  416. }
  417. getFileManager(filename, currentDirectory, options, environment, isSync) {
  418. if (!filename) {
  419. logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
  420. }
  421. if (currentDirectory === undefined) {
  422. logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
  423. }
  424. let fileManagers = this.fileManagers;
  425. if (options.pluginManager) {
  426. fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
  427. }
  428. for (let i = fileManagers.length - 1; i >= 0 ; i--) {
  429. const fileManager = fileManagers[i];
  430. if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
  431. return fileManager;
  432. }
  433. }
  434. return null;
  435. }
  436. addFileManager(fileManager) {
  437. this.fileManagers.push(fileManager);
  438. }
  439. clearFileManagers() {
  440. this.fileManagers = [];
  441. }
  442. }
  443. var colors = {
  444. 'aliceblue':'#f0f8ff',
  445. 'antiquewhite':'#faebd7',
  446. 'aqua':'#00ffff',
  447. 'aquamarine':'#7fffd4',
  448. 'azure':'#f0ffff',
  449. 'beige':'#f5f5dc',
  450. 'bisque':'#ffe4c4',
  451. 'black':'#000000',
  452. 'blanchedalmond':'#ffebcd',
  453. 'blue':'#0000ff',
  454. 'blueviolet':'#8a2be2',
  455. 'brown':'#a52a2a',
  456. 'burlywood':'#deb887',
  457. 'cadetblue':'#5f9ea0',
  458. 'chartreuse':'#7fff00',
  459. 'chocolate':'#d2691e',
  460. 'coral':'#ff7f50',
  461. 'cornflowerblue':'#6495ed',
  462. 'cornsilk':'#fff8dc',
  463. 'crimson':'#dc143c',
  464. 'cyan':'#00ffff',
  465. 'darkblue':'#00008b',
  466. 'darkcyan':'#008b8b',
  467. 'darkgoldenrod':'#b8860b',
  468. 'darkgray':'#a9a9a9',
  469. 'darkgrey':'#a9a9a9',
  470. 'darkgreen':'#006400',
  471. 'darkkhaki':'#bdb76b',
  472. 'darkmagenta':'#8b008b',
  473. 'darkolivegreen':'#556b2f',
  474. 'darkorange':'#ff8c00',
  475. 'darkorchid':'#9932cc',
  476. 'darkred':'#8b0000',
  477. 'darksalmon':'#e9967a',
  478. 'darkseagreen':'#8fbc8f',
  479. 'darkslateblue':'#483d8b',
  480. 'darkslategray':'#2f4f4f',
  481. 'darkslategrey':'#2f4f4f',
  482. 'darkturquoise':'#00ced1',
  483. 'darkviolet':'#9400d3',
  484. 'deeppink':'#ff1493',
  485. 'deepskyblue':'#00bfff',
  486. 'dimgray':'#696969',
  487. 'dimgrey':'#696969',
  488. 'dodgerblue':'#1e90ff',
  489. 'firebrick':'#b22222',
  490. 'floralwhite':'#fffaf0',
  491. 'forestgreen':'#228b22',
  492. 'fuchsia':'#ff00ff',
  493. 'gainsboro':'#dcdcdc',
  494. 'ghostwhite':'#f8f8ff',
  495. 'gold':'#ffd700',
  496. 'goldenrod':'#daa520',
  497. 'gray':'#808080',
  498. 'grey':'#808080',
  499. 'green':'#008000',
  500. 'greenyellow':'#adff2f',
  501. 'honeydew':'#f0fff0',
  502. 'hotpink':'#ff69b4',
  503. 'indianred':'#cd5c5c',
  504. 'indigo':'#4b0082',
  505. 'ivory':'#fffff0',
  506. 'khaki':'#f0e68c',
  507. 'lavender':'#e6e6fa',
  508. 'lavenderblush':'#fff0f5',
  509. 'lawngreen':'#7cfc00',
  510. 'lemonchiffon':'#fffacd',
  511. 'lightblue':'#add8e6',
  512. 'lightcoral':'#f08080',
  513. 'lightcyan':'#e0ffff',
  514. 'lightgoldenrodyellow':'#fafad2',
  515. 'lightgray':'#d3d3d3',
  516. 'lightgrey':'#d3d3d3',
  517. 'lightgreen':'#90ee90',
  518. 'lightpink':'#ffb6c1',
  519. 'lightsalmon':'#ffa07a',
  520. 'lightseagreen':'#20b2aa',
  521. 'lightskyblue':'#87cefa',
  522. 'lightslategray':'#778899',
  523. 'lightslategrey':'#778899',
  524. 'lightsteelblue':'#b0c4de',
  525. 'lightyellow':'#ffffe0',
  526. 'lime':'#00ff00',
  527. 'limegreen':'#32cd32',
  528. 'linen':'#faf0e6',
  529. 'magenta':'#ff00ff',
  530. 'maroon':'#800000',
  531. 'mediumaquamarine':'#66cdaa',
  532. 'mediumblue':'#0000cd',
  533. 'mediumorchid':'#ba55d3',
  534. 'mediumpurple':'#9370d8',
  535. 'mediumseagreen':'#3cb371',
  536. 'mediumslateblue':'#7b68ee',
  537. 'mediumspringgreen':'#00fa9a',
  538. 'mediumturquoise':'#48d1cc',
  539. 'mediumvioletred':'#c71585',
  540. 'midnightblue':'#191970',
  541. 'mintcream':'#f5fffa',
  542. 'mistyrose':'#ffe4e1',
  543. 'moccasin':'#ffe4b5',
  544. 'navajowhite':'#ffdead',
  545. 'navy':'#000080',
  546. 'oldlace':'#fdf5e6',
  547. 'olive':'#808000',
  548. 'olivedrab':'#6b8e23',
  549. 'orange':'#ffa500',
  550. 'orangered':'#ff4500',
  551. 'orchid':'#da70d6',
  552. 'palegoldenrod':'#eee8aa',
  553. 'palegreen':'#98fb98',
  554. 'paleturquoise':'#afeeee',
  555. 'palevioletred':'#d87093',
  556. 'papayawhip':'#ffefd5',
  557. 'peachpuff':'#ffdab9',
  558. 'peru':'#cd853f',
  559. 'pink':'#ffc0cb',
  560. 'plum':'#dda0dd',
  561. 'powderblue':'#b0e0e6',
  562. 'purple':'#800080',
  563. 'rebeccapurple':'#663399',
  564. 'red':'#ff0000',
  565. 'rosybrown':'#bc8f8f',
  566. 'royalblue':'#4169e1',
  567. 'saddlebrown':'#8b4513',
  568. 'salmon':'#fa8072',
  569. 'sandybrown':'#f4a460',
  570. 'seagreen':'#2e8b57',
  571. 'seashell':'#fff5ee',
  572. 'sienna':'#a0522d',
  573. 'silver':'#c0c0c0',
  574. 'skyblue':'#87ceeb',
  575. 'slateblue':'#6a5acd',
  576. 'slategray':'#708090',
  577. 'slategrey':'#708090',
  578. 'snow':'#fffafa',
  579. 'springgreen':'#00ff7f',
  580. 'steelblue':'#4682b4',
  581. 'tan':'#d2b48c',
  582. 'teal':'#008080',
  583. 'thistle':'#d8bfd8',
  584. 'tomato':'#ff6347',
  585. 'turquoise':'#40e0d0',
  586. 'violet':'#ee82ee',
  587. 'wheat':'#f5deb3',
  588. 'white':'#ffffff',
  589. 'whitesmoke':'#f5f5f5',
  590. 'yellow':'#ffff00',
  591. 'yellowgreen':'#9acd32'
  592. };
  593. var unitConversions = {
  594. length: {
  595. 'm': 1,
  596. 'cm': 0.01,
  597. 'mm': 0.001,
  598. 'in': 0.0254,
  599. 'px': 0.0254 / 96,
  600. 'pt': 0.0254 / 72,
  601. 'pc': 0.0254 / 72 * 12
  602. },
  603. duration: {
  604. 's': 1,
  605. 'ms': 0.001
  606. },
  607. angle: {
  608. 'rad': 1 / (2 * Math.PI),
  609. 'deg': 1 / 360,
  610. 'grad': 1 / 400,
  611. 'turn': 1
  612. }
  613. };
  614. var data = { colors, unitConversions };
  615. // @ts-check
  616. /**
  617. * @typedef {object} FileInfo
  618. * @property {string} [filename]
  619. * @property {string} [rootpath]
  620. * @property {string} [currentDirectory]
  621. * @property {string} [rootFilename]
  622. * @property {string} [entryPath]
  623. * @property {boolean} [reference]
  624. */
  625. /**
  626. * @typedef {object} VisibilityInfo
  627. * @property {number} [visibilityBlocks]
  628. * @property {boolean} [nodeVisible]
  629. */
  630. /**
  631. * @typedef {object} CSSOutput
  632. * @property {(chunk: string, fileInfo?: FileInfo, index?: number, mapLines?: boolean) => void} add
  633. * @property {() => boolean} isEmpty
  634. */
  635. /**
  636. * @typedef {object} EvalContext
  637. * @property {number} [numPrecision]
  638. * @property {(op?: string) => boolean} [isMathOn]
  639. * @property {number} [math]
  640. * @property {Node[]} [frames]
  641. * @property {Array<{important?: string}>} [importantScope]
  642. * @property {string[]} [paths]
  643. * @property {boolean} [compress]
  644. * @property {boolean} [strictUnits]
  645. * @property {boolean} [sourceMap]
  646. * @property {boolean} [importMultiple]
  647. * @property {string} [urlArgs]
  648. * @property {boolean} [javascriptEnabled]
  649. * @property {object} [pluginManager]
  650. * @property {number} [rewriteUrls]
  651. * @property {boolean} [inCalc]
  652. * @property {boolean} [mathOn]
  653. * @property {boolean[]} [calcStack]
  654. * @property {boolean[]} [parensStack]
  655. * @property {Node[]} [mediaBlocks]
  656. * @property {Node[]} [mediaPath]
  657. * @property {() => void} [inParenthesis]
  658. * @property {() => void} [outOfParenthesis]
  659. * @property {() => void} [enterCalc]
  660. * @property {() => void} [exitCalc]
  661. * @property {(path: string) => boolean} [pathRequiresRewrite]
  662. * @property {(path: string, rootpath?: string) => string} [rewritePath]
  663. * @property {(path: string) => string} [normalizePath]
  664. * @property {number} [tabLevel]
  665. * @property {boolean} [lastRule]
  666. */
  667. /**
  668. * @typedef {object} TreeVisitor
  669. * @property {(node: Node) => Node} visit
  670. * @property {(nodes: Node[], nonReplacing?: boolean) => Node[]} visitArray
  671. */
  672. /**
  673. * The reason why Node is a class and other nodes simply do not extend
  674. * from Node (since we're transpiling) is due to this issue:
  675. *
  676. * @see https://github.com/less/less.js/issues/3434
  677. */
  678. class Node {
  679. get type() { return ''; }
  680. constructor() {
  681. /** @type {Node | null} */
  682. this.parent = null;
  683. /** @type {number | undefined} */
  684. this.visibilityBlocks = undefined;
  685. /** @type {boolean | undefined} */
  686. this.nodeVisible = undefined;
  687. /** @type {Node | null} */
  688. this.rootNode = null;
  689. /** @type {Node | null} */
  690. this.parsed = null;
  691. /** @type {Node | Node[] | string | number | undefined} */
  692. this.value = undefined;
  693. /** @type {number | undefined} */
  694. this._index = undefined;
  695. /** @type {FileInfo | undefined} */
  696. this._fileInfo = undefined;
  697. }
  698. get currentFileInfo() {
  699. return this.fileInfo();
  700. }
  701. get index() {
  702. return this.getIndex();
  703. }
  704. /**
  705. * @param {Node | Node[]} nodes
  706. * @param {Node} parent
  707. */
  708. setParent(nodes, parent) {
  709. /** @param {Node} node */
  710. function set(node) {
  711. if (node && node instanceof Node) {
  712. node.parent = parent;
  713. }
  714. }
  715. if (Array.isArray(nodes)) {
  716. nodes.forEach(set);
  717. }
  718. else {
  719. set(nodes);
  720. }
  721. }
  722. /** @returns {number} */
  723. getIndex() {
  724. return this._index || (this.parent && this.parent.getIndex()) || 0;
  725. }
  726. /** @returns {FileInfo} */
  727. fileInfo() {
  728. return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
  729. }
  730. /** @returns {boolean} */
  731. isRulesetLike() { return false; }
  732. /**
  733. * @param {EvalContext} context
  734. * @returns {string}
  735. */
  736. toCSS(context) {
  737. /** @type {string[]} */
  738. const strs = [];
  739. this.genCSS(context, {
  740. add: function(chunk, fileInfo, index) {
  741. strs.push(chunk);
  742. },
  743. isEmpty: function () {
  744. return strs.length === 0;
  745. }
  746. });
  747. return strs.join('');
  748. }
  749. /**
  750. * @param {EvalContext} context
  751. * @param {CSSOutput} output
  752. */
  753. genCSS(context, output) {
  754. output.add(/** @type {string} */ (this.value));
  755. }
  756. /**
  757. * @param {TreeVisitor} visitor
  758. */
  759. accept(visitor) {
  760. this.value = visitor.visit(/** @type {Node} */ (this.value));
  761. }
  762. /**
  763. * @param {EvalContext} [context]
  764. * @returns {Node}
  765. */
  766. eval(context) { return this; }
  767. /**
  768. * @param {EvalContext} context
  769. * @param {string} op
  770. * @param {number} a
  771. * @param {number} b
  772. * @returns {number | undefined}
  773. */
  774. _operate(context, op, a, b) {
  775. switch (op) {
  776. case '+': return a + b;
  777. case '-': return a - b;
  778. case '*': return a * b;
  779. case '/': return a / b;
  780. }
  781. }
  782. /**
  783. * @param {EvalContext} context
  784. * @param {number} value
  785. * @returns {number}
  786. */
  787. fround(context, value) {
  788. const precision = context && context.numPrecision;
  789. // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
  790. return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
  791. }
  792. /**
  793. * @param {Node & { compare?: (other: Node) => number | undefined }} a
  794. * @param {Node & { compare?: (other: Node) => number | undefined }} b
  795. * @returns {number | undefined}
  796. */
  797. static compare(a, b) {
  798. /* returns:
  799. -1: a < b
  800. 0: a = b
  801. 1: a > b
  802. and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
  803. if ((a.compare) &&
  804. // for "symmetric results" force toCSS-based comparison
  805. // of Quoted or Anonymous if either value is one of those
  806. !(b.type === 'Quoted' || b.type === 'Anonymous')) {
  807. return a.compare(b);
  808. } else if (b.compare) {
  809. return -b.compare(a);
  810. } else if (a.type !== b.type) {
  811. return undefined;
  812. }
  813. let aVal = a.value;
  814. let bVal = b.value;
  815. if (!Array.isArray(aVal)) {
  816. return aVal === bVal ? 0 : undefined;
  817. }
  818. if (!Array.isArray(bVal)) {
  819. return undefined;
  820. }
  821. if (aVal.length !== bVal.length) {
  822. return undefined;
  823. }
  824. for (let i = 0; i < aVal.length; i++) {
  825. if (Node.compare(aVal[i], bVal[i]) !== 0) {
  826. return undefined;
  827. }
  828. }
  829. return 0;
  830. }
  831. /**
  832. * @param {number | string} a
  833. * @param {number | string} b
  834. * @returns {number | undefined}
  835. */
  836. static numericCompare(a, b) {
  837. return a < b ? -1
  838. : a === b ? 0
  839. : a > b ? 1 : undefined;
  840. }
  841. /** @returns {boolean} */
  842. blocksVisibility() {
  843. if (this.visibilityBlocks === undefined) {
  844. this.visibilityBlocks = 0;
  845. }
  846. return this.visibilityBlocks !== 0;
  847. }
  848. addVisibilityBlock() {
  849. if (this.visibilityBlocks === undefined) {
  850. this.visibilityBlocks = 0;
  851. }
  852. this.visibilityBlocks = this.visibilityBlocks + 1;
  853. }
  854. removeVisibilityBlock() {
  855. if (this.visibilityBlocks === undefined) {
  856. this.visibilityBlocks = 0;
  857. }
  858. this.visibilityBlocks = this.visibilityBlocks - 1;
  859. }
  860. ensureVisibility() {
  861. this.nodeVisible = true;
  862. }
  863. ensureInvisibility() {
  864. this.nodeVisible = false;
  865. }
  866. /** @returns {boolean | undefined} */
  867. isVisible() {
  868. return this.nodeVisible;
  869. }
  870. /** @returns {VisibilityInfo} */
  871. visibilityInfo() {
  872. return {
  873. visibilityBlocks: this.visibilityBlocks,
  874. nodeVisible: this.nodeVisible
  875. };
  876. }
  877. /** @param {VisibilityInfo} info */
  878. copyVisibilityInfo(info) {
  879. if (!info) {
  880. return;
  881. }
  882. this.visibilityBlocks = info.visibilityBlocks;
  883. this.nodeVisible = info.nodeVisible;
  884. }
  885. }
  886. /**
  887. * Set by the parser at runtime on Node.prototype.
  888. * @type {{ context: EvalContext, importManager: object, imports: object } | undefined}
  889. */
  890. Node.prototype.parse = undefined;
  891. // @ts-check
  892. /** @import { EvalContext, CSSOutput } from './node.js' */
  893. //
  894. // RGB Colors - #ff0014, #eee
  895. //
  896. class Color extends Node {
  897. get type() { return 'Color'; }
  898. /**
  899. * @param {number[] | string} rgb
  900. * @param {number} [a]
  901. * @param {string} [originalForm]
  902. */
  903. constructor(rgb, a, originalForm) {
  904. super();
  905. const self = this;
  906. //
  907. // The end goal here, is to parse the arguments
  908. // into an integer triplet, such as `128, 255, 0`
  909. //
  910. // This facilitates operations and conversions.
  911. //
  912. if (Array.isArray(rgb)) {
  913. /** @type {number[]} */
  914. this.rgb = rgb;
  915. } else if (rgb.length >= 6) {
  916. /** @type {number[]} */
  917. this.rgb = [];
  918. /** @type {RegExpMatchArray} */ (rgb.match(/.{2}/g)).map(function (c, i) {
  919. if (i < 3) {
  920. self.rgb.push(parseInt(c, 16));
  921. } else {
  922. self.alpha = (parseInt(c, 16)) / 255;
  923. }
  924. });
  925. } else {
  926. /** @type {number[]} */
  927. this.rgb = [];
  928. rgb.split('').map(function (c, i) {
  929. if (i < 3) {
  930. self.rgb.push(parseInt(c + c, 16));
  931. } else {
  932. self.alpha = (parseInt(c + c, 16)) / 255;
  933. }
  934. });
  935. }
  936. /** @type {number} */
  937. if (typeof this.alpha === 'undefined') {
  938. this.alpha = (typeof a === 'number') ? a : 1;
  939. }
  940. if (typeof originalForm !== 'undefined') {
  941. this.value = originalForm;
  942. }
  943. }
  944. luma() {
  945. let r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255;
  946. r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
  947. g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
  948. b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
  949. return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  950. }
  951. /**
  952. * @param {EvalContext} context
  953. * @param {CSSOutput} output
  954. */
  955. genCSS(context, output) {
  956. output.add(this.toCSS(context));
  957. }
  958. /**
  959. * @param {EvalContext} context
  960. * @param {boolean} [doNotCompress]
  961. * @returns {string}
  962. */
  963. toCSS(context, doNotCompress) {
  964. const compress = context && context.compress && !doNotCompress;
  965. let color;
  966. let alpha;
  967. /** @type {string | undefined} */
  968. let colorFunction;
  969. /** @type {(string | number)[]} */
  970. let args = [];
  971. // `value` is set if this color was originally
  972. // converted from a named color string so we need
  973. // to respect this and try to output named color too.
  974. alpha = this.fround(context, this.alpha);
  975. if (this.value) {
  976. if (/** @type {string} */ (this.value).indexOf('rgb') === 0) {
  977. if (alpha < 1) {
  978. colorFunction = 'rgba';
  979. }
  980. } else if (/** @type {string} */ (this.value).indexOf('hsl') === 0) {
  981. if (alpha < 1) {
  982. colorFunction = 'hsla';
  983. } else {
  984. colorFunction = 'hsl';
  985. }
  986. } else {
  987. return /** @type {string} */ (this.value);
  988. }
  989. } else {
  990. if (alpha < 1) {
  991. colorFunction = 'rgba';
  992. }
  993. }
  994. switch (colorFunction) {
  995. case 'rgba':
  996. args = this.rgb.map(function (c) {
  997. return clamp$1(Math.round(c), 255);
  998. }).concat(clamp$1(alpha, 1));
  999. break;
  1000. case 'hsla':
  1001. args.push(clamp$1(alpha, 1));
  1002. // eslint-disable-next-line no-fallthrough
  1003. case 'hsl':
  1004. color = this.toHSL();
  1005. args = [
  1006. this.fround(context, color.h),
  1007. `${this.fround(context, color.s * 100)}%`,
  1008. `${this.fround(context, color.l * 100)}%`
  1009. ].concat(args);
  1010. }
  1011. if (colorFunction) {
  1012. // Values are capped between `0` and `255`, rounded and zero-padded.
  1013. return `${colorFunction}(${args.join(`,${compress ? '' : ' '}`)})`;
  1014. }
  1015. color = this.toRGB();
  1016. if (compress) {
  1017. const splitcolor = color.split('');
  1018. // Convert color to short format
  1019. if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
  1020. color = `#${splitcolor[1]}${splitcolor[3]}${splitcolor[5]}`;
  1021. }
  1022. }
  1023. return color;
  1024. }
  1025. //
  1026. // Operations have to be done per-channel, if not,
  1027. // channels will spill onto each other. Once we have
  1028. // our result, in the form of an integer triplet,
  1029. // we create a new Color node to hold the result.
  1030. //
  1031. /**
  1032. * @param {EvalContext} context
  1033. * @param {string} op
  1034. * @param {Color} other
  1035. */
  1036. operate(context, op, other) {
  1037. const rgb = new Array(3);
  1038. const alpha = this.alpha * (1 - other.alpha) + other.alpha;
  1039. for (let c = 0; c < 3; c++) {
  1040. rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
  1041. }
  1042. return new Color(rgb, alpha);
  1043. }
  1044. toRGB() {
  1045. return toHex(this.rgb);
  1046. }
  1047. toHSL() {
  1048. const r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
  1049. const max = Math.max(r, g, b), min = Math.min(r, g, b);
  1050. /** @type {number} */
  1051. let h;
  1052. let s;
  1053. const l = (max + min) / 2;
  1054. const d = max - min;
  1055. if (max === min) {
  1056. h = s = 0;
  1057. } else {
  1058. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  1059. switch (max) {
  1060. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  1061. case g: h = (b - r) / d + 2; break;
  1062. case b: h = (r - g) / d + 4; break;
  1063. }
  1064. /** @type {number} */ (h) /= 6;
  1065. }
  1066. return { h: /** @type {number} */ (h) * 360, s, l, a };
  1067. }
  1068. // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  1069. toHSV() {
  1070. const r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
  1071. const max = Math.max(r, g, b), min = Math.min(r, g, b);
  1072. /** @type {number} */
  1073. let h;
  1074. let s;
  1075. const v = max;
  1076. const d = max - min;
  1077. if (max === 0) {
  1078. s = 0;
  1079. } else {
  1080. s = d / max;
  1081. }
  1082. if (max === min) {
  1083. h = 0;
  1084. } else {
  1085. switch (max) {
  1086. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  1087. case g: h = (b - r) / d + 2; break;
  1088. case b: h = (r - g) / d + 4; break;
  1089. }
  1090. /** @type {number} */ (h) /= 6;
  1091. }
  1092. return { h: /** @type {number} */ (h) * 360, s, v, a };
  1093. }
  1094. toARGB() {
  1095. return toHex([this.alpha * 255].concat(this.rgb));
  1096. }
  1097. /**
  1098. * @param {Node & { rgb?: number[], alpha?: number }} x
  1099. * @returns {0 | undefined}
  1100. */
  1101. compare(x) {
  1102. return (x.rgb &&
  1103. x.rgb[0] === this.rgb[0] &&
  1104. x.rgb[1] === this.rgb[1] &&
  1105. x.rgb[2] === this.rgb[2] &&
  1106. x.alpha === this.alpha) ? 0 : undefined;
  1107. }
  1108. /** @param {string} keyword */
  1109. static fromKeyword(keyword) {
  1110. /** @type {Color | undefined} */
  1111. let c;
  1112. const key = keyword.toLowerCase();
  1113. // eslint-disable-next-line no-prototype-builtins
  1114. if (colors.hasOwnProperty(key)) {
  1115. c = new Color(/** @type {string} */ (colors[/** @type {keyof typeof colors} */ (key)]).slice(1));
  1116. }
  1117. else if (key === 'transparent') {
  1118. c = new Color([0, 0, 0], 0);
  1119. }
  1120. if (c) {
  1121. c.value = keyword;
  1122. return c;
  1123. }
  1124. }
  1125. }
  1126. /**
  1127. * @param {number} v
  1128. * @param {number} max
  1129. */
  1130. function clamp$1(v, max) {
  1131. return Math.min(Math.max(v, 0), max);
  1132. }
  1133. /** @param {number[]} v */
  1134. function toHex(v) {
  1135. return `#${v.map(function (c) {
  1136. c = clamp$1(Math.round(c), 255);
  1137. return (c < 16 ? '0' : '') + c.toString(16);
  1138. }).join('')}`;
  1139. }
  1140. // @ts-check
  1141. class Paren extends Node {
  1142. get type() { return 'Paren'; }
  1143. /** @param {Node} node */
  1144. constructor(node) {
  1145. super();
  1146. this.value = node;
  1147. /** @type {boolean | undefined} */
  1148. this.noSpacing = undefined;
  1149. }
  1150. /**
  1151. * @param {EvalContext} context
  1152. * @param {CSSOutput} output
  1153. */
  1154. genCSS(context, output) {
  1155. output.add('(');
  1156. /** @type {Node} */ (this.value).genCSS(context, output);
  1157. output.add(')');
  1158. }
  1159. /**
  1160. * @param {EvalContext} context
  1161. * @returns {Paren}
  1162. */
  1163. eval(context) {
  1164. const paren = new Paren(/** @type {Node} */ (this.value).eval(context));
  1165. if (this.noSpacing) {
  1166. paren.noSpacing = true;
  1167. }
  1168. return paren;
  1169. }
  1170. }
  1171. // @ts-check
  1172. /** @import { EvalContext, CSSOutput } from './node.js' */
  1173. /** @type {Record<string, boolean>} */
  1174. const _noSpaceCombinators = {
  1175. '': true,
  1176. ' ': true,
  1177. '|': true
  1178. };
  1179. class Combinator extends Node {
  1180. get type() { return 'Combinator'; }
  1181. /** @param {string} value */
  1182. constructor(value) {
  1183. super();
  1184. if (value === ' ') {
  1185. this.value = ' ';
  1186. this.emptyOrWhitespace = true;
  1187. } else {
  1188. this.value = value ? value.trim() : '';
  1189. this.emptyOrWhitespace = this.value === '';
  1190. }
  1191. }
  1192. /**
  1193. * @param {EvalContext} context
  1194. * @param {CSSOutput} output
  1195. */
  1196. genCSS(context, output) {
  1197. const spaceOrEmpty = (context.compress || _noSpaceCombinators[/** @type {string} */ (this.value)]) ? '' : ' ';
  1198. output.add(spaceOrEmpty + this.value + spaceOrEmpty);
  1199. }
  1200. }
  1201. // @ts-check
  1202. class Element extends Node {
  1203. get type() { return 'Element'; }
  1204. /**
  1205. * @param {Combinator | string} combinator
  1206. * @param {string | Node} value
  1207. * @param {boolean} [isVariable]
  1208. * @param {number} [index]
  1209. * @param {FileInfo} [currentFileInfo]
  1210. * @param {VisibilityInfo} [visibilityInfo]
  1211. */
  1212. constructor(combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
  1213. super();
  1214. this.combinator = combinator instanceof Combinator ?
  1215. combinator : new Combinator(combinator);
  1216. if (typeof value === 'string') {
  1217. this.value = value.trim();
  1218. } else if (value) {
  1219. this.value = value;
  1220. } else {
  1221. this.value = '';
  1222. }
  1223. /** @type {boolean | undefined} */
  1224. this.isVariable = isVariable;
  1225. this._index = index;
  1226. this._fileInfo = currentFileInfo;
  1227. this.copyVisibilityInfo(visibilityInfo);
  1228. this.setParent(this.combinator, this);
  1229. }
  1230. /** @param {TreeVisitor} visitor */
  1231. accept(visitor) {
  1232. const value = this.value;
  1233. this.combinator = /** @type {Combinator} */ (visitor.visit(this.combinator));
  1234. if (typeof value === 'object') {
  1235. this.value = visitor.visit(/** @type {Node} */ (value));
  1236. }
  1237. }
  1238. /** @param {EvalContext} context */
  1239. eval(context) {
  1240. return new Element(this.combinator,
  1241. /** @type {Node} */ (this.value).eval ? /** @type {Node} */ (this.value).eval(context) : /** @type {string} */ (this.value),
  1242. this.isVariable,
  1243. this.getIndex(),
  1244. this.fileInfo(), this.visibilityInfo());
  1245. }
  1246. clone() {
  1247. return new Element(this.combinator,
  1248. /** @type {string | Node} */ (this.value),
  1249. this.isVariable,
  1250. this.getIndex(),
  1251. this.fileInfo(), this.visibilityInfo());
  1252. }
  1253. /**
  1254. * @param {EvalContext} context
  1255. * @param {CSSOutput} output
  1256. */
  1257. genCSS(context, output) {
  1258. output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
  1259. }
  1260. /** @param {EvalContext} [context] */
  1261. toCSS(context) {
  1262. /** @type {EvalContext & { firstSelector?: boolean }} */
  1263. const ctx = context || {};
  1264. let value = this.value;
  1265. const firstSelector = ctx.firstSelector;
  1266. if (value instanceof Paren) {
  1267. // selector in parens should not be affected by outer selector
  1268. // flags (breaks only interpolated selectors - see #1973)
  1269. ctx.firstSelector = true;
  1270. }
  1271. value = /** @type {Node} */ (value).toCSS ? /** @type {Node} */ (value).toCSS(ctx) : /** @type {string} */ (value);
  1272. ctx.firstSelector = firstSelector;
  1273. if (value === '' && this.combinator.value.charAt(0) === '&') {
  1274. return '';
  1275. } else {
  1276. return this.combinator.toCSS(ctx) + value;
  1277. }
  1278. }
  1279. }
  1280. const Math$1 = {
  1281. ALWAYS: 0,
  1282. PARENS_DIVISION: 1,
  1283. PARENS: 2
  1284. // removed - STRICT_LEGACY: 3
  1285. };
  1286. const RewriteUrls = {
  1287. OFF: 0,
  1288. LOCAL: 1,
  1289. ALL: 2
  1290. };
  1291. function getType(payload) {
  1292. return Object.prototype.toString.call(payload).slice(8, -1);
  1293. }
  1294. function isArray(payload) {
  1295. return getType(payload) === "Array";
  1296. }
  1297. function isPlainObject(payload) {
  1298. if (getType(payload) !== "Object")
  1299. return false;
  1300. const prototype = Object.getPrototypeOf(payload);
  1301. return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
  1302. }
  1303. function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
  1304. const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
  1305. if (propType === "enumerable")
  1306. carry[key] = newVal;
  1307. if (includeNonenumerable && propType === "nonenumerable") {
  1308. Object.defineProperty(carry, key, {
  1309. value: newVal,
  1310. enumerable: false,
  1311. writable: true,
  1312. configurable: true
  1313. });
  1314. }
  1315. }
  1316. function copy(target, options = {}) {
  1317. if (isArray(target)) {
  1318. return target.map((item) => copy(item, options));
  1319. }
  1320. if (!isPlainObject(target)) {
  1321. return target;
  1322. }
  1323. const props = Object.getOwnPropertyNames(target);
  1324. const symbols = Object.getOwnPropertySymbols(target);
  1325. return [...props, ...symbols].reduce((carry, key) => {
  1326. if (isArray(options.props) && !options.props.includes(key)) {
  1327. return carry;
  1328. }
  1329. const val = target[key];
  1330. const newVal = copy(val, options);
  1331. assignProp(carry, key, newVal, target, options.nonenumerable);
  1332. return carry;
  1333. }, {});
  1334. }
  1335. /* jshint proto: true */
  1336. function getLocation(index, inputStream) {
  1337. let n = index + 1;
  1338. let line = null;
  1339. let column = -1;
  1340. while (--n >= 0 && inputStream.charAt(n) !== '\n') {
  1341. column++;
  1342. }
  1343. if (typeof index === 'number') {
  1344. line = (inputStream.slice(0, index).match(/\n/g) || '').length;
  1345. }
  1346. return {
  1347. line,
  1348. column
  1349. };
  1350. }
  1351. function copyArray(arr) {
  1352. let i;
  1353. const length = arr.length;
  1354. const copy = new Array(length);
  1355. for (i = 0; i < length; i++) {
  1356. copy[i] = arr[i];
  1357. }
  1358. return copy;
  1359. }
  1360. function clone(obj) {
  1361. const cloned = {};
  1362. for (const prop in obj) {
  1363. if (Object.prototype.hasOwnProperty.call(obj, prop)) {
  1364. cloned[prop] = obj[prop];
  1365. }
  1366. }
  1367. return cloned;
  1368. }
  1369. function defaults(obj1, obj2) {
  1370. let newObj = obj2 || {};
  1371. if (!obj2._defaults) {
  1372. newObj = {};
  1373. const defaults = copy(obj1);
  1374. newObj._defaults = defaults;
  1375. const cloned = obj2 ? copy(obj2) : {};
  1376. Object.assign(newObj, defaults, cloned);
  1377. }
  1378. return newObj;
  1379. }
  1380. function copyOptions(obj1, obj2) {
  1381. if (obj2 && obj2._defaults) {
  1382. return obj2;
  1383. }
  1384. const opts = defaults(obj1, obj2);
  1385. if (opts.strictMath) {
  1386. opts.math = Math$1.PARENS;
  1387. }
  1388. // Back compat with changed relativeUrls option
  1389. if (opts.relativeUrls) {
  1390. opts.rewriteUrls = RewriteUrls.ALL;
  1391. }
  1392. if (typeof opts.math === 'string') {
  1393. switch (opts.math.toLowerCase()) {
  1394. case 'always':
  1395. opts.math = Math$1.ALWAYS;
  1396. break;
  1397. case 'parens-division':
  1398. opts.math = Math$1.PARENS_DIVISION;
  1399. break;
  1400. case 'strict':
  1401. case 'parens':
  1402. opts.math = Math$1.PARENS;
  1403. break;
  1404. default:
  1405. opts.math = Math$1.PARENS;
  1406. }
  1407. }
  1408. if (typeof opts.rewriteUrls === 'string') {
  1409. switch (opts.rewriteUrls.toLowerCase()) {
  1410. case 'off':
  1411. opts.rewriteUrls = RewriteUrls.OFF;
  1412. break;
  1413. case 'local':
  1414. opts.rewriteUrls = RewriteUrls.LOCAL;
  1415. break;
  1416. case 'all':
  1417. opts.rewriteUrls = RewriteUrls.ALL;
  1418. break;
  1419. }
  1420. }
  1421. return opts;
  1422. }
  1423. function merge(obj1, obj2) {
  1424. for (const prop in obj2) {
  1425. if (Object.prototype.hasOwnProperty.call(obj2, prop)) {
  1426. obj1[prop] = obj2[prop];
  1427. }
  1428. }
  1429. return obj1;
  1430. }
  1431. function flattenArray(arr, result = []) {
  1432. for (let i = 0, length = arr.length; i < length; i++) {
  1433. const value = arr[i];
  1434. if (Array.isArray(value)) {
  1435. flattenArray(value, result);
  1436. } else {
  1437. if (value !== undefined) {
  1438. result.push(value);
  1439. }
  1440. }
  1441. }
  1442. return result;
  1443. }
  1444. function isNullOrUndefined(val) {
  1445. return val === null || val === undefined
  1446. }
  1447. var utils = /*#__PURE__*/Object.freeze({
  1448. __proto__: null,
  1449. getLocation: getLocation,
  1450. copyArray: copyArray,
  1451. clone: clone,
  1452. defaults: defaults,
  1453. copyOptions: copyOptions,
  1454. merge: merge,
  1455. flattenArray: flattenArray,
  1456. isNullOrUndefined: isNullOrUndefined
  1457. });
  1458. const anonymousFunc = /(<anonymous>|Function):(\d+):(\d+)/;
  1459. /**
  1460. * This is a centralized class of any error that could be thrown internally (mostly by the parser).
  1461. * Besides standard .message it keeps some additional data like a path to the file where the error
  1462. * occurred along with line and column numbers.
  1463. *
  1464. * @class
  1465. * @extends Error
  1466. * @type {module.LessError}
  1467. *
  1468. * @prop {string} type
  1469. * @prop {string} filename
  1470. * @prop {number} index
  1471. * @prop {number} line
  1472. * @prop {number} column
  1473. * @prop {number} callLine
  1474. * @prop {number} callExtract
  1475. * @prop {string[]} extract
  1476. *
  1477. * @param {Object} e - An error object to wrap around or just a descriptive object
  1478. * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
  1479. * @param {string} [currentFilename]
  1480. */
  1481. const LessError = function(e, fileContentMap, currentFilename) {
  1482. Error.call(this);
  1483. const filename = e.filename || currentFilename;
  1484. this.message = e.message;
  1485. this.stack = e.stack;
  1486. // Set type early so it's always available, even if fileContentMap is missing
  1487. this.type = e.type || 'Syntax';
  1488. if (fileContentMap && filename) {
  1489. const input = fileContentMap.contents[filename];
  1490. const loc = getLocation(e.index, input);
  1491. var line = loc.line;
  1492. const col = loc.column;
  1493. const callLine = e.call && getLocation(e.call, input).line;
  1494. const lines = input ? input.split('\n') : '';
  1495. this.filename = filename;
  1496. this.index = e.index;
  1497. this.line = typeof line === 'number' ? line + 1 : null;
  1498. this.column = col;
  1499. if (!this.line && this.stack) {
  1500. const found = this.stack.match(anonymousFunc);
  1501. /**
  1502. * We have to figure out how this environment stringifies anonymous functions
  1503. * so we can correctly map plugin errors.
  1504. *
  1505. * Note, in Node 8, the output of anonymous funcs varied based on parameters
  1506. * being present or not, so we inject dummy params.
  1507. */
  1508. const func = new Function('a', 'throw new Error()');
  1509. let lineAdjust = 0;
  1510. try {
  1511. func();
  1512. } catch (e) {
  1513. const match = e.stack.match(anonymousFunc);
  1514. lineAdjust = 1 - parseInt(match[2]);
  1515. }
  1516. if (found) {
  1517. if (found[2]) {
  1518. this.line = parseInt(found[2]) + lineAdjust;
  1519. }
  1520. if (found[3]) {
  1521. this.column = parseInt(found[3]);
  1522. }
  1523. }
  1524. }
  1525. this.callLine = callLine + 1;
  1526. this.callExtract = lines[callLine];
  1527. this.extract = [
  1528. lines[this.line - 2],
  1529. lines[this.line - 1],
  1530. lines[this.line]
  1531. ];
  1532. }
  1533. };
  1534. if (typeof Object.create === 'undefined') {
  1535. const F = function () {};
  1536. F.prototype = Error.prototype;
  1537. LessError.prototype = new F();
  1538. } else {
  1539. LessError.prototype = Object.create(Error.prototype);
  1540. }
  1541. LessError.prototype.constructor = LessError;
  1542. /**
  1543. * An overridden version of the default Object.prototype.toString
  1544. * which uses additional information to create a helpful message.
  1545. *
  1546. * @param {Object} options
  1547. * @returns {string}
  1548. */
  1549. LessError.prototype.toString = function(options) {
  1550. options = options || {};
  1551. const isWarning = (this.type ?? '').toLowerCase().includes('warning');
  1552. const type = isWarning ? this.type : `${this.type}Error`;
  1553. const color = isWarning ? 'yellow' : 'red';
  1554. let message = '';
  1555. const extract = this.extract || [];
  1556. let error = [];
  1557. let stylize = function (str) { return str; };
  1558. if (options.stylize) {
  1559. const type = typeof options.stylize;
  1560. if (type !== 'function') {
  1561. throw Error(`options.stylize should be a function, got a ${type}!`);
  1562. }
  1563. stylize = options.stylize;
  1564. }
  1565. if (this.line !== null) {
  1566. if (!isWarning && typeof extract[0] === 'string') {
  1567. error.push(stylize(`${this.line - 1} ${extract[0]}`, 'grey'));
  1568. }
  1569. if (typeof extract[1] === 'string') {
  1570. let errorTxt = `${this.line} `;
  1571. if (extract[1]) {
  1572. errorTxt += extract[1].slice(0, this.column) +
  1573. stylize(stylize(stylize(extract[1].slice(this.column, this.column + 1), 'bold') +
  1574. extract[1].slice(this.column + 1), 'red'), 'inverse');
  1575. }
  1576. error.push(errorTxt);
  1577. }
  1578. if (!isWarning && typeof extract[2] === 'string') {
  1579. error.push(stylize(`${this.line + 1} ${extract[2]}`, 'grey'));
  1580. }
  1581. error = `${error.join('\n') + stylize('', 'reset')}\n`;
  1582. }
  1583. message += stylize(`${type}: ${this.message}`, color);
  1584. if (this.filename) {
  1585. message += stylize(' in ', color) + this.filename;
  1586. }
  1587. if (this.line) {
  1588. message += stylize(` on line ${this.line}, column ${this.column + 1}:`, 'grey');
  1589. }
  1590. message += `\n${error}`;
  1591. if (this.callLine) {
  1592. message += `${stylize('from ', color) + (this.filename || '')}/n`;
  1593. message += `${stylize(this.callLine, 'grey')} ${this.callExtract}/n`;
  1594. }
  1595. return message;
  1596. };
  1597. const _visitArgs = { visitDeeper: true };
  1598. let _hasIndexed = false;
  1599. function _noop(node) {
  1600. return node;
  1601. }
  1602. function indexNodeTypes(parent, ticker) {
  1603. // add .typeIndex to tree node types for lookup table
  1604. let key, child;
  1605. for (key in parent) {
  1606. /* eslint guard-for-in: 0 */
  1607. child = parent[key];
  1608. switch (typeof child) {
  1609. case 'function':
  1610. // ignore bound functions directly on tree which do not have a prototype
  1611. // or aren't nodes
  1612. if (child.prototype && child.prototype.type) {
  1613. child.prototype.typeIndex = ticker++;
  1614. }
  1615. break;
  1616. case 'object':
  1617. ticker = indexNodeTypes(child, ticker);
  1618. break;
  1619. }
  1620. }
  1621. return ticker;
  1622. }
  1623. class Visitor {
  1624. constructor(implementation) {
  1625. this._implementation = implementation;
  1626. this._visitInCache = {};
  1627. this._visitOutCache = {};
  1628. if (!_hasIndexed) {
  1629. indexNodeTypes(tree, 1);
  1630. _hasIndexed = true;
  1631. }
  1632. }
  1633. visit(node) {
  1634. if (!node) {
  1635. return node;
  1636. }
  1637. const nodeTypeIndex = node.typeIndex;
  1638. if (!nodeTypeIndex) {
  1639. // MixinCall args aren't a node type?
  1640. if (node.value && node.value.typeIndex) {
  1641. this.visit(node.value);
  1642. }
  1643. return node;
  1644. }
  1645. const impl = this._implementation;
  1646. let func = this._visitInCache[nodeTypeIndex];
  1647. let funcOut = this._visitOutCache[nodeTypeIndex];
  1648. const visitArgs = _visitArgs;
  1649. let fnName;
  1650. visitArgs.visitDeeper = true;
  1651. if (!func) {
  1652. fnName = `visit${node.type}`;
  1653. func = impl[fnName] || _noop;
  1654. funcOut = impl[`${fnName}Out`] || _noop;
  1655. this._visitInCache[nodeTypeIndex] = func;
  1656. this._visitOutCache[nodeTypeIndex] = funcOut;
  1657. }
  1658. if (func !== _noop) {
  1659. const newNode = func.call(impl, node, visitArgs);
  1660. if (node && impl.isReplacing) {
  1661. node = newNode;
  1662. }
  1663. }
  1664. if (visitArgs.visitDeeper && node) {
  1665. if (node.length) {
  1666. for (let i = 0, cnt = node.length; i < cnt; i++) {
  1667. if (node[i].accept) {
  1668. node[i].accept(this);
  1669. }
  1670. }
  1671. } else if (node.accept) {
  1672. node.accept(this);
  1673. }
  1674. }
  1675. if (funcOut != _noop) {
  1676. funcOut.call(impl, node);
  1677. }
  1678. return node;
  1679. }
  1680. visitArray(nodes, nonReplacing) {
  1681. if (!nodes) {
  1682. return nodes;
  1683. }
  1684. const cnt = nodes.length;
  1685. let i;
  1686. // Non-replacing
  1687. if (nonReplacing || !this._implementation.isReplacing) {
  1688. for (i = 0; i < cnt; i++) {
  1689. this.visit(nodes[i]);
  1690. }
  1691. return nodes;
  1692. }
  1693. // Replacing
  1694. const out = [];
  1695. for (i = 0; i < cnt; i++) {
  1696. const evald = this.visit(nodes[i]);
  1697. if (evald === undefined) { continue; }
  1698. if (!evald.splice) {
  1699. out.push(evald);
  1700. } else if (evald.length) {
  1701. this.flatten(evald, out);
  1702. }
  1703. }
  1704. return out;
  1705. }
  1706. flatten(arr, out) {
  1707. if (!out) {
  1708. out = [];
  1709. }
  1710. let cnt, i, item, nestedCnt, j, nestedItem;
  1711. for (i = 0, cnt = arr.length; i < cnt; i++) {
  1712. item = arr[i];
  1713. if (item === undefined) {
  1714. continue;
  1715. }
  1716. if (!item.splice) {
  1717. out.push(item);
  1718. continue;
  1719. }
  1720. for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
  1721. nestedItem = item[j];
  1722. if (nestedItem === undefined) {
  1723. continue;
  1724. }
  1725. if (!nestedItem.splice) {
  1726. out.push(nestedItem);
  1727. } else if (nestedItem.length) {
  1728. this.flatten(nestedItem, out);
  1729. }
  1730. }
  1731. }
  1732. return out;
  1733. }
  1734. }
  1735. const contexts = {};
  1736. const copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
  1737. if (!original) { return; }
  1738. for (let i = 0; i < propertiesToCopy.length; i++) {
  1739. if (Object.prototype.hasOwnProperty.call(original, propertiesToCopy[i])) {
  1740. destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
  1741. }
  1742. }
  1743. };
  1744. /*
  1745. parse is used whilst parsing
  1746. */
  1747. const parseCopyProperties = [
  1748. // options
  1749. 'paths', // option - unmodified - paths to search for imports on
  1750. 'rewriteUrls', // option - whether to adjust URL's to be relative
  1751. 'rootpath', // option - rootpath to append to URL's
  1752. 'strictImports', // option -
  1753. 'insecure', // option - whether to allow imports from insecure ssl hosts
  1754. 'dumpLineNumbers', // option - @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead. All modes ('comments', 'mediaquery', 'all') will be removed in a future version.
  1755. 'compress', // option - whether to compress
  1756. 'syncImport', // option - whether to import synchronously
  1757. 'mime', // browser only - mime type for sheet import
  1758. 'useFileCache', // browser only - whether to use the per file session cache
  1759. // context
  1760. 'processImports', // option & context - whether to process imports. if false then imports will not be imported.
  1761. // Used by the import manager to stop multiple import visitors being created.
  1762. 'pluginManager', // Used as the plugin manager for the session
  1763. 'quiet', // option - whether to log warnings
  1764. 'quietDeprecations', // option - whether to suppress deprecation warnings only
  1765. ];
  1766. contexts.Parse = function(options) {
  1767. copyFromOriginal(options, this, parseCopyProperties);
  1768. if (typeof this.paths === 'string') { this.paths = [this.paths]; }
  1769. };
  1770. const evalCopyProperties = [
  1771. 'paths', // additional include paths
  1772. 'compress', // whether to compress
  1773. 'math', // whether math has to be within parenthesis
  1774. 'strictUnits', // whether units need to evaluate correctly
  1775. 'sourceMap', // whether to output a source map
  1776. 'importMultiple', // whether we are currently importing multiple copies
  1777. 'urlArgs', // whether to add args into url tokens
  1778. 'javascriptEnabled', // option - whether Inline JavaScript is enabled. if undefined, defaults to false
  1779. 'pluginManager', // Used as the plugin manager for the session
  1780. 'importantScope', // used to bubble up !important statements
  1781. 'rewriteUrls' // option - whether to adjust URL's to be relative
  1782. ];
  1783. contexts.Eval = function(options, frames) {
  1784. copyFromOriginal(options, this, evalCopyProperties);
  1785. if (typeof this.paths === 'string') { this.paths = [this.paths]; }
  1786. this.frames = frames || [];
  1787. this.importantScope = this.importantScope || [];
  1788. };
  1789. contexts.Eval.prototype.enterCalc = function () {
  1790. if (!this.calcStack) {
  1791. this.calcStack = [];
  1792. }
  1793. this.calcStack.push(true);
  1794. this.inCalc = true;
  1795. };
  1796. contexts.Eval.prototype.exitCalc = function () {
  1797. this.calcStack.pop();
  1798. if (!this.calcStack.length) {
  1799. this.inCalc = false;
  1800. }
  1801. };
  1802. contexts.Eval.prototype.inParenthesis = function () {
  1803. if (!this.parensStack) {
  1804. this.parensStack = [];
  1805. }
  1806. this.parensStack.push(true);
  1807. };
  1808. contexts.Eval.prototype.outOfParenthesis = function () {
  1809. this.parensStack.pop();
  1810. };
  1811. contexts.Eval.prototype.inCalc = false;
  1812. contexts.Eval.prototype.mathOn = true;
  1813. contexts.Eval.prototype.isMathOn = function (op) {
  1814. if (!this.mathOn) {
  1815. return false;
  1816. }
  1817. if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
  1818. return false;
  1819. }
  1820. if (this.math > Math$1.PARENS_DIVISION) {
  1821. return this.parensStack && this.parensStack.length;
  1822. }
  1823. return true;
  1824. };
  1825. contexts.Eval.prototype.pathRequiresRewrite = function (path) {
  1826. const isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
  1827. return isRelative(path);
  1828. };
  1829. contexts.Eval.prototype.rewritePath = function (path, rootpath) {
  1830. let newPath;
  1831. rootpath = rootpath || '';
  1832. newPath = this.normalizePath(rootpath + path);
  1833. // If a path was explicit relative and the rootpath was not an absolute path
  1834. // we must ensure that the new path is also explicit relative.
  1835. if (isPathLocalRelative(path) &&
  1836. isPathRelative(rootpath) &&
  1837. isPathLocalRelative(newPath) === false) {
  1838. newPath = `./${newPath}`;
  1839. }
  1840. return newPath;
  1841. };
  1842. contexts.Eval.prototype.normalizePath = function (path) {
  1843. const segments = path.split('/').reverse();
  1844. let segment;
  1845. path = [];
  1846. while (segments.length !== 0) {
  1847. segment = segments.pop();
  1848. switch ( segment ) {
  1849. case '.':
  1850. break;
  1851. case '..':
  1852. if ((path.length === 0) || (path[path.length - 1] === '..')) {
  1853. path.push( segment );
  1854. } else {
  1855. path.pop();
  1856. }
  1857. break;
  1858. default:
  1859. path.push(segment);
  1860. break;
  1861. }
  1862. }
  1863. return path.join('/');
  1864. };
  1865. function isPathRelative(path) {
  1866. return !/^(?:[a-z-]+:|\/|#)/i.test(path);
  1867. }
  1868. function isPathLocalRelative(path) {
  1869. return path.charAt(0) === '.';
  1870. }
  1871. // todo - do the same for the toCSS ?
  1872. class ImportSequencer {
  1873. constructor(onSequencerEmpty) {
  1874. this.imports = [];
  1875. this.variableImports = [];
  1876. this._onSequencerEmpty = onSequencerEmpty;
  1877. this._currentDepth = 0;
  1878. }
  1879. addImport(callback) {
  1880. const importSequencer = this,
  1881. importItem = {
  1882. callback,
  1883. args: null,
  1884. isReady: false
  1885. };
  1886. this.imports.push(importItem);
  1887. return function() {
  1888. importItem.args = Array.prototype.slice.call(arguments, 0);
  1889. importItem.isReady = true;
  1890. importSequencer.tryRun();
  1891. };
  1892. }
  1893. addVariableImport(callback) {
  1894. this.variableImports.push(callback);
  1895. }
  1896. tryRun() {
  1897. this._currentDepth++;
  1898. try {
  1899. while (true) {
  1900. while (this.imports.length > 0) {
  1901. const importItem = this.imports[0];
  1902. if (!importItem.isReady) {
  1903. return;
  1904. }
  1905. this.imports = this.imports.slice(1);
  1906. importItem.callback.apply(null, importItem.args);
  1907. }
  1908. if (this.variableImports.length === 0) {
  1909. break;
  1910. }
  1911. const variableImport = this.variableImports[0];
  1912. this.variableImports = this.variableImports.slice(1);
  1913. variableImport();
  1914. }
  1915. } finally {
  1916. this._currentDepth--;
  1917. }
  1918. if (this._currentDepth === 0 && this._onSequencerEmpty) {
  1919. this._onSequencerEmpty();
  1920. }
  1921. }
  1922. }
  1923. /* eslint-disable no-unused-vars */
  1924. const ImportVisitor = function(importer, finish) {
  1925. this._visitor = new Visitor(this);
  1926. this._importer = importer;
  1927. this._finish = finish;
  1928. this.context = new contexts.Eval();
  1929. this.importCount = 0;
  1930. this.onceFileDetectionMap = {};
  1931. this.recursionDetector = {};
  1932. this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
  1933. };
  1934. ImportVisitor.prototype = {
  1935. isReplacing: false,
  1936. run: function (root) {
  1937. try {
  1938. // process the contents
  1939. this._visitor.visit(root);
  1940. }
  1941. catch (e) {
  1942. this.error = e;
  1943. }
  1944. this.isFinished = true;
  1945. this._sequencer.tryRun();
  1946. },
  1947. _onSequencerEmpty: function() {
  1948. if (!this.isFinished) {
  1949. return;
  1950. }
  1951. this._finish(this.error);
  1952. },
  1953. visitImport: function (importNode, visitArgs) {
  1954. const inlineCSS = importNode.options.inline;
  1955. if (!importNode.css || inlineCSS) {
  1956. const context = new contexts.Eval(this.context, copyArray(this.context.frames));
  1957. const importParent = context.frames[0];
  1958. this.importCount++;
  1959. if (importNode.isVariableImport()) {
  1960. this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
  1961. } else {
  1962. this.processImportNode(importNode, context, importParent);
  1963. }
  1964. }
  1965. visitArgs.visitDeeper = false;
  1966. },
  1967. processImportNode: function(importNode, context, importParent) {
  1968. let evaldImportNode;
  1969. const inlineCSS = importNode.options.inline;
  1970. try {
  1971. evaldImportNode = importNode.evalForImport(context);
  1972. } catch (e) {
  1973. if (!e.filename) { e.index = importNode.getIndex(); e.filename = importNode.fileInfo().filename; }
  1974. // attempt to eval properly and treat as css
  1975. importNode.css = true;
  1976. // if that fails, this error will be thrown
  1977. importNode.error = e;
  1978. }
  1979. if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
  1980. if (evaldImportNode.options.multiple) {
  1981. context.importMultiple = true;
  1982. }
  1983. // try appending if we haven't determined if it is css or not
  1984. const tryAppendLessExtension = evaldImportNode.css === undefined;
  1985. for (let i = 0; i < importParent.rules.length; i++) {
  1986. if (importParent.rules[i] === importNode) {
  1987. importParent.rules[i] = evaldImportNode;
  1988. break;
  1989. }
  1990. }
  1991. const onImported = this.onImported.bind(this, evaldImportNode, context), sequencedOnImported = this._sequencer.addImport(onImported);
  1992. this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(),
  1993. evaldImportNode.options, sequencedOnImported);
  1994. } else {
  1995. this.importCount--;
  1996. if (this.isFinished) {
  1997. this._sequencer.tryRun();
  1998. }
  1999. }
  2000. },
  2001. onImported: function (importNode, context, e, root, importedAtRoot, fullPath) {
  2002. if (e) {
  2003. if (!e.filename) {
  2004. e.index = importNode.getIndex(); e.filename = importNode.fileInfo().filename;
  2005. }
  2006. this.error = e;
  2007. }
  2008. const importVisitor = this,
  2009. inlineCSS = importNode.options.inline,
  2010. isPlugin = importNode.options.isPlugin,
  2011. isOptional = importNode.options.optional,
  2012. duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
  2013. if (!context.importMultiple) {
  2014. if (duplicateImport) {
  2015. importNode.skip = true;
  2016. } else {
  2017. importNode.skip = function() {
  2018. if (fullPath in importVisitor.onceFileDetectionMap) {
  2019. return true;
  2020. }
  2021. importVisitor.onceFileDetectionMap[fullPath] = true;
  2022. return false;
  2023. };
  2024. }
  2025. }
  2026. if (!fullPath && isOptional) {
  2027. importNode.skip = true;
  2028. }
  2029. if (root) {
  2030. importNode.root = root;
  2031. importNode.importedFilename = fullPath;
  2032. if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
  2033. importVisitor.recursionDetector[fullPath] = true;
  2034. const oldContext = this.context;
  2035. this.context = context;
  2036. try {
  2037. this._visitor.visit(root);
  2038. } catch (e) {
  2039. this.error = e;
  2040. }
  2041. this.context = oldContext;
  2042. }
  2043. }
  2044. importVisitor.importCount--;
  2045. if (importVisitor.isFinished) {
  2046. importVisitor._sequencer.tryRun();
  2047. }
  2048. },
  2049. visitDeclaration: function (declNode, visitArgs) {
  2050. if (declNode.value.type === 'DetachedRuleset') {
  2051. this.context.frames.unshift(declNode);
  2052. } else {
  2053. visitArgs.visitDeeper = false;
  2054. }
  2055. },
  2056. visitDeclarationOut: function(declNode) {
  2057. if (declNode.value.type === 'DetachedRuleset') {
  2058. this.context.frames.shift();
  2059. }
  2060. },
  2061. visitAtRule: function (atRuleNode, visitArgs) {
  2062. if (atRuleNode.value) {
  2063. this.context.frames.unshift(atRuleNode);
  2064. } else if (atRuleNode.declarations && atRuleNode.declarations.length) {
  2065. if (atRuleNode.isRooted) {
  2066. this.context.frames.unshift(atRuleNode);
  2067. } else {
  2068. this.context.frames.unshift(atRuleNode.declarations[0]);
  2069. }
  2070. } else if (atRuleNode.rules && atRuleNode.rules.length) {
  2071. this.context.frames.unshift(atRuleNode);
  2072. }
  2073. },
  2074. visitAtRuleOut: function (atRuleNode) {
  2075. this.context.frames.shift();
  2076. },
  2077. visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
  2078. this.context.frames.unshift(mixinDefinitionNode);
  2079. },
  2080. visitMixinDefinitionOut: function (mixinDefinitionNode) {
  2081. this.context.frames.shift();
  2082. },
  2083. visitRuleset: function (rulesetNode, visitArgs) {
  2084. this.context.frames.unshift(rulesetNode);
  2085. },
  2086. visitRulesetOut: function (rulesetNode) {
  2087. this.context.frames.shift();
  2088. },
  2089. visitMedia: function (mediaNode, visitArgs) {
  2090. this.context.frames.unshift(mediaNode.rules[0]);
  2091. },
  2092. visitMediaOut: function (mediaNode) {
  2093. this.context.frames.shift();
  2094. }
  2095. };
  2096. class SetTreeVisibilityVisitor {
  2097. /** @param {boolean} visible */
  2098. constructor(visible) {
  2099. this.visible = visible;
  2100. }
  2101. /** @param {Node} root */
  2102. run(root) {
  2103. this.visit(root);
  2104. }
  2105. /**
  2106. * @param {Node[]} nodes
  2107. * @returns {Node[]}
  2108. */
  2109. visitArray(nodes) {
  2110. if (!nodes) {
  2111. return nodes;
  2112. }
  2113. const cnt = nodes.length;
  2114. let i;
  2115. for (i = 0; i < cnt; i++) {
  2116. this.visit(nodes[i]);
  2117. }
  2118. return nodes;
  2119. }
  2120. /**
  2121. * @param {*} node
  2122. * @returns {*}
  2123. */
  2124. visit(node) {
  2125. if (!node) {
  2126. return node;
  2127. }
  2128. if (node.constructor === Array) {
  2129. return this.visitArray(node);
  2130. }
  2131. if (!node.blocksVisibility || node.blocksVisibility()) {
  2132. return node;
  2133. }
  2134. if (this.visible) {
  2135. node.ensureVisibility();
  2136. } else {
  2137. node.ensureInvisibility();
  2138. }
  2139. node.accept(this);
  2140. return node;
  2141. }
  2142. }
  2143. /* eslint-disable no-unused-vars */
  2144. /* jshint loopfunc:true */
  2145. class ExtendFinderVisitor {
  2146. constructor() {
  2147. this._visitor = new Visitor(this);
  2148. this.contexts = [];
  2149. this.allExtendsStack = [[]];
  2150. }
  2151. run(root) {
  2152. root = this._visitor.visit(root);
  2153. root.allExtends = this.allExtendsStack[0];
  2154. return root;
  2155. }
  2156. visitDeclaration(declNode, visitArgs) {
  2157. visitArgs.visitDeeper = false;
  2158. }
  2159. visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  2160. visitArgs.visitDeeper = false;
  2161. }
  2162. visitRuleset(rulesetNode, visitArgs) {
  2163. if (rulesetNode.root) {
  2164. return;
  2165. }
  2166. let i;
  2167. let j;
  2168. let extend;
  2169. const allSelectorsExtendList = [];
  2170. let extendList;
  2171. // get &:extend(.a); rules which apply to all selectors in this ruleset
  2172. const rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0;
  2173. for (i = 0; i < ruleCnt; i++) {
  2174. if (rulesetNode.rules[i] instanceof tree.Extend) {
  2175. allSelectorsExtendList.push(rules[i]);
  2176. rulesetNode.extendOnEveryPath = true;
  2177. }
  2178. }
  2179. // now find every selector and apply the extends that apply to all extends
  2180. // and the ones which apply to an individual extend
  2181. const paths = rulesetNode.paths;
  2182. for (i = 0; i < paths.length; i++) {
  2183. const selectorPath = paths[i], selector = selectorPath[selectorPath.length - 1], selExtendList = selector.extendList;
  2184. extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList)
  2185. : allSelectorsExtendList;
  2186. if (extendList) {
  2187. extendList = extendList.map(function(allSelectorsExtend) {
  2188. return allSelectorsExtend.clone();
  2189. });
  2190. }
  2191. for (j = 0; j < extendList.length; j++) {
  2192. this.foundExtends = true;
  2193. extend = extendList[j];
  2194. extend.findSelfSelectors(selectorPath);
  2195. extend.ruleset = rulesetNode;
  2196. if (j === 0) { extend.firstExtendOnThisSelectorPath = true; }
  2197. this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
  2198. }
  2199. }
  2200. this.contexts.push(rulesetNode.selectors);
  2201. }
  2202. visitRulesetOut(rulesetNode) {
  2203. if (!rulesetNode.root) {
  2204. this.contexts.length = this.contexts.length - 1;
  2205. }
  2206. }
  2207. visitMedia(mediaNode, visitArgs) {
  2208. mediaNode.allExtends = [];
  2209. this.allExtendsStack.push(mediaNode.allExtends);
  2210. }
  2211. visitMediaOut(mediaNode) {
  2212. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  2213. }
  2214. visitAtRule(atRuleNode, visitArgs) {
  2215. atRuleNode.allExtends = [];
  2216. this.allExtendsStack.push(atRuleNode.allExtends);
  2217. }
  2218. visitAtRuleOut(atRuleNode) {
  2219. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  2220. }
  2221. }
  2222. class ProcessExtendsVisitor {
  2223. constructor() {
  2224. this._visitor = new Visitor(this);
  2225. }
  2226. run(root) {
  2227. const extendFinder = new ExtendFinderVisitor();
  2228. this.extendIndices = {};
  2229. extendFinder.run(root);
  2230. if (!extendFinder.foundExtends) { return root; }
  2231. root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
  2232. this.allExtendsStack = [root.allExtends];
  2233. const newRoot = this._visitor.visit(root);
  2234. this.checkExtendsForNonMatched(root.allExtends);
  2235. return newRoot;
  2236. }
  2237. checkExtendsForNonMatched(extendList) {
  2238. const indices = this.extendIndices;
  2239. extendList.filter(function(extend) {
  2240. return !extend.hasFoundMatches && extend.parent_ids.length == 1;
  2241. }).forEach(function(extend) {
  2242. let selector = '_unknown_';
  2243. try {
  2244. selector = extend.selector.toCSS({});
  2245. }
  2246. catch (_) {}
  2247. if (!indices[`${extend.index} ${selector}`]) {
  2248. indices[`${extend.index} ${selector}`] = true;
  2249. /**
  2250. * @todo Shouldn't this be an error? To alert the developer
  2251. * that they may have made an error in the selector they are
  2252. * targeting?
  2253. */
  2254. logger.warn(`WARNING: extend '${selector}' has no matches`);
  2255. }
  2256. });
  2257. }
  2258. doExtendChaining(extendsList, extendsListTarget, iterationCount) {
  2259. //
  2260. // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
  2261. // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
  2262. // this means this new extend can then go and alter other extends
  2263. //
  2264. // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
  2265. // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
  2266. // processed if we look at each selector at a time, as is done in visitRuleset
  2267. let extendIndex;
  2268. let targetExtendIndex;
  2269. let matches;
  2270. const extendsToAdd = [];
  2271. let newSelector;
  2272. const extendVisitor = this;
  2273. let selectorPath;
  2274. let extend;
  2275. let targetExtend;
  2276. let newExtend;
  2277. iterationCount = iterationCount || 0;
  2278. // loop through comparing every extend with every target extend.
  2279. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
  2280. // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
  2281. // and the second is the target.
  2282. // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
  2283. // case when processing media queries
  2284. for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
  2285. for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
  2286. extend = extendsList[extendIndex];
  2287. targetExtend = extendsListTarget[targetExtendIndex];
  2288. // look for circular references
  2289. if ( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ) { continue; }
  2290. // find a match in the target extends self selector (the bit before :extend)
  2291. selectorPath = [targetExtend.selfSelectors[0]];
  2292. matches = extendVisitor.findMatch(extend, selectorPath);
  2293. if (matches.length) {
  2294. extend.hasFoundMatches = true;
  2295. // we found a match, so for each self selector..
  2296. extend.selfSelectors.forEach(function(selfSelector) {
  2297. const info = targetExtend.visibilityInfo();
  2298. // process the extend as usual
  2299. newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible());
  2300. // but now we create a new extend from it
  2301. newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
  2302. newExtend.selfSelectors = newSelector;
  2303. // add the extend onto the list of extends for that selector
  2304. newSelector[newSelector.length - 1].extendList = [newExtend];
  2305. // record that we need to add it.
  2306. extendsToAdd.push(newExtend);
  2307. newExtend.ruleset = targetExtend.ruleset;
  2308. // remember its parents for circular references
  2309. newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
  2310. // only process the selector once.. if we have :extend(.a,.b) then multiple
  2311. // extends will look at the same selector path, so when extending
  2312. // we know that any others will be duplicates in terms of what is added to the css
  2313. if (targetExtend.firstExtendOnThisSelectorPath) {
  2314. newExtend.firstExtendOnThisSelectorPath = true;
  2315. targetExtend.ruleset.paths.push(newSelector);
  2316. }
  2317. });
  2318. }
  2319. }
  2320. }
  2321. if (extendsToAdd.length) {
  2322. // try to detect circular references to stop a stack overflow.
  2323. // may no longer be needed.
  2324. this.extendChainCount++;
  2325. if (iterationCount > 100) {
  2326. let selectorOne = '{unable to calculate}';
  2327. let selectorTwo = '{unable to calculate}';
  2328. try {
  2329. selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
  2330. selectorTwo = extendsToAdd[0].selector.toCSS();
  2331. }
  2332. catch (e) {}
  2333. throw { message: `extend circular reference detected. One of the circular extends is currently:${selectorOne}:extend(${selectorTwo})`};
  2334. }
  2335. // now process the new extends on the existing rules so that we can handle a extending b extending c extending
  2336. // d extending e...
  2337. return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
  2338. } else {
  2339. return extendsToAdd;
  2340. }
  2341. }
  2342. visitDeclaration(ruleNode, visitArgs) {
  2343. visitArgs.visitDeeper = false;
  2344. }
  2345. visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  2346. visitArgs.visitDeeper = false;
  2347. }
  2348. visitSelector(selectorNode, visitArgs) {
  2349. visitArgs.visitDeeper = false;
  2350. }
  2351. visitRuleset(rulesetNode, visitArgs) {
  2352. if (rulesetNode.root) {
  2353. return;
  2354. }
  2355. let matches;
  2356. const allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
  2357. const selectorsToAdd = [];
  2358. const paths = rulesetNode.paths;
  2359. const pathCount = paths.length;
  2360. // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
  2361. for (let extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
  2362. const extend = allExtends[extendIndex];
  2363. for (let pathIndex = 0; pathIndex < pathCount; pathIndex++) {
  2364. const selectorPath = paths[pathIndex];
  2365. // extending extends happens initially, before the main pass
  2366. if (rulesetNode.extendOnEveryPath) { continue; }
  2367. const extendList = selectorPath[selectorPath.length - 1].extendList;
  2368. if (extendList && extendList.length) { continue; }
  2369. matches = this.findMatch(extend, selectorPath);
  2370. if (matches.length) {
  2371. extend.hasFoundMatches = true;
  2372. const selfSelectors = extend.selfSelectors;
  2373. const isVisible = extend.isVisible();
  2374. for (let si = 0; si < selfSelectors.length; si++) {
  2375. selectorsToAdd.push(this.extendSelector(matches, selectorPath, selfSelectors[si], isVisible));
  2376. }
  2377. }
  2378. }
  2379. }
  2380. rulesetNode.paths = paths.concat(selectorsToAdd);
  2381. }
  2382. findMatch(extend, haystackSelectorPath) {
  2383. //
  2384. // look through the haystack selector path to try and find the needle - extend.selector
  2385. // returns an array of selector matches that can then be replaced
  2386. //
  2387. let haystackSelectorIndex;
  2388. let hackstackSelector;
  2389. let hackstackElementIndex;
  2390. let haystackElement;
  2391. let targetCombinator;
  2392. let i;
  2393. const needleElements = extend.selector.elements;
  2394. const potentialMatches = [];
  2395. let potentialMatch;
  2396. const matches = [];
  2397. // loop through the haystack elements
  2398. for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
  2399. hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
  2400. for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
  2401. haystackElement = hackstackSelector.elements[hackstackElementIndex];
  2402. // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
  2403. if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
  2404. potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0,
  2405. initialCombinator: haystackElement.combinator});
  2406. }
  2407. for (i = 0; i < potentialMatches.length; i++) {
  2408. potentialMatch = potentialMatches[i];
  2409. // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
  2410. // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
  2411. // work out what the resulting combinator will be
  2412. targetCombinator = haystackElement.combinator.value;
  2413. if (targetCombinator === '' && hackstackElementIndex === 0) {
  2414. targetCombinator = ' ';
  2415. }
  2416. // if we don't match, null our match to indicate failure
  2417. if (!this.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
  2418. (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
  2419. potentialMatch = null;
  2420. } else {
  2421. potentialMatch.matched++;
  2422. }
  2423. // if we are still valid and have finished, test whether we have elements after and whether these are allowed
  2424. if (potentialMatch) {
  2425. potentialMatch.finished = potentialMatch.matched === needleElements.length;
  2426. if (potentialMatch.finished &&
  2427. (!extend.allowAfter &&
  2428. (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) {
  2429. potentialMatch = null;
  2430. }
  2431. }
  2432. // if null we remove, if not, we are still valid, so either push as a valid match or continue
  2433. if (potentialMatch) {
  2434. if (potentialMatch.finished) {
  2435. potentialMatch.length = needleElements.length;
  2436. potentialMatch.endPathIndex = haystackSelectorIndex;
  2437. potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
  2438. potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
  2439. matches.push(potentialMatch);
  2440. }
  2441. } else {
  2442. potentialMatches.splice(i, 1);
  2443. i--;
  2444. }
  2445. }
  2446. }
  2447. }
  2448. return matches;
  2449. }
  2450. isElementValuesEqual(elementValue1, elementValue2) {
  2451. if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
  2452. return elementValue1 === elementValue2;
  2453. }
  2454. if (elementValue1 instanceof tree.Attribute) {
  2455. if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
  2456. return false;
  2457. }
  2458. if (!elementValue1.value || !elementValue2.value) {
  2459. if (elementValue1.value || elementValue2.value) {
  2460. return false;
  2461. }
  2462. return true;
  2463. }
  2464. elementValue1 = elementValue1.value.value || elementValue1.value;
  2465. elementValue2 = elementValue2.value.value || elementValue2.value;
  2466. return elementValue1 === elementValue2;
  2467. }
  2468. elementValue1 = elementValue1.value;
  2469. elementValue2 = elementValue2.value;
  2470. if (elementValue1 instanceof tree.Selector) {
  2471. if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
  2472. return false;
  2473. }
  2474. for (let i = 0; i < elementValue1.elements.length; i++) {
  2475. if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
  2476. if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
  2477. return false;
  2478. }
  2479. }
  2480. if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
  2481. return false;
  2482. }
  2483. }
  2484. return true;
  2485. }
  2486. return false;
  2487. }
  2488. extendSelector(matches, selectorPath, replacementSelector, isVisible) {
  2489. // for a set of matches, replace each match with the replacement selector
  2490. let currentSelectorPathIndex = 0, currentSelectorPathElementIndex = 0, path = [], matchIndex, selector, firstElement, match, newElements;
  2491. for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
  2492. match = matches[matchIndex];
  2493. selector = selectorPath[match.pathIndex];
  2494. firstElement = new tree.Element(
  2495. match.initialCombinator,
  2496. replacementSelector.elements[0].value,
  2497. replacementSelector.elements[0].isVariable,
  2498. replacementSelector.elements[0].getIndex(),
  2499. replacementSelector.elements[0].fileInfo()
  2500. );
  2501. if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
  2502. path[path.length - 1].elements = path[path.length - 1]
  2503. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  2504. currentSelectorPathElementIndex = 0;
  2505. currentSelectorPathIndex++;
  2506. }
  2507. newElements = selector.elements
  2508. .slice(currentSelectorPathElementIndex, match.index)
  2509. .concat([firstElement])
  2510. .concat(replacementSelector.elements.slice(1));
  2511. if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
  2512. path[path.length - 1].elements =
  2513. path[path.length - 1].elements.concat(newElements);
  2514. } else {
  2515. path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
  2516. path.push(new tree.Selector(
  2517. newElements
  2518. ));
  2519. }
  2520. currentSelectorPathIndex = match.endPathIndex;
  2521. currentSelectorPathElementIndex = match.endPathElementIndex;
  2522. if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
  2523. currentSelectorPathElementIndex = 0;
  2524. currentSelectorPathIndex++;
  2525. }
  2526. }
  2527. if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
  2528. path[path.length - 1].elements = path[path.length - 1]
  2529. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  2530. currentSelectorPathIndex++;
  2531. }
  2532. path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
  2533. path = path.map(function (currentValue) {
  2534. // we can re-use elements here, because the visibility property matters only for selectors
  2535. const derived = currentValue.createDerived(currentValue.elements);
  2536. if (isVisible) {
  2537. derived.ensureVisibility();
  2538. } else {
  2539. derived.ensureInvisibility();
  2540. }
  2541. return derived;
  2542. });
  2543. return path;
  2544. }
  2545. visitMedia(mediaNode, visitArgs) {
  2546. let newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  2547. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
  2548. this.allExtendsStack.push(newAllExtends);
  2549. }
  2550. visitMediaOut(mediaNode) {
  2551. const lastIndex = this.allExtendsStack.length - 1;
  2552. this.allExtendsStack.length = lastIndex;
  2553. }
  2554. visitAtRule(atRuleNode, visitArgs) {
  2555. let newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  2556. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
  2557. this.allExtendsStack.push(newAllExtends);
  2558. }
  2559. visitAtRuleOut(atRuleNode) {
  2560. const lastIndex = this.allExtendsStack.length - 1;
  2561. this.allExtendsStack.length = lastIndex;
  2562. }
  2563. }
  2564. /* eslint-disable no-unused-vars */
  2565. class JoinSelectorVisitor {
  2566. constructor() {
  2567. this.contexts = [[]];
  2568. this._visitor = new Visitor(this);
  2569. }
  2570. run(root) {
  2571. return this._visitor.visit(root);
  2572. }
  2573. visitDeclaration(declNode, visitArgs) {
  2574. visitArgs.visitDeeper = false;
  2575. }
  2576. visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  2577. visitArgs.visitDeeper = false;
  2578. }
  2579. visitRuleset(rulesetNode, visitArgs) {
  2580. const context = this.contexts[this.contexts.length - 1];
  2581. const paths = [];
  2582. let selectors;
  2583. this.contexts.push(paths);
  2584. if (!rulesetNode.root) {
  2585. selectors = rulesetNode.selectors;
  2586. if (selectors) {
  2587. selectors = selectors.filter(function(selector) { return selector.getIsOutput(); });
  2588. rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
  2589. if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); }
  2590. }
  2591. if (!selectors) { rulesetNode.rules = null; }
  2592. rulesetNode.paths = paths;
  2593. }
  2594. }
  2595. visitRulesetOut(rulesetNode) {
  2596. this.contexts.length = this.contexts.length - 1;
  2597. }
  2598. visitMedia(mediaNode, visitArgs) {
  2599. const context = this.contexts[this.contexts.length - 1];
  2600. mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
  2601. }
  2602. visitAtRule(atRuleNode, visitArgs) {
  2603. const context = this.contexts[this.contexts.length - 1];
  2604. if (atRuleNode.declarations && atRuleNode.declarations.length) {
  2605. atRuleNode.declarations[0].root = (context.length === 0 || context[0].multiMedia);
  2606. }
  2607. else if (atRuleNode.rules && atRuleNode.rules.length) {
  2608. atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);
  2609. }
  2610. }
  2611. }
  2612. // @ts-check
  2613. /**
  2614. * @typedef {object} DebugInfoData
  2615. * @property {number} lineNumber
  2616. * @property {string} fileName
  2617. */
  2618. /**
  2619. * @typedef {object} DebugInfoContext
  2620. * @property {DebugInfoData} debugInfo
  2621. */
  2622. /**
  2623. * @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead.
  2624. * This will be removed in a future version.
  2625. *
  2626. * @param {DebugInfoContext} ctx - Context object with debugInfo
  2627. * @returns {string} Debug info as CSS comment
  2628. */
  2629. function asComment(ctx) {
  2630. return `/* line ${ctx.debugInfo.lineNumber}, ${ctx.debugInfo.fileName} */\n`;
  2631. }
  2632. /**
  2633. * @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead.
  2634. * This function generates Sass-compatible debug info using @media -sass-debug-info syntax.
  2635. * This format had short-lived usage and is no longer recommended.
  2636. * This will be removed in a future version.
  2637. *
  2638. * @param {DebugInfoContext} ctx - Context object with debugInfo
  2639. * @returns {string} Sass-compatible debug info as @media query
  2640. */
  2641. function asMediaQuery(ctx) {
  2642. let filenameWithProtocol = ctx.debugInfo.fileName;
  2643. if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
  2644. filenameWithProtocol = `file://${filenameWithProtocol}`;
  2645. }
  2646. return `@media -sass-debug-info{filename{font-family:${filenameWithProtocol.replace(/([.:/\\])/g, function (a) {
  2647. if (a == '\\') {
  2648. a = '/';
  2649. }
  2650. return `\\${a}`;
  2651. })}}line{font-family:\\00003${ctx.debugInfo.lineNumber}}}\n`;
  2652. }
  2653. /**
  2654. * Generates debug information (line numbers) for CSS output.
  2655. *
  2656. * @param {{ dumpLineNumbers?: string, compress?: boolean }} context - Context object with dumpLineNumbers option
  2657. * @param {DebugInfoContext} ctx - Context object with debugInfo
  2658. * @param {string} [lineSeparator] - Separator between comment and media query (for 'all' mode)
  2659. * @returns {string} Debug info string
  2660. *
  2661. * @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead.
  2662. * All modes ('comments', 'mediaquery', 'all') are deprecated and will be removed in a future version.
  2663. * The 'mediaquery' and 'all' modes generate Sass-compatible @media -sass-debug-info output
  2664. * which had short-lived usage and is no longer recommended.
  2665. */
  2666. function debugInfo(context, ctx, lineSeparator) {
  2667. let result = '';
  2668. if (context.dumpLineNumbers && !context.compress) {
  2669. switch (context.dumpLineNumbers) {
  2670. case 'comments':
  2671. result = asComment(ctx);
  2672. break;
  2673. case 'mediaquery':
  2674. result = asMediaQuery(ctx);
  2675. break;
  2676. case 'all':
  2677. result = asComment(ctx) + (lineSeparator || '') + asMediaQuery(ctx);
  2678. break;
  2679. }
  2680. }
  2681. return result;
  2682. }
  2683. // @ts-check
  2684. class Comment extends Node {
  2685. get type() { return 'Comment'; }
  2686. /**
  2687. * @param {string} value
  2688. * @param {boolean} isLineComment
  2689. * @param {number} index
  2690. * @param {FileInfo} currentFileInfo
  2691. */
  2692. constructor(value, isLineComment, index, currentFileInfo) {
  2693. super();
  2694. this.value = value;
  2695. this.isLineComment = isLineComment;
  2696. this._index = index;
  2697. this._fileInfo = currentFileInfo;
  2698. this.allowRoot = true;
  2699. /** @type {{ lineNumber: number, fileName: string } | undefined} */
  2700. this.debugInfo = undefined;
  2701. }
  2702. /**
  2703. * @param {EvalContext} context
  2704. * @param {CSSOutput} output
  2705. */
  2706. genCSS(context, output) {
  2707. if (this.debugInfo) {
  2708. output.add(debugInfo(context, /** @type {DebugInfoContext} */ (this)), this.fileInfo(), this.getIndex());
  2709. }
  2710. output.add(/** @type {string} */ (this.value));
  2711. }
  2712. /**
  2713. * @param {EvalContext} context
  2714. * @returns {boolean}
  2715. */
  2716. isSilent(context) {
  2717. const isCompressed = context.compress && /** @type {string} */ (this.value)[2] !== '!';
  2718. return this.isLineComment || isCompressed;
  2719. }
  2720. }
  2721. // @ts-check
  2722. /** @import { EvalContext, CSSOutput } from './node.js' */
  2723. class Unit extends Node {
  2724. get type() { return 'Unit'; }
  2725. /**
  2726. * @param {string[]} [numerator]
  2727. * @param {string[]} [denominator]
  2728. * @param {string} [backupUnit]
  2729. */
  2730. constructor(numerator, denominator, backupUnit) {
  2731. super();
  2732. /** @type {string[]} */
  2733. this.numerator = numerator ? copyArray(numerator).sort() : [];
  2734. /** @type {string[]} */
  2735. this.denominator = denominator ? copyArray(denominator).sort() : [];
  2736. if (backupUnit) {
  2737. /** @type {string | undefined} */
  2738. this.backupUnit = backupUnit;
  2739. } else if (numerator && numerator.length) {
  2740. this.backupUnit = numerator[0];
  2741. }
  2742. }
  2743. clone() {
  2744. return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
  2745. }
  2746. /**
  2747. * @param {EvalContext} context
  2748. * @param {CSSOutput} output
  2749. */
  2750. genCSS(context, output) {
  2751. // Dimension checks the unit is singular and throws an error if in strict math mode.
  2752. const strictUnits = context && context.strictUnits;
  2753. if (this.numerator.length === 1) {
  2754. output.add(this.numerator[0]); // the ideal situation
  2755. } else if (!strictUnits && this.backupUnit) {
  2756. output.add(this.backupUnit);
  2757. } else if (!strictUnits && this.denominator.length) {
  2758. output.add(this.denominator[0]);
  2759. }
  2760. }
  2761. toString() {
  2762. let i, returnStr = this.numerator.join('*');
  2763. for (i = 0; i < this.denominator.length; i++) {
  2764. returnStr += `/${this.denominator[i]}`;
  2765. }
  2766. return returnStr;
  2767. }
  2768. /**
  2769. * @param {Unit} other
  2770. * @returns {0 | undefined}
  2771. */
  2772. compare(other) {
  2773. return this.is(other.toString()) ? 0 : undefined;
  2774. }
  2775. /** @param {string} unitString */
  2776. is(unitString) {
  2777. return this.toString().toUpperCase() === unitString.toUpperCase();
  2778. }
  2779. isLength() {
  2780. return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS(/** @type {import('./node.js').EvalContext} */ ({})));
  2781. }
  2782. isEmpty() {
  2783. return this.numerator.length === 0 && this.denominator.length === 0;
  2784. }
  2785. isSingular() {
  2786. return this.numerator.length <= 1 && this.denominator.length === 0;
  2787. }
  2788. /** @param {(atomicUnit: string, denominator: boolean) => string} callback */
  2789. map(callback) {
  2790. let i;
  2791. for (i = 0; i < this.numerator.length; i++) {
  2792. this.numerator[i] = callback(this.numerator[i], false);
  2793. }
  2794. for (i = 0; i < this.denominator.length; i++) {
  2795. this.denominator[i] = callback(this.denominator[i], true);
  2796. }
  2797. }
  2798. /** @returns {{ [groupName: string]: string }} */
  2799. usedUnits() {
  2800. /** @type {{ [unitName: string]: number }} */
  2801. let group;
  2802. /** @type {{ [groupName: string]: string }} */
  2803. const result = {};
  2804. /** @type {(atomicUnit: string) => string} */
  2805. let mapUnit;
  2806. /** @type {string} */
  2807. let groupName;
  2808. mapUnit = function (atomicUnit) {
  2809. // eslint-disable-next-line no-prototype-builtins
  2810. if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
  2811. result[groupName] = atomicUnit;
  2812. }
  2813. return atomicUnit;
  2814. };
  2815. for (groupName in unitConversions) {
  2816. // eslint-disable-next-line no-prototype-builtins
  2817. if (unitConversions.hasOwnProperty(groupName)) {
  2818. group = /** @type {{ [unitName: string]: number }} */ (unitConversions[/** @type {keyof typeof unitConversions} */ (groupName)]);
  2819. this.map(mapUnit);
  2820. }
  2821. }
  2822. return result;
  2823. }
  2824. cancel() {
  2825. /** @type {{ [unit: string]: number }} */
  2826. const counter = {};
  2827. /** @type {string} */
  2828. let atomicUnit;
  2829. let i;
  2830. for (i = 0; i < this.numerator.length; i++) {
  2831. atomicUnit = this.numerator[i];
  2832. counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
  2833. }
  2834. for (i = 0; i < this.denominator.length; i++) {
  2835. atomicUnit = this.denominator[i];
  2836. counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
  2837. }
  2838. this.numerator = [];
  2839. this.denominator = [];
  2840. for (atomicUnit in counter) {
  2841. // eslint-disable-next-line no-prototype-builtins
  2842. if (counter.hasOwnProperty(atomicUnit)) {
  2843. const count = counter[atomicUnit];
  2844. if (count > 0) {
  2845. for (i = 0; i < count; i++) {
  2846. this.numerator.push(atomicUnit);
  2847. }
  2848. } else if (count < 0) {
  2849. for (i = 0; i < -count; i++) {
  2850. this.denominator.push(atomicUnit);
  2851. }
  2852. }
  2853. }
  2854. }
  2855. this.numerator.sort();
  2856. this.denominator.sort();
  2857. }
  2858. }
  2859. // @ts-check
  2860. /** @import { EvalContext, CSSOutput } from './node.js' */
  2861. //
  2862. // A number with a unit
  2863. //
  2864. class Dimension extends Node {
  2865. get type() { return 'Dimension'; }
  2866. /**
  2867. * @param {number | string} value
  2868. * @param {Unit | string} [unit]
  2869. */
  2870. constructor(value, unit) {
  2871. super();
  2872. /** @type {number} */
  2873. this.value = parseFloat(/** @type {string} */ (value));
  2874. if (isNaN(this.value)) {
  2875. throw new Error('Dimension is not a number.');
  2876. }
  2877. /** @type {Unit} */
  2878. this.unit = (unit && unit instanceof Unit) ? unit :
  2879. new Unit(unit ? [/** @type {string} */ (unit)] : undefined);
  2880. this.setParent(this.unit, this);
  2881. }
  2882. /**
  2883. * @param {import('./node.js').TreeVisitor} visitor
  2884. */
  2885. accept(visitor) {
  2886. this.unit = /** @type {Unit} */ (visitor.visit(this.unit));
  2887. }
  2888. // remove when Nodes have JSDoc types
  2889. // eslint-disable-next-line no-unused-vars
  2890. /** @param {EvalContext} context */
  2891. eval(context) {
  2892. return this;
  2893. }
  2894. toColor() {
  2895. const v = /** @type {number} */ (this.value);
  2896. return new Color([v, v, v]);
  2897. }
  2898. /**
  2899. * @param {EvalContext} context
  2900. * @param {CSSOutput} output
  2901. */
  2902. genCSS(context, output) {
  2903. if ((context && context.strictUnits) && !this.unit.isSingular()) {
  2904. throw new Error(`Multiple units in dimension. Correct the units or use the unit function. Bad unit: ${this.unit.toString()}`);
  2905. }
  2906. const value = this.fround(context, /** @type {number} */ (this.value));
  2907. let strValue = String(value);
  2908. if (value !== 0 && value < 0.000001 && value > -0.000001) {
  2909. // would be output 1e-6 etc.
  2910. strValue = value.toFixed(20).replace(/0+$/, '');
  2911. }
  2912. if (context && context.compress) {
  2913. // Zero values doesn't need a unit
  2914. if (value === 0 && this.unit.isLength()) {
  2915. output.add(strValue);
  2916. return;
  2917. }
  2918. // Float values doesn't need a leading zero
  2919. if (value > 0 && value < 1) {
  2920. strValue = (strValue).slice(1);
  2921. }
  2922. }
  2923. output.add(strValue);
  2924. this.unit.genCSS(context, output);
  2925. }
  2926. // In an operation between two Dimensions,
  2927. // we default to the first Dimension's unit,
  2928. // so `1px + 2` will yield `3px`.
  2929. /**
  2930. * @param {EvalContext} context
  2931. * @param {string} op
  2932. * @param {Dimension} other
  2933. */
  2934. operate(context, op, other) {
  2935. /* jshint noempty:false */
  2936. let value = this._operate(context, op, /** @type {number} */ (this.value), /** @type {number} */ (other.value));
  2937. let unit = this.unit.clone();
  2938. if (op === '+' || op === '-') {
  2939. if (unit.numerator.length === 0 && unit.denominator.length === 0) {
  2940. unit = other.unit.clone();
  2941. if (this.unit.backupUnit) {
  2942. unit.backupUnit = this.unit.backupUnit;
  2943. }
  2944. } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ; else {
  2945. other = other.convertTo(this.unit.usedUnits());
  2946. if (context.strictUnits && other.unit.toString() !== unit.toString()) {
  2947. throw new Error('Incompatible units. Change the units or use the unit function. '
  2948. + `Bad units: '${unit.toString()}' and '${other.unit.toString()}'.`);
  2949. }
  2950. value = this._operate(context, op, /** @type {number} */ (this.value), /** @type {number} */ (other.value));
  2951. }
  2952. } else if (op === '*') {
  2953. unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
  2954. unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
  2955. unit.cancel();
  2956. } else if (op === '/') {
  2957. unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
  2958. unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
  2959. unit.cancel();
  2960. }
  2961. return new Dimension(/** @type {number} */ (value), unit);
  2962. }
  2963. /**
  2964. * @param {Node} other
  2965. * @returns {number | undefined}
  2966. */
  2967. compare(other) {
  2968. let a, b;
  2969. if (!(other instanceof Dimension)) {
  2970. return undefined;
  2971. }
  2972. if (this.unit.isEmpty() || other.unit.isEmpty()) {
  2973. a = this;
  2974. b = other;
  2975. } else {
  2976. a = this.unify();
  2977. b = other.unify();
  2978. if (a.unit.compare(b.unit) !== 0) {
  2979. return undefined;
  2980. }
  2981. }
  2982. return Node.numericCompare(/** @type {number} */ (a.value), /** @type {number} */ (b.value));
  2983. }
  2984. unify() {
  2985. return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
  2986. }
  2987. /**
  2988. * @param {string | { [groupName: string]: string }} conversions
  2989. * @returns {Dimension}
  2990. */
  2991. convertTo(conversions) {
  2992. let value = /** @type {number} */ (this.value);
  2993. const unit = this.unit.clone();
  2994. let i;
  2995. /** @type {string} */
  2996. let groupName;
  2997. /** @type {{ [unitName: string]: number }} */
  2998. let group;
  2999. /** @type {string} */
  3000. let targetUnit;
  3001. /** @type {{ [groupName: string]: string }} */
  3002. let derivedConversions = {};
  3003. /** @type {(atomicUnit: string, denominator: boolean) => string} */
  3004. let applyUnit;
  3005. if (typeof conversions === 'string') {
  3006. for (i in unitConversions) {
  3007. if (unitConversions[/** @type {keyof typeof unitConversions} */ (i)].hasOwnProperty(conversions)) {
  3008. derivedConversions = {};
  3009. derivedConversions[i] = conversions;
  3010. }
  3011. }
  3012. conversions = derivedConversions;
  3013. }
  3014. applyUnit = function (atomicUnit, denominator) {
  3015. if (group.hasOwnProperty(atomicUnit)) {
  3016. if (denominator) {
  3017. value = value / (group[atomicUnit] / group[targetUnit]);
  3018. } else {
  3019. value = value * (group[atomicUnit] / group[targetUnit]);
  3020. }
  3021. return targetUnit;
  3022. }
  3023. return atomicUnit;
  3024. };
  3025. for (groupName in conversions) {
  3026. if (conversions.hasOwnProperty(groupName)) {
  3027. targetUnit = conversions[groupName];
  3028. group = /** @type {{ [unitName: string]: number }} */ (unitConversions[/** @type {keyof typeof unitConversions} */ (groupName)]);
  3029. unit.map(applyUnit);
  3030. }
  3031. }
  3032. unit.cancel();
  3033. return new Dimension(value, unit);
  3034. }
  3035. }
  3036. // @ts-check
  3037. class Anonymous extends Node {
  3038. get type() { return 'Anonymous'; }
  3039. /**
  3040. * @param {string | null} value
  3041. * @param {number} [index]
  3042. * @param {FileInfo} [currentFileInfo]
  3043. * @param {boolean} [mapLines]
  3044. * @param {boolean} [rulesetLike]
  3045. * @param {VisibilityInfo} [visibilityInfo]
  3046. */
  3047. constructor(value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
  3048. super();
  3049. this.value = value;
  3050. this._index = index;
  3051. this._fileInfo = currentFileInfo;
  3052. this.mapLines = mapLines;
  3053. this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
  3054. this.allowRoot = true;
  3055. this.copyVisibilityInfo(visibilityInfo);
  3056. }
  3057. /** @returns {Anonymous} */
  3058. eval() {
  3059. return new Anonymous(/** @type {string | null} */ (this.value), this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
  3060. }
  3061. /**
  3062. * @param {Node} other
  3063. * @returns {number | undefined}
  3064. */
  3065. compare(other) {
  3066. return other.toCSS && this.toCSS(/** @type {EvalContext} */ ({})) === other.toCSS(/** @type {EvalContext} */ ({})) ? 0 : undefined;
  3067. }
  3068. /** @returns {boolean} */
  3069. isRulesetLike() {
  3070. return this.rulesetLike;
  3071. }
  3072. /**
  3073. * @param {EvalContext} context
  3074. * @param {CSSOutput} output
  3075. */
  3076. genCSS(context, output) {
  3077. this.nodeVisible = Boolean(this.value);
  3078. if (this.nodeVisible) {
  3079. output.add(/** @type {string} */ (this.value), this._fileInfo, this._index, this.mapLines);
  3080. }
  3081. }
  3082. }
  3083. // @ts-check
  3084. class Expression extends Node {
  3085. get type() { return 'Expression'; }
  3086. /**
  3087. * @param {Node[]} value
  3088. * @param {boolean} [noSpacing]
  3089. */
  3090. constructor(value, noSpacing) {
  3091. super();
  3092. this.value = value;
  3093. /** @type {boolean | undefined} */
  3094. this.noSpacing = noSpacing;
  3095. /** @type {boolean | undefined} */
  3096. this.parens = undefined;
  3097. /** @type {boolean | undefined} */
  3098. this.parensInOp = undefined;
  3099. if (!value) {
  3100. throw new Error('Expression requires an array parameter');
  3101. }
  3102. }
  3103. /** @param {TreeVisitor} visitor */
  3104. accept(visitor) {
  3105. this.value = visitor.visitArray(/** @type {Node[]} */ (this.value));
  3106. }
  3107. /** @param {EvalContext} context */
  3108. eval(context) {
  3109. const noSpacing = this.noSpacing;
  3110. /** @type {Node | Expression} */
  3111. let returnValue;
  3112. const mathOn = context.isMathOn();
  3113. const inParenthesis = this.parens;
  3114. let doubleParen = false;
  3115. if (inParenthesis) {
  3116. context.inParenthesis();
  3117. }
  3118. const value = /** @type {Node[]} */ (this.value);
  3119. if (value.length > 1) {
  3120. returnValue = new Expression(value.map(function (e) {
  3121. if (!e.eval) {
  3122. return e;
  3123. }
  3124. return e.eval(context);
  3125. }), this.noSpacing);
  3126. } else if (value.length === 1) {
  3127. const first = /** @type {Expression} */ (value[0]);
  3128. if (first.parens && !first.parensInOp && !context.inCalc) {
  3129. doubleParen = true;
  3130. }
  3131. returnValue = value[0].eval(context);
  3132. } else {
  3133. returnValue = this;
  3134. }
  3135. if (inParenthesis) {
  3136. context.outOfParenthesis();
  3137. }
  3138. if (this.parens && this.parensInOp && !mathOn && !doubleParen
  3139. && (!(returnValue instanceof Dimension))) {
  3140. returnValue = new Paren(returnValue);
  3141. }
  3142. /** @type {Expression} */ (returnValue).noSpacing =
  3143. /** @type {Expression} */ (returnValue).noSpacing || noSpacing;
  3144. return returnValue;
  3145. }
  3146. /**
  3147. * @param {EvalContext} context
  3148. * @param {CSSOutput} output
  3149. */
  3150. genCSS(context, output) {
  3151. const value = /** @type {Node[]} */ (this.value);
  3152. for (let i = 0; i < value.length; i++) {
  3153. value[i].genCSS(context, output);
  3154. if (!this.noSpacing && i + 1 < value.length) {
  3155. if (!(value[i + 1] instanceof Anonymous) ||
  3156. value[i + 1] instanceof Anonymous && /** @type {string} */ (value[i + 1].value) !== ',') {
  3157. output.add(' ');
  3158. }
  3159. }
  3160. }
  3161. }
  3162. throwAwayComments() {
  3163. this.value = /** @type {Node[]} */ (this.value).filter(function(v) {
  3164. return !(v instanceof Comment);
  3165. });
  3166. }
  3167. }
  3168. // @ts-check
  3169. class Value extends Node {
  3170. get type() { return 'Value'; }
  3171. /** @param {Node[] | Node} value */
  3172. constructor(value) {
  3173. super();
  3174. if (!value) {
  3175. throw new Error('Value requires an array argument');
  3176. }
  3177. if (!Array.isArray(value)) {
  3178. this.value = [ value ];
  3179. }
  3180. else {
  3181. this.value = value;
  3182. }
  3183. }
  3184. /** @param {TreeVisitor} visitor */
  3185. accept(visitor) {
  3186. if (this.value) {
  3187. this.value = visitor.visitArray(/** @type {Node[]} */ (this.value));
  3188. }
  3189. }
  3190. /**
  3191. * @param {EvalContext} context
  3192. * @returns {Node}
  3193. */
  3194. eval(context) {
  3195. const value = /** @type {Node[]} */ (this.value);
  3196. if (value.length === 1) {
  3197. return value[0].eval(context);
  3198. } else {
  3199. return new Value(value.map(function (v) {
  3200. return v.eval(context);
  3201. }));
  3202. }
  3203. }
  3204. /**
  3205. * @param {EvalContext} context
  3206. * @param {CSSOutput} output
  3207. */
  3208. genCSS(context, output) {
  3209. const value = /** @type {Node[]} */ (this.value);
  3210. let i;
  3211. for (i = 0; i < value.length; i++) {
  3212. value[i].genCSS(context, output);
  3213. if (i + 1 < value.length) {
  3214. output.add((context && context.compress) ? ',' : ', ');
  3215. }
  3216. }
  3217. }
  3218. }
  3219. // @ts-check
  3220. /**
  3221. * Merges declarations with merge flags (+ or ,) into combined values.
  3222. * Used by both the ToCSSVisitor and AtRule eval.
  3223. * @param {Node[]} rules
  3224. */
  3225. function mergeRules(rules) {
  3226. if (!rules) {
  3227. return;
  3228. }
  3229. /** @type {Record<string, Array<Node & { merge: string, name: string, value: Node, important: string }>>} */
  3230. const groups = {};
  3231. /** @type {Array<Array<Node & { merge: string, name: string, value: Node, important: string }>>} */
  3232. const groupsArr = [];
  3233. for (let i = 0; i < rules.length; i++) {
  3234. const rule = /** @type {Node & { merge: string, name: string }} */ (rules[i]);
  3235. if (rule.merge) {
  3236. const key = rule.name;
  3237. groups[key] ? rules.splice(i--, 1) :
  3238. groupsArr.push(groups[key] = []);
  3239. groups[key].push(/** @type {Node & { merge: string, name: string, value: Node, important: string }} */ (rule));
  3240. }
  3241. }
  3242. groupsArr.forEach(group => {
  3243. if (group.length > 0) {
  3244. const result = group[0];
  3245. /** @type {Node[]} */
  3246. let space = [];
  3247. const comma = [new Expression(space)];
  3248. group.forEach(rule => {
  3249. if ((rule.merge === '+') && (space.length > 0)) {
  3250. comma.push(new Expression(space = []));
  3251. }
  3252. space.push(rule.value);
  3253. result.important = result.important || rule.important;
  3254. });
  3255. result.value = new Value(comma);
  3256. }
  3257. });
  3258. }
  3259. /* eslint-disable no-unused-vars */
  3260. class CSSVisitorUtils {
  3261. constructor(context) {
  3262. this._visitor = new Visitor(this);
  3263. this._context = context;
  3264. }
  3265. containsSilentNonBlockedChild(bodyRules) {
  3266. let rule;
  3267. if (!bodyRules) {
  3268. return false;
  3269. }
  3270. for (let r = 0; r < bodyRules.length; r++) {
  3271. rule = bodyRules[r];
  3272. if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
  3273. // the atrule contains something that was referenced (likely by extend)
  3274. // therefore it needs to be shown in output too
  3275. return true;
  3276. }
  3277. }
  3278. return false;
  3279. }
  3280. keepOnlyVisibleChilds(owner) {
  3281. if (owner && owner.rules) {
  3282. owner.rules = owner.rules.filter(thing => thing.isVisible());
  3283. }
  3284. }
  3285. isEmpty(owner) {
  3286. return (owner && owner.rules)
  3287. ? (owner.rules.length === 0) : true;
  3288. }
  3289. hasVisibleSelector(rulesetNode) {
  3290. return (rulesetNode && rulesetNode.paths)
  3291. ? (rulesetNode.paths.length > 0) : false;
  3292. }
  3293. resolveVisibility(node) {
  3294. if (!node.blocksVisibility()) {
  3295. if (this.isEmpty(node)) {
  3296. return ;
  3297. }
  3298. return node;
  3299. }
  3300. const compiledRulesBody = node.rules[0];
  3301. this.keepOnlyVisibleChilds(compiledRulesBody);
  3302. if (this.isEmpty(compiledRulesBody)) {
  3303. return ;
  3304. }
  3305. node.ensureVisibility();
  3306. node.removeVisibilityBlock();
  3307. return node;
  3308. }
  3309. isVisibleRuleset(rulesetNode) {
  3310. if (rulesetNode.firstRoot) {
  3311. return true;
  3312. }
  3313. if (this.isEmpty(rulesetNode)) {
  3314. return false;
  3315. }
  3316. if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
  3317. return false;
  3318. }
  3319. return true;
  3320. }
  3321. }
  3322. const ToCSSVisitor = function(context) {
  3323. this._visitor = new Visitor(this);
  3324. this._context = context;
  3325. this.utils = new CSSVisitorUtils(context);
  3326. };
  3327. ToCSSVisitor.prototype = {
  3328. isReplacing: true,
  3329. run: function (root) {
  3330. return this._visitor.visit(root);
  3331. },
  3332. visitDeclaration: function (declNode, visitArgs) {
  3333. if (declNode.blocksVisibility() || declNode.variable) {
  3334. return;
  3335. }
  3336. return declNode;
  3337. },
  3338. visitMixinDefinition: function (mixinNode, visitArgs) {
  3339. // mixin definitions do not get eval'd - this means they keep state
  3340. // so we have to clear that state here so it isn't used if toCSS is called twice
  3341. mixinNode.frames = [];
  3342. },
  3343. visitExtend: function (extendNode, visitArgs) {
  3344. },
  3345. visitComment: function (commentNode, visitArgs) {
  3346. if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
  3347. return;
  3348. }
  3349. return commentNode;
  3350. },
  3351. visitMedia: function(mediaNode, visitArgs) {
  3352. const originalRules = mediaNode.rules[0].rules;
  3353. mediaNode.accept(this._visitor);
  3354. visitArgs.visitDeeper = false;
  3355. return this.utils.resolveVisibility(mediaNode, originalRules);
  3356. },
  3357. visitImport: function (importNode, visitArgs) {
  3358. if (importNode.blocksVisibility()) {
  3359. return ;
  3360. }
  3361. return importNode;
  3362. },
  3363. visitAtRule: function(atRuleNode, visitArgs) {
  3364. if (atRuleNode.rules && atRuleNode.rules.length) {
  3365. return this.visitAtRuleWithBody(atRuleNode, visitArgs);
  3366. } else {
  3367. return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
  3368. }
  3369. },
  3370. visitAnonymous: function(anonymousNode, visitArgs) {
  3371. if (!anonymousNode.blocksVisibility()) {
  3372. anonymousNode.accept(this._visitor);
  3373. return anonymousNode;
  3374. }
  3375. },
  3376. visitAtRuleWithBody: function(atRuleNode, visitArgs) {
  3377. // if there is only one nested ruleset and that one has no path, then it is
  3378. // just fake ruleset
  3379. function hasFakeRuleset(atRuleNode) {
  3380. const bodyRules = atRuleNode.rules;
  3381. return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
  3382. }
  3383. function getBodyRules(atRuleNode) {
  3384. const nodeRules = atRuleNode.rules;
  3385. if (hasFakeRuleset(atRuleNode)) {
  3386. return nodeRules[0].rules;
  3387. }
  3388. return nodeRules;
  3389. }
  3390. // it is still true that it is only one ruleset in array
  3391. // this is last such moment
  3392. // process childs
  3393. const originalRules = getBodyRules(atRuleNode);
  3394. atRuleNode.accept(this._visitor);
  3395. visitArgs.visitDeeper = false;
  3396. if (!this.utils.isEmpty(atRuleNode)) {
  3397. this._mergeRules(atRuleNode.rules[0].rules);
  3398. }
  3399. return this.utils.resolveVisibility(atRuleNode, originalRules);
  3400. },
  3401. visitAtRuleWithoutBody: function(atRuleNode, visitArgs) {
  3402. if (atRuleNode.blocksVisibility()) {
  3403. return;
  3404. }
  3405. if (atRuleNode.name === '@charset') {
  3406. // Only output the debug info together with subsequent @charset definitions
  3407. // a comment (or @media statement) before the actual @charset atrule would
  3408. // be considered illegal css as it has to be on the first line
  3409. if (this.charset) {
  3410. if (atRuleNode.debugInfo) {
  3411. const comment = new tree.Comment(`/* ${atRuleNode.toCSS(this._context).replace(/\n/g, '')} */\n`);
  3412. comment.debugInfo = atRuleNode.debugInfo;
  3413. return this._visitor.visit(comment);
  3414. }
  3415. return;
  3416. }
  3417. this.charset = true;
  3418. }
  3419. return atRuleNode;
  3420. },
  3421. checkValidNodes: function(rules, isRoot) {
  3422. if (!rules) {
  3423. return;
  3424. }
  3425. for (let i = 0; i < rules.length; i++) {
  3426. const ruleNode = rules[i];
  3427. if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
  3428. throw { message: 'Properties must be inside selector blocks. They cannot be in the root',
  3429. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename};
  3430. }
  3431. if (ruleNode instanceof tree.Call) {
  3432. throw { message: `Function '${ruleNode.name}' did not return a root node`,
  3433. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename};
  3434. }
  3435. if (ruleNode.type && !ruleNode.allowRoot) {
  3436. throw { message: `${ruleNode.type} node returned by a function is not valid here`,
  3437. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename};
  3438. }
  3439. }
  3440. },
  3441. visitRuleset: function (rulesetNode, visitArgs) {
  3442. // at this point rulesets are nested into each other
  3443. let rule;
  3444. const rulesets = [];
  3445. this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
  3446. if (!rulesetNode.root) {
  3447. // remove invisible paths
  3448. this._compileRulesetPaths(rulesetNode);
  3449. // remove rulesets from this ruleset body and compile them separately
  3450. const nodeRules = rulesetNode.rules;
  3451. let nodeRuleCnt = nodeRules ? nodeRules.length : 0;
  3452. for (let i = 0; i < nodeRuleCnt; ) {
  3453. rule = nodeRules[i];
  3454. if (rule && rule.rules) {
  3455. // visit because we are moving them out from being a child
  3456. rulesets.push(this._visitor.visit(rule));
  3457. nodeRules.splice(i, 1);
  3458. nodeRuleCnt--;
  3459. continue;
  3460. }
  3461. i++;
  3462. }
  3463. // accept the visitor to remove rules and refactor itself
  3464. // then we can decide nogw whether we want it or not
  3465. // compile body
  3466. if (nodeRuleCnt > 0) {
  3467. rulesetNode.accept(this._visitor);
  3468. } else {
  3469. rulesetNode.rules = null;
  3470. }
  3471. visitArgs.visitDeeper = false;
  3472. } else { // if (! rulesetNode.root) {
  3473. rulesetNode.accept(this._visitor);
  3474. visitArgs.visitDeeper = false;
  3475. }
  3476. if (rulesetNode.rules) {
  3477. this._mergeRules(rulesetNode.rules);
  3478. this._removeDuplicateRules(rulesetNode.rules);
  3479. }
  3480. // now decide whether we keep the ruleset
  3481. if (this.utils.isVisibleRuleset(rulesetNode)) {
  3482. rulesetNode.ensureVisibility();
  3483. rulesets.splice(0, 0, rulesetNode);
  3484. }
  3485. if (rulesets.length === 1) {
  3486. return rulesets[0];
  3487. }
  3488. return rulesets;
  3489. },
  3490. _compileRulesetPaths: function(rulesetNode) {
  3491. if (rulesetNode.paths) {
  3492. rulesetNode.paths = rulesetNode.paths
  3493. .filter(p => {
  3494. let i;
  3495. if (p[0].elements[0].combinator.value === ' ') {
  3496. p[0].elements[0].combinator = new(tree.Combinator)('');
  3497. }
  3498. for (i = 0; i < p.length; i++) {
  3499. if (p[i].isVisible() && p[i].getIsOutput()) {
  3500. return true;
  3501. }
  3502. }
  3503. return false;
  3504. });
  3505. }
  3506. },
  3507. _removeDuplicateRules: function(rules) {
  3508. if (!rules) { return; }
  3509. // remove duplicates
  3510. const ruleCache = {};
  3511. for (let i = rules.length - 1; i >= 0 ; i--) {
  3512. let rule = rules[i];
  3513. if (rule instanceof tree.Declaration) {
  3514. if (!Object.prototype.hasOwnProperty.call(ruleCache, rule.name)) {
  3515. ruleCache[rule.name] = rule;
  3516. } else {
  3517. let ruleList = ruleCache[rule.name];
  3518. if (!Array.isArray(ruleList)) {
  3519. const prevRuleCSS = ruleList.toCSS(this._context);
  3520. ruleList = ruleCache[rule.name] = [prevRuleCSS];
  3521. }
  3522. const ruleCSS = rule.toCSS(this._context);
  3523. if (ruleList.indexOf(ruleCSS) !== -1) {
  3524. rules.splice(i, 1);
  3525. } else {
  3526. ruleList.push(ruleCSS);
  3527. }
  3528. }
  3529. }
  3530. }
  3531. },
  3532. _mergeRules: mergeRules
  3533. };
  3534. var visitors = {
  3535. Visitor,
  3536. ImportVisitor,
  3537. MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
  3538. ExtendVisitor: ProcessExtendsVisitor,
  3539. JoinSelectorVisitor,
  3540. ToCSSVisitor
  3541. };
  3542. var getParserInput = () => {
  3543. let // Less input string
  3544. input;
  3545. let // current chunk
  3546. j;
  3547. const // holds state for backtracking
  3548. saveStack = [];
  3549. let // furthest index the parser has gone to
  3550. furthest;
  3551. let // if this is furthest we got to, this is the probably cause
  3552. furthestPossibleErrorMessage;
  3553. let // chunkified input
  3554. chunks;
  3555. let // current chunk
  3556. current;
  3557. let // index of current chunk, in `input`
  3558. currentPos;
  3559. const parserInput = {};
  3560. const CHARCODE_SPACE = 32;
  3561. const CHARCODE_TAB = 9;
  3562. const CHARCODE_LF = 10;
  3563. const CHARCODE_CR = 13;
  3564. const CHARCODE_PLUS = 43;
  3565. const CHARCODE_COMMA = 44;
  3566. const CHARCODE_FORWARD_SLASH = 47;
  3567. const CHARCODE_9 = 57;
  3568. function skipWhitespace(length) {
  3569. const oldi = parserInput.i;
  3570. const oldj = j;
  3571. const curr = parserInput.i - currentPos;
  3572. const endIndex = parserInput.i + current.length - curr;
  3573. const mem = (parserInput.i += length);
  3574. const inp = input;
  3575. let c;
  3576. let nextChar;
  3577. let comment;
  3578. for (; parserInput.i < endIndex; parserInput.i++) {
  3579. c = inp.charCodeAt(parserInput.i);
  3580. if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
  3581. nextChar = inp.charAt(parserInput.i + 1);
  3582. if (nextChar === '/') {
  3583. comment = {index: parserInput.i, isLineComment: true};
  3584. let nextNewLine = inp.indexOf('\n', parserInput.i + 2);
  3585. if (nextNewLine < 0) {
  3586. nextNewLine = endIndex;
  3587. }
  3588. parserInput.i = nextNewLine;
  3589. comment.text = inp.slice(comment.index, parserInput.i);
  3590. parserInput.commentStore.push(comment);
  3591. continue;
  3592. } else if (nextChar === '*') {
  3593. const nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
  3594. if (nextStarSlash >= 0) {
  3595. comment = {
  3596. index: parserInput.i,
  3597. text: inp.slice(parserInput.i, nextStarSlash + 2),
  3598. isLineComment: false
  3599. };
  3600. parserInput.i += comment.text.length - 1;
  3601. parserInput.commentStore.push(comment);
  3602. continue;
  3603. }
  3604. }
  3605. break;
  3606. }
  3607. if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
  3608. break;
  3609. }
  3610. }
  3611. current = current.slice(length + parserInput.i - mem + curr);
  3612. currentPos = parserInput.i;
  3613. if (!current.length) {
  3614. if (j < chunks.length - 1) {
  3615. current = chunks[++j];
  3616. skipWhitespace(0); // skip space at the beginning of a chunk
  3617. return true; // things changed
  3618. }
  3619. parserInput.finished = true;
  3620. }
  3621. return oldi !== parserInput.i || oldj !== j;
  3622. }
  3623. parserInput.save = () => {
  3624. currentPos = parserInput.i;
  3625. saveStack.push( { current, i: parserInput.i, j });
  3626. };
  3627. parserInput.restore = possibleErrorMessage => {
  3628. if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
  3629. furthest = parserInput.i;
  3630. furthestPossibleErrorMessage = possibleErrorMessage;
  3631. }
  3632. const state = saveStack.pop();
  3633. current = state.current;
  3634. currentPos = parserInput.i = state.i;
  3635. j = state.j;
  3636. };
  3637. parserInput.forget = () => {
  3638. saveStack.pop();
  3639. };
  3640. parserInput.isWhitespace = offset => {
  3641. const pos = parserInput.i + (offset || 0);
  3642. const code = input.charCodeAt(pos);
  3643. return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
  3644. };
  3645. // Specialization of $(tok)
  3646. parserInput.$re = tok => {
  3647. if (parserInput.i > currentPos) {
  3648. current = current.slice(parserInput.i - currentPos);
  3649. currentPos = parserInput.i;
  3650. }
  3651. const m = tok.exec(current);
  3652. if (!m) {
  3653. return null;
  3654. }
  3655. skipWhitespace(m[0].length);
  3656. if (typeof m === 'string') {
  3657. return m;
  3658. }
  3659. return m.length === 1 ? m[0] : m;
  3660. };
  3661. parserInput.$char = tok => {
  3662. if (input.charAt(parserInput.i) !== tok) {
  3663. return null;
  3664. }
  3665. skipWhitespace(1);
  3666. return tok;
  3667. };
  3668. parserInput.$peekChar = tok => {
  3669. if (input.charAt(parserInput.i) !== tok) {
  3670. return null;
  3671. }
  3672. return tok;
  3673. };
  3674. parserInput.$str = tok => {
  3675. const tokLength = tok.length;
  3676. // https://jsperf.com/string-startswith/21
  3677. for (let i = 0; i < tokLength; i++) {
  3678. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  3679. return null;
  3680. }
  3681. }
  3682. skipWhitespace(tokLength);
  3683. return tok;
  3684. };
  3685. parserInput.$quoted = loc => {
  3686. const pos = loc || parserInput.i;
  3687. const startChar = input.charAt(pos);
  3688. if (startChar !== '\'' && startChar !== '"') {
  3689. return;
  3690. }
  3691. const length = input.length;
  3692. const currentPosition = pos;
  3693. for (let i = 1; i + currentPosition < length; i++) {
  3694. const nextChar = input.charAt(i + currentPosition);
  3695. switch (nextChar) {
  3696. case '\\':
  3697. i++;
  3698. continue;
  3699. case '\r':
  3700. case '\n':
  3701. break;
  3702. case startChar: {
  3703. const str = input.slice(currentPosition, currentPosition + i + 1);
  3704. if (!loc && loc !== 0) {
  3705. skipWhitespace(i + 1);
  3706. return str
  3707. }
  3708. return [startChar, str];
  3709. }
  3710. }
  3711. }
  3712. return null;
  3713. };
  3714. /**
  3715. * Permissive parsing. Ignores everything except matching {} [] () and quotes
  3716. * until matching token (outside of blocks)
  3717. */
  3718. parserInput.$parseUntil = tok => {
  3719. let quote = '';
  3720. let returnVal = null;
  3721. let inComment = false;
  3722. let blockDepth = 0;
  3723. const blockStack = [];
  3724. const parseGroups = [];
  3725. const length = input.length;
  3726. const startPos = parserInput.i;
  3727. let lastPos = parserInput.i;
  3728. let i = parserInput.i;
  3729. let loop = true;
  3730. let testChar;
  3731. if (typeof tok === 'string') {
  3732. testChar = char => char === tok;
  3733. } else {
  3734. testChar = char => tok.test(char);
  3735. }
  3736. do {
  3737. let nextChar = input.charAt(i);
  3738. if (blockDepth === 0 && testChar(nextChar)) {
  3739. returnVal = input.slice(lastPos, i);
  3740. if (returnVal) {
  3741. parseGroups.push(returnVal);
  3742. }
  3743. else {
  3744. parseGroups.push(' ');
  3745. }
  3746. returnVal = parseGroups;
  3747. skipWhitespace(i - startPos);
  3748. loop = false;
  3749. } else {
  3750. if (inComment) {
  3751. if (nextChar === '*' &&
  3752. input.charAt(i + 1) === '/') {
  3753. i++;
  3754. blockDepth--;
  3755. inComment = false;
  3756. }
  3757. i++;
  3758. continue;
  3759. }
  3760. switch (nextChar) {
  3761. case '\\':
  3762. i++;
  3763. nextChar = input.charAt(i);
  3764. parseGroups.push(input.slice(lastPos, i + 1));
  3765. lastPos = i + 1;
  3766. break;
  3767. case '/':
  3768. if (input.charAt(i + 1) === '*') {
  3769. i++;
  3770. inComment = true;
  3771. blockDepth++;
  3772. }
  3773. break;
  3774. case '\'':
  3775. case '"':
  3776. quote = parserInput.$quoted(i);
  3777. if (quote) {
  3778. parseGroups.push(input.slice(lastPos, i), quote);
  3779. i += quote[1].length - 1;
  3780. lastPos = i + 1;
  3781. }
  3782. else {
  3783. skipWhitespace(i - startPos);
  3784. returnVal = nextChar;
  3785. loop = false;
  3786. }
  3787. break;
  3788. case '{':
  3789. blockStack.push('}');
  3790. blockDepth++;
  3791. break;
  3792. case '(':
  3793. blockStack.push(')');
  3794. blockDepth++;
  3795. break;
  3796. case '[':
  3797. blockStack.push(']');
  3798. blockDepth++;
  3799. break;
  3800. case '}':
  3801. case ')':
  3802. case ']': {
  3803. const expected = blockStack.pop();
  3804. if (nextChar === expected) {
  3805. blockDepth--;
  3806. } else {
  3807. // move the parser to the error and return expected
  3808. skipWhitespace(i - startPos);
  3809. returnVal = expected;
  3810. loop = false;
  3811. }
  3812. }
  3813. }
  3814. i++;
  3815. if (i > length) {
  3816. loop = false;
  3817. }
  3818. }
  3819. } while (loop);
  3820. return returnVal ? returnVal : null;
  3821. };
  3822. parserInput.autoCommentAbsorb = true;
  3823. parserInput.commentStore = [];
  3824. parserInput.finished = false;
  3825. // Same as $(), but don't change the state of the parser,
  3826. // just return the match.
  3827. parserInput.peek = tok => {
  3828. if (typeof tok === 'string') {
  3829. // https://jsperf.com/string-startswith/21
  3830. for (let i = 0; i < tok.length; i++) {
  3831. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  3832. return false;
  3833. }
  3834. }
  3835. return true;
  3836. } else {
  3837. return tok.test(current);
  3838. }
  3839. };
  3840. // Specialization of peek()
  3841. // TODO remove or change some currentChar calls to peekChar
  3842. parserInput.peekChar = tok => input.charAt(parserInput.i) === tok;
  3843. parserInput.currentChar = () => input.charAt(parserInput.i);
  3844. parserInput.prevChar = () => input.charAt(parserInput.i - 1);
  3845. parserInput.getInput = () => input;
  3846. parserInput.peekNotNumeric = () => {
  3847. const c = input.charCodeAt(parserInput.i);
  3848. // Is the first char of the dimension 0-9, '.', '+' or '-'
  3849. return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
  3850. };
  3851. parserInput.start = (str) => {
  3852. input = str;
  3853. parserInput.i = j = currentPos = furthest = 0;
  3854. chunks = [str];
  3855. current = chunks[0];
  3856. skipWhitespace(0);
  3857. };
  3858. parserInput.end = () => {
  3859. let message;
  3860. const isFinished = parserInput.i >= input.length;
  3861. if (parserInput.i < furthest) {
  3862. message = furthestPossibleErrorMessage;
  3863. parserInput.i = furthest;
  3864. }
  3865. return {
  3866. isFinished,
  3867. furthest: parserInput.i,
  3868. furthestPossibleErrorMessage: message,
  3869. furthestReachedEnd: parserInput.i >= input.length - 1,
  3870. furthestChar: input[parserInput.i]
  3871. };
  3872. };
  3873. return parserInput;
  3874. };
  3875. function makeRegistry( base ) {
  3876. return {
  3877. _data: {},
  3878. add: function(name, func) {
  3879. // precautionary case conversion, as later querying of
  3880. // the registry by function-caller uses lower case as well.
  3881. name = name.toLowerCase();
  3882. // eslint-disable-next-line no-prototype-builtins
  3883. if (this._data.hasOwnProperty(name)) ;
  3884. this._data[name] = func;
  3885. },
  3886. addMultiple: function(functions) {
  3887. Object.keys(functions).forEach(
  3888. name => {
  3889. this.add(name, functions[name]);
  3890. });
  3891. },
  3892. get: function(name) {
  3893. return this._data[name] || ( base && base.get( name ));
  3894. },
  3895. getLocalFunctions: function() {
  3896. return this._data;
  3897. },
  3898. inherit: function() {
  3899. return makeRegistry( this );
  3900. },
  3901. create: function(base) {
  3902. return makeRegistry(base);
  3903. }
  3904. };
  3905. }
  3906. var functionRegistry = makeRegistry( null );
  3907. // @ts-check
  3908. const MediaSyntaxOptions = {
  3909. queryInParens: true
  3910. };
  3911. const ContainerSyntaxOptions = {
  3912. queryInParens: true
  3913. };
  3914. /**
  3915. * Deprecation registry for Less.js
  3916. *
  3917. * Each deprecation has a unique ID and description.
  3918. * Repetition limiting caps warnings at 5 per deprecation type per parse.
  3919. * Use --quiet-deprecations to suppress all deprecation warnings.
  3920. */
  3921. const MAX_REPETITIONS = 5;
  3922. class DeprecationHandler {
  3923. constructor() {
  3924. /** @type {Record<string, number>} */
  3925. this._counts = {};
  3926. }
  3927. /** @param {string} deprecationId */
  3928. shouldWarn(deprecationId) {
  3929. if (!deprecationId) { return true; }
  3930. const count = (this._counts[deprecationId] || 0) + 1;
  3931. this._counts[deprecationId] = count;
  3932. return count <= MAX_REPETITIONS;
  3933. }
  3934. /** @param {{ warn: (msg: string) => void }} logger */
  3935. summarize(logger) {
  3936. for (const id of Object.keys(this._counts)) {
  3937. const omitted = this._counts[id] - MAX_REPETITIONS;
  3938. if (omitted > 0) {
  3939. logger.warn(`${omitted} repetitive "${id}" deprecation warning(s) omitted.`);
  3940. }
  3941. }
  3942. }
  3943. }
  3944. //
  3945. // less.js - parser
  3946. //
  3947. // A relatively straight-forward predictive parser.
  3948. // There is no tokenization/lexing stage, the input is parsed
  3949. // in one sweep.
  3950. //
  3951. // To make the parser fast enough to run in the browser, several
  3952. // optimization had to be made:
  3953. //
  3954. // - Matching and slicing on a huge input is often cause of slowdowns.
  3955. // The solution is to chunkify the input into smaller strings.
  3956. // The chunks are stored in the `chunks` var,
  3957. // `j` holds the current chunk index, and `currentPos` holds
  3958. // the index of the current chunk in relation to `input`.
  3959. // This gives us an almost 4x speed-up.
  3960. //
  3961. // - In many cases, we don't need to match individual tokens;
  3962. // for example, if a value doesn't hold any variables, operations
  3963. // or dynamic references, the parser can effectively 'skip' it,
  3964. // treating it as a literal.
  3965. // An example would be '1px solid #000' - which evaluates to itself,
  3966. // we don't need to know what the individual components are.
  3967. // The drawback, of course is that you don't get the benefits of
  3968. // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
  3969. // and a smaller speed-up in the code-gen.
  3970. //
  3971. //
  3972. // Token matching is done with the `$` function, which either takes
  3973. // a terminal string or regexp, or a non-terminal function to call.
  3974. // It also takes care of moving all the indices forwards.
  3975. //
  3976. const Parser = function Parser(context, imports, fileInfo, currentIndex) {
  3977. currentIndex = currentIndex || 0;
  3978. let parsers;
  3979. const parserInput = getParserInput();
  3980. function error(msg, type) {
  3981. throw new LessError(
  3982. {
  3983. index: parserInput.i,
  3984. filename: fileInfo.filename,
  3985. type: type || 'Syntax',
  3986. message: msg
  3987. },
  3988. imports
  3989. );
  3990. }
  3991. const deprecationHandler = new DeprecationHandler();
  3992. /**
  3993. * @param {string} msg
  3994. * @param {number} index
  3995. * @param {string} type
  3996. * @param {string} [deprecationId] - stable deprecation ID for repetition limiting
  3997. */
  3998. function warn(msg, index, type, deprecationId) {
  3999. if (context.quiet) { return; }
  4000. if (deprecationId && context.quietDeprecations) { return; }
  4001. if (deprecationId && !deprecationHandler.shouldWarn(deprecationId)) { return; }
  4002. logger.warn(
  4003. (new LessError(
  4004. {
  4005. index: index ?? parserInput.i,
  4006. filename: fileInfo.filename,
  4007. type: type ? `${type.toUpperCase()} WARNING` : 'WARNING',
  4008. message: msg
  4009. },
  4010. imports
  4011. )).toString()
  4012. );
  4013. }
  4014. function expect(arg, msg) {
  4015. // some older browsers return typeof 'function' for RegExp
  4016. const result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
  4017. if (result) {
  4018. return result;
  4019. }
  4020. error(msg || (typeof arg === 'string'
  4021. ? `expected '${arg}' got '${parserInput.currentChar()}'`
  4022. : 'unexpected token'));
  4023. }
  4024. // Specialization of expect()
  4025. function expectChar(arg, msg) {
  4026. if (parserInput.$char(arg)) {
  4027. return arg;
  4028. }
  4029. error(msg || `expected '${arg}' got '${parserInput.currentChar()}'`);
  4030. }
  4031. function getDebugInfo(index) {
  4032. const filename = fileInfo.filename;
  4033. return {
  4034. lineNumber: getLocation(index, parserInput.getInput()).line + 1,
  4035. fileName: filename
  4036. };
  4037. }
  4038. /**
  4039. * Used after initial parsing to create nodes on the fly
  4040. *
  4041. * @param {String} str - string to parse
  4042. * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
  4043. * @param {Number} currentIndex - start number to begin indexing
  4044. * @param {Object} fileInfo - fileInfo to attach to created nodes
  4045. */
  4046. function parseNode(str, parseList, callback) {
  4047. let result;
  4048. const returnNodes = [];
  4049. const parser = parserInput;
  4050. try {
  4051. parser.start(str);
  4052. for (let x = 0, p; (p = parseList[x]); x++) {
  4053. result = parsers[p]();
  4054. returnNodes.push(result || null);
  4055. }
  4056. const endInfo = parser.end();
  4057. if (endInfo.isFinished) {
  4058. callback(null, returnNodes);
  4059. }
  4060. else {
  4061. callback(true, null);
  4062. }
  4063. } catch (e) {
  4064. throw new LessError({
  4065. index: e.index + currentIndex,
  4066. message: e.message
  4067. }, imports, fileInfo.filename);
  4068. }
  4069. }
  4070. //
  4071. // The Parser
  4072. //
  4073. return {
  4074. parserInput,
  4075. imports,
  4076. fileInfo,
  4077. parseNode,
  4078. //
  4079. // Parse an input string into an abstract syntax tree,
  4080. // @param str A string containing 'less' markup
  4081. // @param callback call `callback` when done.
  4082. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
  4083. //
  4084. parse: function (str, callback, additionalData) {
  4085. let root;
  4086. let err = null;
  4087. let globalVars;
  4088. let modifyVars;
  4089. let ignored;
  4090. let preText = '';
  4091. // Optionally disable @plugin parsing
  4092. if (additionalData && additionalData.disablePluginRule) {
  4093. parsers.plugin = function() {
  4094. var dir = parserInput.$re(/^@plugin?\s+/);
  4095. if (dir) {
  4096. error('@plugin statements are not allowed when disablePluginRule is set to true');
  4097. }
  4098. };
  4099. }
  4100. globalVars = (additionalData && additionalData.globalVars) ? `${Parser.serializeVars(additionalData.globalVars)}\n` : '';
  4101. modifyVars = (additionalData && additionalData.modifyVars) ? `\n${Parser.serializeVars(additionalData.modifyVars)}` : '';
  4102. if (context.pluginManager) {
  4103. const preProcessors = context.pluginManager.getPreProcessors();
  4104. for (let i = 0; i < preProcessors.length; i++) {
  4105. str = preProcessors[i].process(str, { context, imports, fileInfo });
  4106. }
  4107. }
  4108. if (globalVars || (additionalData && additionalData.banner)) {
  4109. preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars;
  4110. ignored = imports.contentsIgnoredChars;
  4111. ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
  4112. ignored[fileInfo.filename] += preText.length;
  4113. }
  4114. str = str.replace(/\r\n?/g, '\n');
  4115. // Remove potential UTF Byte Order Mark
  4116. str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
  4117. imports.contents[fileInfo.filename] = str;
  4118. // Start with the primary rule.
  4119. // The whole syntax tree is held under a Ruleset node,
  4120. // with the `root` property set to true, so no `{}` are
  4121. // output. The callback is called when the input is parsed.
  4122. try {
  4123. parserInput.start(str);
  4124. tree.Node.prototype.parse = this;
  4125. root = new tree.Ruleset(null, this.parsers.primary());
  4126. tree.Node.prototype.rootNode = root;
  4127. root.root = true;
  4128. root.firstRoot = true;
  4129. root.functionRegistry = functionRegistry.inherit();
  4130. } catch (e) {
  4131. return callback(new LessError(e, imports, fileInfo.filename));
  4132. }
  4133. // If `i` is smaller than the `input.length - 1`,
  4134. // it means the parser wasn't able to parse the whole
  4135. // string, so we've got a parsing error.
  4136. //
  4137. // We try to extract a \n delimited string,
  4138. // showing the line where the parse error occurred.
  4139. // We split it up into two parts (the part which parsed,
  4140. // and the part which didn't), so we can color them differently.
  4141. const endInfo = parserInput.end();
  4142. if (!endInfo.isFinished) {
  4143. let message = endInfo.furthestPossibleErrorMessage;
  4144. if (!message) {
  4145. message = 'Unrecognised input';
  4146. if (endInfo.furthestChar === '}') {
  4147. message += '. Possibly missing opening \'{\'';
  4148. } else if (endInfo.furthestChar === ')') {
  4149. message += '. Possibly missing opening \'(\'';
  4150. } else if (endInfo.furthestReachedEnd) {
  4151. message += '. Possibly missing something';
  4152. }
  4153. }
  4154. err = new LessError({
  4155. type: 'Parse',
  4156. message,
  4157. index: endInfo.furthest,
  4158. filename: fileInfo.filename
  4159. }, imports);
  4160. }
  4161. const finish = e => {
  4162. e = err || e || imports.error;
  4163. if (e) {
  4164. if (!(e instanceof LessError)) {
  4165. e = new LessError(e, imports, fileInfo.filename);
  4166. }
  4167. return callback(e);
  4168. }
  4169. else {
  4170. return callback(null, root);
  4171. }
  4172. };
  4173. if (context.processImports !== false) {
  4174. new visitors.ImportVisitor(imports, finish)
  4175. .run(root);
  4176. } else {
  4177. return finish();
  4178. }
  4179. },
  4180. //
  4181. // Here in, the parsing rules/functions
  4182. //
  4183. // The basic structure of the syntax tree generated is as follows:
  4184. //
  4185. // Ruleset -> Declaration -> Value -> Expression -> Entity
  4186. //
  4187. // Here's some Less code:
  4188. //
  4189. // .class {
  4190. // color: #fff;
  4191. // border: 1px solid #000;
  4192. // width: @w + 4px;
  4193. // > .child {...}
  4194. // }
  4195. //
  4196. // And here's what the parse tree might look like:
  4197. //
  4198. // Ruleset (Selector '.class', [
  4199. // Declaration ("color", Value ([Expression [Color #fff]]))
  4200. // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
  4201. // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
  4202. // Ruleset (Selector [Element '>', '.child'], [...])
  4203. // ])
  4204. //
  4205. // In general, most rules will try to parse a token with the `$re()` function, and if the return
  4206. // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
  4207. // first, before parsing, that's when we use `peek()`.
  4208. //
  4209. parsers: parsers = {
  4210. //
  4211. // The `primary` rule is the *entry* and *exit* point of the parser.
  4212. // The rules here can appear at any level of the parse tree.
  4213. //
  4214. // The recursive nature of the grammar is an interplay between the `block`
  4215. // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
  4216. // as represented by this simplified grammar:
  4217. //
  4218. // primary → (ruleset | declaration)+
  4219. // ruleset → selector+ block
  4220. // block → '{' primary '}'
  4221. //
  4222. // Only at one point is the primary rule not called from the
  4223. // block rule: at the root level.
  4224. //
  4225. primary: function () {
  4226. const mixin = this.mixin;
  4227. let root = [];
  4228. let node;
  4229. while (true) {
  4230. while (true) {
  4231. node = this.comment();
  4232. if (!node) { break; }
  4233. root.push(node);
  4234. }
  4235. // always process comments before deciding if finished
  4236. if (parserInput.finished) {
  4237. break;
  4238. }
  4239. if (parserInput.peek('}')) {
  4240. break;
  4241. }
  4242. node = this.extendRule();
  4243. if (node) {
  4244. root = root.concat(node);
  4245. continue;
  4246. }
  4247. node = mixin.definition() || this.declaration() || mixin.call(false, false) ||
  4248. this.ruleset() || this.variableCall() || this.entities.call() || this.atrule();
  4249. if (node) {
  4250. root.push(node);
  4251. } else {
  4252. let foundSemiColon = false;
  4253. while (parserInput.$char(';')) {
  4254. foundSemiColon = true;
  4255. }
  4256. if (!foundSemiColon) {
  4257. break;
  4258. }
  4259. }
  4260. }
  4261. return root;
  4262. },
  4263. // comments are collected by the main parsing mechanism and then assigned to nodes
  4264. // where the current structure allows it
  4265. comment: function () {
  4266. if (parserInput.commentStore.length) {
  4267. const comment = parserInput.commentStore.shift();
  4268. return new(tree.Comment)(comment.text, comment.isLineComment, comment.index + currentIndex, fileInfo);
  4269. }
  4270. },
  4271. //
  4272. // Entities are tokens which can be found inside an Expression
  4273. //
  4274. entities: {
  4275. mixinLookup: function() {
  4276. return parsers.mixin.call(true, true);
  4277. },
  4278. //
  4279. // A string, which supports escaping " and '
  4280. //
  4281. // "milky way" 'he\'s the one!'
  4282. //
  4283. quoted: function (forceEscaped) {
  4284. let str;
  4285. const index = parserInput.i;
  4286. let isEscaped = false;
  4287. parserInput.save();
  4288. if (parserInput.$char('~')) {
  4289. isEscaped = true;
  4290. } else if (forceEscaped) {
  4291. parserInput.restore();
  4292. return;
  4293. }
  4294. str = parserInput.$quoted();
  4295. if (!str) {
  4296. parserInput.restore();
  4297. return;
  4298. }
  4299. parserInput.forget();
  4300. return new(tree.Quoted)(str.charAt(0), str.slice(1, -1), isEscaped, index + currentIndex, fileInfo);
  4301. },
  4302. //
  4303. // A catch-all word, such as:
  4304. //
  4305. // black border-collapse
  4306. //
  4307. keyword: function () {
  4308. const k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
  4309. if (k) {
  4310. return tree.Color.fromKeyword(k) || new(tree.Keyword)(k);
  4311. }
  4312. },
  4313. //
  4314. // A function call
  4315. //
  4316. // rgb(255, 0, 255)
  4317. //
  4318. // The arguments are parsed with the `entities.arguments` parser.
  4319. //
  4320. call: function () {
  4321. let name;
  4322. let args;
  4323. let func;
  4324. const index = parserInput.i;
  4325. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  4326. if (parserInput.peek(/^url\(/i)) {
  4327. return;
  4328. }
  4329. parserInput.save();
  4330. name = parserInput.$re(/^([\w-]+|%|~|progid:[\w.]+)\(/);
  4331. if (!name) {
  4332. parserInput.forget();
  4333. return;
  4334. }
  4335. name = name[1];
  4336. func = this.customFuncCall(name);
  4337. if (func) {
  4338. args = func.parse();
  4339. if (args && func.stop) {
  4340. parserInput.forget();
  4341. return args;
  4342. }
  4343. }
  4344. args = this.arguments(args);
  4345. if (!parserInput.$char(')')) {
  4346. parserInput.restore('Could not parse call arguments or missing \')\'');
  4347. return;
  4348. }
  4349. parserInput.forget();
  4350. return new(tree.Call)(name, args, index + currentIndex, fileInfo);
  4351. },
  4352. declarationCall: function () {
  4353. let validCall;
  4354. let args;
  4355. const index = parserInput.i;
  4356. parserInput.save();
  4357. validCall = parserInput.$re(/^[\w]+\(/);
  4358. if (!validCall) {
  4359. parserInput.forget();
  4360. return;
  4361. }
  4362. validCall = validCall.substring(0, validCall.length - 1);
  4363. // CSS at-rule keywords should never be parsed as declaration calls
  4364. if (/^(and|or|not|only|layer)$/i.test(validCall)) {
  4365. parserInput.restore();
  4366. return;
  4367. }
  4368. let rule = this.ruleProperty();
  4369. let value;
  4370. if (rule) {
  4371. value = this.value();
  4372. }
  4373. if (rule && value) {
  4374. args = [new (tree.Declaration)(rule, value, null, null, parserInput.i + currentIndex, fileInfo, true)];
  4375. }
  4376. if (!parserInput.$char(')')) {
  4377. parserInput.restore('Could not parse call arguments or missing \')\'');
  4378. return;
  4379. }
  4380. parserInput.forget();
  4381. return new(tree.Call)(validCall, args, index + currentIndex, fileInfo);
  4382. },
  4383. //
  4384. // Parsing rules for functions with non-standard args, e.g.:
  4385. //
  4386. // boolean(not(2 > 1))
  4387. //
  4388. // This is a quick prototype, to be modified/improved when
  4389. // more custom-parsed funcs come (e.g. `selector(...)`)
  4390. //
  4391. customFuncCall: function (name) {
  4392. /* Ideally the table is to be moved out of here for faster perf.,
  4393. but it's quite tricky since it relies on all these `parsers`
  4394. and `expect` available only here */
  4395. return {
  4396. alpha: f(parsers.ieAlpha, true),
  4397. boolean: f(condition),
  4398. 'if': f(condition)
  4399. }[name.toLowerCase()];
  4400. function f(parse, stop) {
  4401. return {
  4402. parse, // parsing function
  4403. stop // when true - stop after parse() and return its result,
  4404. // otherwise continue for plain args
  4405. };
  4406. }
  4407. function condition() {
  4408. return [expect(parsers.condition, 'expected condition')];
  4409. }
  4410. },
  4411. arguments: function (prevArgs) {
  4412. let argsComma = prevArgs || [];
  4413. const argsSemiColon = [];
  4414. let isSemiColonSeparated;
  4415. let value;
  4416. parserInput.save();
  4417. while (true) {
  4418. if (prevArgs) {
  4419. prevArgs = false;
  4420. } else {
  4421. value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
  4422. if (!value) {
  4423. break;
  4424. }
  4425. if (value.value && value.value.length == 1) {
  4426. value = value.value[0];
  4427. }
  4428. argsComma.push(value);
  4429. }
  4430. if (parserInput.$char(',')) {
  4431. continue;
  4432. }
  4433. if (parserInput.$char(';') || isSemiColonSeparated) {
  4434. isSemiColonSeparated = true;
  4435. value = (argsComma.length < 1) ? argsComma[0]
  4436. : new tree.Value(argsComma);
  4437. argsSemiColon.push(value);
  4438. argsComma = [];
  4439. }
  4440. }
  4441. parserInput.forget();
  4442. return isSemiColonSeparated ? argsSemiColon : argsComma;
  4443. },
  4444. literal: function () {
  4445. return this.dimension() ||
  4446. this.color() ||
  4447. this.quoted() ||
  4448. this.unicodeDescriptor();
  4449. },
  4450. // Assignments are argument entities for calls.
  4451. // They are present in ie filter properties as shown below.
  4452. //
  4453. // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
  4454. //
  4455. assignment: function () {
  4456. let key;
  4457. let value;
  4458. parserInput.save();
  4459. key = parserInput.$re(/^\w+(?=\s?=)/i);
  4460. if (!key) {
  4461. parserInput.restore();
  4462. return;
  4463. }
  4464. if (!parserInput.$char('=')) {
  4465. parserInput.restore();
  4466. return;
  4467. }
  4468. value = parsers.entity();
  4469. if (value) {
  4470. parserInput.forget();
  4471. return new(tree.Assignment)(key, value);
  4472. } else {
  4473. parserInput.restore();
  4474. }
  4475. },
  4476. //
  4477. // Parse url() tokens
  4478. //
  4479. // We use a specific rule for urls, because they don't really behave like
  4480. // standard function calls. The difference is that the argument doesn't have
  4481. // to be enclosed within a string, so it can't be parsed as an Expression.
  4482. //
  4483. url: function () {
  4484. let value;
  4485. const index = parserInput.i;
  4486. parserInput.autoCommentAbsorb = false;
  4487. if (!parserInput.$str('url(')) {
  4488. parserInput.autoCommentAbsorb = true;
  4489. return;
  4490. }
  4491. value = this.quoted() || this.variable() || this.property() ||
  4492. parserInput.$re(/^(?:(?:\\[()'"])|[^()'"])+/) || '';
  4493. parserInput.autoCommentAbsorb = true;
  4494. expectChar(')');
  4495. return new(tree.URL)((value.value !== undefined ||
  4496. value instanceof tree.Variable ||
  4497. value instanceof tree.Property) ?
  4498. value : new(tree.Anonymous)(value, index), index + currentIndex, fileInfo);
  4499. },
  4500. //
  4501. // A Variable entity, such as `@fink`, in
  4502. //
  4503. // width: @fink + 2px
  4504. //
  4505. // We use a different parser for variable definitions,
  4506. // see `parsers.variable`.
  4507. //
  4508. variable: function () {
  4509. let ch;
  4510. let name;
  4511. const index = parserInput.i;
  4512. parserInput.save();
  4513. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
  4514. ch = parserInput.currentChar();
  4515. if ((ch === '(' && !parserInput.prevChar().match(/^\s/))
  4516. || (ch === '[' && !parserInput.prevChar().match(/^\s/))) {
  4517. // this may be a VariableCall lookup
  4518. const result = parsers.variableCall(name);
  4519. if (result) {
  4520. parserInput.forget();
  4521. return result;
  4522. }
  4523. }
  4524. parserInput.forget();
  4525. return new(tree.Variable)(name, index + currentIndex, fileInfo);
  4526. }
  4527. parserInput.restore();
  4528. },
  4529. // A variable entity using the protective {} e.g. @{var}
  4530. variableCurly: function () {
  4531. let curly;
  4532. const index = parserInput.i;
  4533. if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
  4534. return new(tree.Variable)(`@${curly[1]}`, index + currentIndex, fileInfo);
  4535. }
  4536. },
  4537. //
  4538. // A Property accessor, such as `$color`, in
  4539. //
  4540. // background-color: $color
  4541. //
  4542. property: function () {
  4543. let name;
  4544. const index = parserInput.i;
  4545. if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
  4546. return new(tree.Property)(name, index + currentIndex, fileInfo);
  4547. }
  4548. },
  4549. //
  4550. // A Hexadecimal color
  4551. //
  4552. // #4F3C2F
  4553. //
  4554. // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
  4555. //
  4556. color: function () {
  4557. let rgb;
  4558. parserInput.save();
  4559. if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#[])?/))) {
  4560. if (!rgb[2]) {
  4561. parserInput.forget();
  4562. return new(tree.Color)(rgb[1], undefined, rgb[0]);
  4563. }
  4564. }
  4565. parserInput.restore();
  4566. },
  4567. colorKeyword: function () {
  4568. parserInput.save();
  4569. const autoCommentAbsorb = parserInput.autoCommentAbsorb;
  4570. parserInput.autoCommentAbsorb = false;
  4571. const k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
  4572. parserInput.autoCommentAbsorb = autoCommentAbsorb;
  4573. if (!k) {
  4574. parserInput.forget();
  4575. return;
  4576. }
  4577. parserInput.restore();
  4578. const color = tree.Color.fromKeyword(k);
  4579. if (color) {
  4580. parserInput.$str(k);
  4581. return color;
  4582. }
  4583. },
  4584. //
  4585. // A Dimension, that is, a number and a unit
  4586. //
  4587. // 0.5em 95%
  4588. //
  4589. dimension: function () {
  4590. if (parserInput.peekNotNumeric()) {
  4591. return;
  4592. }
  4593. const value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
  4594. if (value) {
  4595. return new(tree.Dimension)(value[1], value[2]);
  4596. }
  4597. },
  4598. //
  4599. // A unicode descriptor, as is used in unicode-range
  4600. //
  4601. // U+0?? or U+00A1-00A9
  4602. //
  4603. unicodeDescriptor: function () {
  4604. let ud;
  4605. ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(-[0-9a-fA-F?]+)?/);
  4606. if (ud) {
  4607. return new(tree.UnicodeDescriptor)(ud[0]);
  4608. }
  4609. },
  4610. //
  4611. // JavaScript code to be evaluated
  4612. //
  4613. // `window.location.href`
  4614. //
  4615. javascript: function () {
  4616. let js;
  4617. const index = parserInput.i;
  4618. parserInput.save();
  4619. const escape = parserInput.$char('~');
  4620. const jsQuote = parserInput.$char('`');
  4621. if (!jsQuote) {
  4622. parserInput.restore();
  4623. return;
  4624. }
  4625. js = parserInput.$re(/^[^`]*`/);
  4626. if (js) {
  4627. warn('Inline JavaScript evaluation (backtick expressions) is deprecated and will be removed in Less 5.x. Use Less functions or custom plugins instead.', index, 'DEPRECATED', 'js-eval');
  4628. parserInput.forget();
  4629. return new(tree.JavaScript)(js.slice(0, -1), Boolean(escape), index + currentIndex, fileInfo);
  4630. }
  4631. parserInput.restore('invalid javascript definition');
  4632. }
  4633. },
  4634. //
  4635. // The variable part of a variable definition. Used in the `rule` parser
  4636. //
  4637. // @fink:
  4638. //
  4639. variable: function () {
  4640. let name;
  4641. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) { return name[1]; }
  4642. },
  4643. //
  4644. // Call a variable value to retrieve a detached ruleset
  4645. // or a value from a detached ruleset's rules.
  4646. //
  4647. // @fink();
  4648. // @fink;
  4649. // color: @fink[@color];
  4650. //
  4651. variableCall: function (parsedName) {
  4652. let lookups;
  4653. const i = parserInput.i;
  4654. const inValue = !!parsedName;
  4655. let name = parsedName;
  4656. parserInput.save();
  4657. if (name || (parserInput.currentChar() === '@'
  4658. && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) {
  4659. lookups = this.mixin.ruleLookups();
  4660. if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) {
  4661. parserInput.restore('Missing \'[...]\' lookup in variable call');
  4662. return;
  4663. }
  4664. if (!inValue) {
  4665. name = name[1];
  4666. }
  4667. const call = new tree.VariableCall(name, i, fileInfo);
  4668. if (!inValue && parsers.end()) {
  4669. parserInput.forget();
  4670. return call;
  4671. }
  4672. else {
  4673. parserInput.forget();
  4674. return new tree.NamespaceValue(call, lookups, i, fileInfo);
  4675. }
  4676. }
  4677. parserInput.restore();
  4678. },
  4679. //
  4680. // extend syntax - used to extend selectors
  4681. //
  4682. extend: function(isRule) {
  4683. let elements;
  4684. let e;
  4685. const index = parserInput.i;
  4686. let option;
  4687. let extendList;
  4688. let extend;
  4689. if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
  4690. return;
  4691. }
  4692. do {
  4693. option = null;
  4694. elements = null;
  4695. let first = true;
  4696. while (!(option = parserInput.$re(/^(!?all)(?=\s*(\)|,))/))) {
  4697. e = this.element();
  4698. if (!e) {
  4699. break;
  4700. }
  4701. /**
  4702. * @note - This will not catch selectors in pseudos like :is() and :where() because
  4703. * they don't currently parse their contents as selectors.
  4704. */
  4705. if (!first && e.combinator.value) {
  4706. warn('Targeting complex selectors can have unexpected behavior, and this behavior may change in the future.', index);
  4707. }
  4708. first = false;
  4709. if (elements) {
  4710. elements.push(e);
  4711. } else {
  4712. elements = [ e ];
  4713. }
  4714. }
  4715. option = option && option[1];
  4716. if (!elements) {
  4717. error('Missing target selector for :extend().');
  4718. }
  4719. extend = new(tree.Extend)(new(tree.Selector)(elements), option, index + currentIndex, fileInfo);
  4720. if (extendList) {
  4721. extendList.push(extend);
  4722. } else {
  4723. extendList = [ extend ];
  4724. }
  4725. } while (parserInput.$char(','));
  4726. expect(/^\)/);
  4727. if (isRule) {
  4728. expect(/^;/);
  4729. }
  4730. return extendList;
  4731. },
  4732. //
  4733. // extendRule - used in a rule to extend all the parent selectors
  4734. //
  4735. extendRule: function() {
  4736. return this.extend(true);
  4737. },
  4738. //
  4739. // Mixins
  4740. //
  4741. mixin: {
  4742. //
  4743. // A Mixin call, with an optional argument list
  4744. //
  4745. // #mixins > .square(#fff);
  4746. // #mixins.square(#fff);
  4747. // .rounded(4px, black);
  4748. // .button;
  4749. //
  4750. // We can lookup / return a value using the lookup syntax:
  4751. //
  4752. // color: #mixin.square(#fff)[@color];
  4753. //
  4754. // The `while` loop is there because mixins can be
  4755. // namespaced, but we only support the child and descendant
  4756. // selector for now.
  4757. //
  4758. call: function (inValue, getLookup) {
  4759. const s = parserInput.currentChar();
  4760. let important = false;
  4761. let lookups;
  4762. const index = parserInput.i;
  4763. let elements;
  4764. let args;
  4765. let hasParens;
  4766. let parensIndex;
  4767. let parensWS = false;
  4768. if (s !== '.' && s !== '#') { return; }
  4769. parserInput.save(); // stop us absorbing part of an invalid selector
  4770. elements = this.elements();
  4771. if (elements) {
  4772. parensIndex = parserInput.i;
  4773. parensWS = parserInput.isWhitespace(-1);
  4774. if (parserInput.$char('(')) {
  4775. args = this.args(true).args;
  4776. expectChar(')');
  4777. hasParens = true;
  4778. if (parensWS) {
  4779. warn('Whitespace between a mixin name and parentheses for a mixin call is deprecated', parensIndex, 'DEPRECATED', 'mixin-call-whitespace');
  4780. }
  4781. }
  4782. if (getLookup !== false) {
  4783. lookups = this.ruleLookups();
  4784. }
  4785. if (getLookup === true && !lookups) {
  4786. parserInput.restore();
  4787. return;
  4788. }
  4789. if (inValue && !lookups && !hasParens) {
  4790. // This isn't a valid in-value mixin call
  4791. parserInput.restore();
  4792. return;
  4793. }
  4794. if (!inValue && parsers.important()) {
  4795. important = true;
  4796. }
  4797. if (inValue || parsers.end()) {
  4798. parserInput.forget();
  4799. const mixin = new(tree.mixin.Call)(elements, args, index + currentIndex, fileInfo, !lookups && important);
  4800. if (lookups) {
  4801. return new tree.NamespaceValue(mixin, lookups);
  4802. }
  4803. else {
  4804. if (!hasParens) {
  4805. warn('Calling a mixin without parentheses is deprecated', parensIndex, 'DEPRECATED', 'mixin-call-no-parens');
  4806. }
  4807. return mixin;
  4808. }
  4809. }
  4810. }
  4811. parserInput.restore();
  4812. },
  4813. /**
  4814. * Matching elements for mixins
  4815. * (Start with . or # and can have > )
  4816. */
  4817. elements: function() {
  4818. let elements;
  4819. let e;
  4820. let c;
  4821. let elem;
  4822. let elemIndex;
  4823. const re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
  4824. while (true) {
  4825. elemIndex = parserInput.i;
  4826. e = parserInput.$re(re);
  4827. if (!e) {
  4828. break;
  4829. }
  4830. elem = new(tree.Element)(c, e, false, elemIndex + currentIndex, fileInfo);
  4831. if (elements) {
  4832. elements.push(elem);
  4833. } else {
  4834. elements = [ elem ];
  4835. }
  4836. c = parserInput.$char('>');
  4837. }
  4838. return elements;
  4839. },
  4840. args: function (isCall) {
  4841. const entities = parsers.entities;
  4842. const returner = { args:null, variadic: false };
  4843. let expressions = [];
  4844. const argsSemiColon = [];
  4845. const argsComma = [];
  4846. let isSemiColonSeparated;
  4847. let expressionContainsNamed;
  4848. let name;
  4849. let nameLoop;
  4850. let value;
  4851. let arg;
  4852. let expand;
  4853. let hasSep = true;
  4854. parserInput.save();
  4855. while (true) {
  4856. if (isCall) {
  4857. arg = parsers.detachedRuleset() || parsers.expression();
  4858. } else {
  4859. parserInput.commentStore.length = 0;
  4860. if (parserInput.$str('...')) {
  4861. returner.variadic = true;
  4862. if (parserInput.$char(';') && !isSemiColonSeparated) {
  4863. isSemiColonSeparated = true;
  4864. }
  4865. (isSemiColonSeparated ? argsSemiColon : argsComma)
  4866. .push({ variadic: true });
  4867. break;
  4868. }
  4869. arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
  4870. }
  4871. if (!arg || !hasSep) {
  4872. break;
  4873. }
  4874. nameLoop = null;
  4875. if (arg.throwAwayComments) {
  4876. arg.throwAwayComments();
  4877. }
  4878. value = arg;
  4879. let val = null;
  4880. if (isCall) {
  4881. // Variable
  4882. if (arg.value && arg.value.length == 1) {
  4883. val = arg.value[0];
  4884. }
  4885. } else {
  4886. val = arg;
  4887. }
  4888. if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
  4889. if (parserInput.$char(':')) {
  4890. if (expressions.length > 0) {
  4891. if (isSemiColonSeparated) {
  4892. error('Cannot mix ; and , as delimiter types');
  4893. }
  4894. expressionContainsNamed = true;
  4895. }
  4896. value = parsers.detachedRuleset() || parsers.expression();
  4897. if (!value) {
  4898. if (isCall) {
  4899. error('could not understand value for named argument');
  4900. } else {
  4901. parserInput.restore();
  4902. returner.args = [];
  4903. return returner;
  4904. }
  4905. }
  4906. nameLoop = (name = val.name);
  4907. } else if (parserInput.$str('...')) {
  4908. if (!isCall) {
  4909. returner.variadic = true;
  4910. if (parserInput.$char(';') && !isSemiColonSeparated) {
  4911. isSemiColonSeparated = true;
  4912. }
  4913. (isSemiColonSeparated ? argsSemiColon : argsComma)
  4914. .push({ name: arg.name, variadic: true });
  4915. break;
  4916. } else {
  4917. expand = true;
  4918. }
  4919. } else if (!isCall) {
  4920. name = nameLoop = val.name;
  4921. value = null;
  4922. }
  4923. }
  4924. if (value) {
  4925. expressions.push(value);
  4926. }
  4927. argsComma.push({ name:nameLoop, value, expand });
  4928. if (parserInput.$char(',')) {
  4929. hasSep = true;
  4930. continue;
  4931. }
  4932. hasSep = parserInput.$char(';') === ';';
  4933. if (hasSep || isSemiColonSeparated) {
  4934. if (expressionContainsNamed) {
  4935. error('Cannot mix ; and , as delimiter types');
  4936. }
  4937. isSemiColonSeparated = true;
  4938. if (expressions.length > 1) {
  4939. value = new(tree.Value)(expressions);
  4940. }
  4941. argsSemiColon.push({ name, value, expand });
  4942. name = null;
  4943. expressions = [];
  4944. expressionContainsNamed = false;
  4945. }
  4946. }
  4947. parserInput.forget();
  4948. returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
  4949. return returner;
  4950. },
  4951. //
  4952. // A Mixin definition, with a list of parameters
  4953. //
  4954. // .rounded (@radius: 2px, @color) {
  4955. // ...
  4956. // }
  4957. //
  4958. // Until we have a finer grained state-machine, we have to
  4959. // do a look-ahead, to make sure we don't have a mixin call.
  4960. // See the `rule` function for more information.
  4961. //
  4962. // We start by matching `.rounded (`, and then proceed on to
  4963. // the argument list, which has optional default values.
  4964. // We store the parameters in `params`, with a `value` key,
  4965. // if there is a value, such as in the case of `@radius`.
  4966. //
  4967. // Once we've got our params list, and a closing `)`, we parse
  4968. // the `{...}` block.
  4969. //
  4970. definition: function () {
  4971. let name;
  4972. let params = [];
  4973. let match;
  4974. let ruleset;
  4975. let cond;
  4976. let variadic = false;
  4977. if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') ||
  4978. parserInput.peek(/^[^{]*\}/)) {
  4979. return;
  4980. }
  4981. parserInput.save();
  4982. match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
  4983. if (match) {
  4984. name = match[1];
  4985. const argInfo = this.args(false);
  4986. params = argInfo.args;
  4987. variadic = argInfo.variadic;
  4988. // .mixincall("@{a}");
  4989. // looks a bit like a mixin definition..
  4990. // also
  4991. // .mixincall(@a: {rule: set;});
  4992. // so we have to be nice and restore
  4993. if (!parserInput.$char(')')) {
  4994. parserInput.restore('Missing closing \')\'');
  4995. return;
  4996. }
  4997. parserInput.commentStore.length = 0;
  4998. if (parserInput.$str('when')) { // Guard
  4999. cond = expect(parsers.conditions, 'expected condition');
  5000. }
  5001. ruleset = parsers.block();
  5002. if (ruleset) {
  5003. parserInput.forget();
  5004. return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic);
  5005. } else {
  5006. parserInput.restore();
  5007. }
  5008. } else {
  5009. parserInput.restore();
  5010. }
  5011. },
  5012. ruleLookups: function() {
  5013. let rule;
  5014. const lookups = [];
  5015. if (parserInput.currentChar() !== '[') {
  5016. return;
  5017. }
  5018. while (true) {
  5019. parserInput.save();
  5020. rule = this.lookupValue();
  5021. if (!rule && rule !== '') {
  5022. parserInput.restore();
  5023. break;
  5024. }
  5025. lookups.push(rule);
  5026. parserInput.forget();
  5027. }
  5028. if (lookups.length > 0) {
  5029. return lookups;
  5030. }
  5031. },
  5032. lookupValue: function() {
  5033. parserInput.save();
  5034. if (!parserInput.$char('[')) {
  5035. parserInput.restore();
  5036. return;
  5037. }
  5038. const name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
  5039. if (!parserInput.$char(']')) {
  5040. parserInput.restore();
  5041. return;
  5042. }
  5043. if (name || name === '') {
  5044. parserInput.forget();
  5045. return name;
  5046. }
  5047. parserInput.restore();
  5048. }
  5049. },
  5050. //
  5051. // Entities are the smallest recognized token,
  5052. // and can be found inside a rule's value.
  5053. //
  5054. entity: function () {
  5055. const entities = this.entities;
  5056. return this.comment() || entities.literal() || entities.variable() || entities.url() ||
  5057. entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) ||
  5058. entities.javascript();
  5059. },
  5060. //
  5061. // A Declaration terminator. Note that we use `peek()` to check for '}',
  5062. // because the `block` rule will be expecting it, but we still need to make sure
  5063. // it's there, if ';' was omitted.
  5064. //
  5065. end: function () {
  5066. return parserInput.$char(';') || parserInput.peek('}');
  5067. },
  5068. //
  5069. // IE's alpha function
  5070. //
  5071. // alpha(opacity=88)
  5072. //
  5073. ieAlpha: function () {
  5074. let value;
  5075. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  5076. if (!parserInput.$re(/^opacity=/i)) { return; }
  5077. value = parserInput.$re(/^\d+/);
  5078. if (!value) {
  5079. value = expect(parsers.entities.variable, 'Could not parse alpha');
  5080. value = `@{${value.name.slice(1)}}`;
  5081. }
  5082. expectChar(')');
  5083. return new tree.Quoted('', `alpha(opacity=${value})`);
  5084. },
  5085. /**
  5086. * A Selector Element
  5087. *
  5088. * div
  5089. * + h1
  5090. * #socks
  5091. * input[type="text"]
  5092. *
  5093. * Elements are the building blocks for Selectors,
  5094. * they are made out of a `Combinator` (see combinator rule),
  5095. * and an element name, such as a tag a class, or `*`.
  5096. */
  5097. element: function () {
  5098. let e;
  5099. let c;
  5100. let v;
  5101. const index = parserInput.i;
  5102. c = this.combinator();
  5103. /** This selector parser is quite simplistic and will pass a number of invalid selectors. */
  5104. e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) ||
  5105. // eslint-disable-next-line no-control-regex
  5106. parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
  5107. parserInput.$char('*') || parserInput.$char('&') || this.attribute() ||
  5108. parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[.#:](?=@)/) ||
  5109. this.entities.variableCurly();
  5110. if (!e) {
  5111. parserInput.save();
  5112. if (parserInput.$char('(')) {
  5113. if ((v = this.selector(false))) {
  5114. let selectors = [];
  5115. while (parserInput.$char(',')) {
  5116. selectors.push(v);
  5117. selectors.push(new Anonymous(','));
  5118. v = this.selector(false);
  5119. }
  5120. selectors.push(v);
  5121. if (parserInput.$char(')')) {
  5122. if (selectors.length > 1) {
  5123. e = new (tree.Paren)(new Selector(selectors));
  5124. } else {
  5125. e = new(tree.Paren)(v);
  5126. }
  5127. parserInput.forget();
  5128. } else {
  5129. parserInput.restore('Missing closing \')\'');
  5130. }
  5131. } else {
  5132. parserInput.restore('Missing closing \')\'');
  5133. }
  5134. } else {
  5135. parserInput.forget();
  5136. }
  5137. }
  5138. if (e) { return new(tree.Element)(c, e, e instanceof tree.Variable, index + currentIndex, fileInfo); }
  5139. },
  5140. //
  5141. // Combinators combine elements together, in a Selector.
  5142. //
  5143. // Because our parser isn't white-space sensitive, special care
  5144. // has to be taken, when parsing the descendant combinator, ` `,
  5145. // as it's an empty space. We have to check the previous character
  5146. // in the input, to see if it's a ` ` character. More info on how
  5147. // we deal with this in *combinator.js*.
  5148. //
  5149. combinator: function () {
  5150. let c = parserInput.currentChar();
  5151. if (c === '/') {
  5152. parserInput.save();
  5153. const slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
  5154. if (slashedCombinator) {
  5155. parserInput.forget();
  5156. return new(tree.Combinator)(slashedCombinator);
  5157. }
  5158. parserInput.restore();
  5159. }
  5160. if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
  5161. parserInput.i++;
  5162. if (c === '^' && parserInput.currentChar() === '^') {
  5163. c = '^^';
  5164. parserInput.i++;
  5165. }
  5166. while (parserInput.isWhitespace()) { parserInput.i++; }
  5167. return new(tree.Combinator)(c);
  5168. } else if (parserInput.isWhitespace(-1)) {
  5169. return new(tree.Combinator)(' ');
  5170. } else {
  5171. return new(tree.Combinator)(null);
  5172. }
  5173. },
  5174. //
  5175. // A CSS Selector
  5176. // with less extensions e.g. the ability to extend and guard
  5177. //
  5178. // .class > div + h1
  5179. // li a:hover
  5180. //
  5181. // Selectors are made out of one or more Elements, see above.
  5182. //
  5183. selector: function (isLess) {
  5184. const index = parserInput.i;
  5185. let elements;
  5186. let extendList;
  5187. let c;
  5188. let e;
  5189. let allExtends;
  5190. let when;
  5191. let condition;
  5192. isLess = isLess !== false;
  5193. while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str('when'))) || (e = this.element())) {
  5194. if (when) {
  5195. condition = expect(this.conditions, 'expected condition');
  5196. } else if (condition) {
  5197. error('CSS guard can only be used at the end of selector');
  5198. } else if (extendList) {
  5199. if (allExtends) {
  5200. allExtends = allExtends.concat(extendList);
  5201. } else {
  5202. allExtends = extendList;
  5203. }
  5204. } else {
  5205. if (allExtends) { error('Extend can only be used at the end of selector'); }
  5206. c = parserInput.currentChar();
  5207. if (Array.isArray(e)){
  5208. e.forEach(ele => elements.push(ele));
  5209. } if (elements) {
  5210. elements.push(e);
  5211. } else {
  5212. elements = [ e ];
  5213. }
  5214. e = null;
  5215. }
  5216. if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
  5217. break;
  5218. }
  5219. }
  5220. if (elements) { return new(tree.Selector)(elements, allExtends, condition, index + currentIndex, fileInfo); }
  5221. if (allExtends) { error('Extend must be used to extend a selector, it cannot be used on its own'); }
  5222. },
  5223. selectors: function () {
  5224. let s;
  5225. let selectors;
  5226. while (true) {
  5227. s = this.selector();
  5228. if (!s) {
  5229. break;
  5230. }
  5231. if (selectors) {
  5232. selectors.push(s);
  5233. } else {
  5234. selectors = [ s ];
  5235. }
  5236. parserInput.commentStore.length = 0;
  5237. if (s.condition && selectors.length > 1) {
  5238. error('Guards are only currently allowed on a single selector.');
  5239. }
  5240. if (!parserInput.$char(',')) { break; }
  5241. if (s.condition) {
  5242. error('Guards are only currently allowed on a single selector.');
  5243. }
  5244. parserInput.commentStore.length = 0;
  5245. }
  5246. return selectors;
  5247. },
  5248. attribute: function () {
  5249. if (!parserInput.$char('[')) { return; }
  5250. const entities = this.entities;
  5251. let key;
  5252. let val;
  5253. let op;
  5254. //
  5255. // case-insensitive flag
  5256. // e.g. [attr operator value i]
  5257. //
  5258. let cif;
  5259. if (!(key = entities.variableCurly())) {
  5260. key = expect(/^(?:[_A-Za-z0-9-*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
  5261. }
  5262. op = parserInput.$re(/^[|~*$^]?=/);
  5263. if (op) {
  5264. val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
  5265. if (val) {
  5266. cif = parserInput.$re(/^[iIsS]/);
  5267. }
  5268. }
  5269. expectChar(']');
  5270. return new(tree.Attribute)(key, op, val, cif);
  5271. },
  5272. //
  5273. // The `block` rule is used by `ruleset` and `mixin.definition`.
  5274. // It's a wrapper around the `primary` rule, with added `{}`.
  5275. //
  5276. block: function () {
  5277. let content;
  5278. if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
  5279. return content;
  5280. }
  5281. },
  5282. blockRuleset: function() {
  5283. let block = this.block();
  5284. if (block) {
  5285. return new tree.Ruleset(null, block);
  5286. }
  5287. },
  5288. detachedRuleset: function() {
  5289. let argInfo;
  5290. let params;
  5291. let variadic;
  5292. parserInput.save();
  5293. if (parserInput.$re(/^[.#]\(/)) {
  5294. /**
  5295. * DR args currently only implemented for each() function, and not
  5296. * yet settable as `@dr: #(@arg) {}`
  5297. * This should be done when DRs are merged with mixins.
  5298. * See: https://github.com/less/less-meta/issues/16
  5299. */
  5300. argInfo = this.mixin.args(false);
  5301. params = argInfo.args;
  5302. variadic = argInfo.variadic;
  5303. if (!parserInput.$char(')')) {
  5304. parserInput.restore();
  5305. return;
  5306. }
  5307. }
  5308. const blockRuleset = this.blockRuleset();
  5309. if (blockRuleset) {
  5310. parserInput.forget();
  5311. if (params) {
  5312. return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
  5313. }
  5314. return new tree.DetachedRuleset(blockRuleset);
  5315. }
  5316. parserInput.restore();
  5317. },
  5318. //
  5319. // div, .class, body > p {...}
  5320. //
  5321. ruleset: function () {
  5322. let selectors;
  5323. let rules;
  5324. let debugInfo;
  5325. parserInput.save();
  5326. if (context.dumpLineNumbers) {
  5327. debugInfo = getDebugInfo(parserInput.i);
  5328. }
  5329. selectors = this.selectors();
  5330. if (selectors && (rules = this.block())) {
  5331. parserInput.forget();
  5332. const ruleset = new(tree.Ruleset)(selectors, rules, context.strictImports);
  5333. if (context.dumpLineNumbers) {
  5334. ruleset.debugInfo = debugInfo;
  5335. }
  5336. return ruleset;
  5337. } else {
  5338. parserInput.restore();
  5339. }
  5340. },
  5341. declaration: function () {
  5342. let name;
  5343. let value;
  5344. const index = parserInput.i;
  5345. let hasDR;
  5346. const c = parserInput.currentChar();
  5347. let important;
  5348. let merge;
  5349. let isVariable;
  5350. if (c === '.' || c === '#' || c === '&' || c === ':') { return; }
  5351. parserInput.save();
  5352. name = this.variable() || this.ruleProperty();
  5353. if (name) {
  5354. isVariable = typeof name === 'string';
  5355. if (isVariable) {
  5356. value = this.detachedRuleset();
  5357. if (value) {
  5358. hasDR = true;
  5359. }
  5360. }
  5361. parserInput.commentStore.length = 0;
  5362. if (!value) {
  5363. // a name returned by this.ruleProperty() is always an array of the form:
  5364. // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
  5365. // where each item is a tree.Keyword or tree.Variable
  5366. merge = !isVariable && name.length > 1 && name.pop().value;
  5367. // Custom property values get permissive parsing
  5368. if (name[0].value && name[0].value.slice(0, 2) === '--') {
  5369. if (parserInput.$char(';')) {
  5370. value = new Anonymous('');
  5371. } else {
  5372. value = this.permissiveValue(/[;}]/, true);
  5373. }
  5374. }
  5375. // Try to store values as anonymous
  5376. // If we need the value later we'll re-parse it in ruleset.parseValue
  5377. else {
  5378. value = this.anonymousValue();
  5379. }
  5380. if (value) {
  5381. parserInput.forget();
  5382. // anonymous values absorb the end ';' which is required for them to work
  5383. return new(tree.Declaration)(name, value, false, merge, index + currentIndex, fileInfo);
  5384. }
  5385. if (!value) {
  5386. value = this.value();
  5387. }
  5388. if (value) {
  5389. important = this.important();
  5390. } else if (isVariable) {
  5391. /**
  5392. * As a last resort, try permissiveValue
  5393. *
  5394. * @todo - This has created some knock-on problems of not
  5395. * flagging incorrect syntax or detecting user intent.
  5396. */
  5397. value = this.permissiveValue();
  5398. }
  5399. }
  5400. if (value && (this.end() || hasDR)) {
  5401. parserInput.forget();
  5402. return new(tree.Declaration)(name, value, important, merge, index + currentIndex, fileInfo);
  5403. }
  5404. else {
  5405. parserInput.restore();
  5406. }
  5407. } else {
  5408. parserInput.restore();
  5409. }
  5410. },
  5411. anonymousValue: function () {
  5412. const index = parserInput.i;
  5413. const match = parserInput.$re(/^([^.#@$+/'"*`(;{}-]*);/);
  5414. if (match) {
  5415. return new(tree.Anonymous)(match[1], index + currentIndex);
  5416. }
  5417. },
  5418. /**
  5419. * Used for custom properties, at-rules, and variables (as fallback)
  5420. * Parses almost anything inside of {} [] () "" blocks
  5421. * until it reaches outer-most tokens.
  5422. *
  5423. * First, it will try to parse comments and entities to reach
  5424. * the end. This is mostly like the Expression parser except no
  5425. * math is allowed.
  5426. *
  5427. * @param {RexExp} untilTokens - Characters to stop parsing at
  5428. */
  5429. permissiveValue: function (untilTokens) {
  5430. let i;
  5431. let e;
  5432. let done;
  5433. let value;
  5434. const tok = untilTokens || ';';
  5435. const index = parserInput.i;
  5436. const result = [];
  5437. function testCurrentChar() {
  5438. const char = parserInput.currentChar();
  5439. if (typeof tok === 'string') {
  5440. return char === tok;
  5441. } else {
  5442. return tok.test(char);
  5443. }
  5444. }
  5445. if (testCurrentChar()) {
  5446. return;
  5447. }
  5448. value = [];
  5449. do {
  5450. e = this.comment();
  5451. if (e) {
  5452. value.push(e);
  5453. continue;
  5454. }
  5455. e = this.entity();
  5456. if (e) {
  5457. value.push(e);
  5458. }
  5459. if (parserInput.peek(',')) {
  5460. value.push(new (tree.Anonymous)(',', parserInput.i));
  5461. parserInput.$char(',');
  5462. }
  5463. } while (e);
  5464. done = testCurrentChar();
  5465. if (value.length > 0) {
  5466. value = new(tree.Expression)(value);
  5467. if (done) {
  5468. return value;
  5469. }
  5470. else {
  5471. result.push(value);
  5472. }
  5473. // Preserve space before $parseUntil as it will not
  5474. if (parserInput.prevChar() === ' ') {
  5475. result.push(new tree.Anonymous(' ', index));
  5476. }
  5477. }
  5478. parserInput.save();
  5479. value = parserInput.$parseUntil(tok);
  5480. if (value) {
  5481. if (typeof value === 'string') {
  5482. error(`Expected '${value}'`, 'Parse');
  5483. }
  5484. if (value.length === 1 && value[0] === ' ') {
  5485. parserInput.forget();
  5486. return new tree.Anonymous('', index);
  5487. }
  5488. /** @type {string} */
  5489. let item;
  5490. for (i = 0; i < value.length; i++) {
  5491. item = value[i];
  5492. if (Array.isArray(item)) {
  5493. // Treat actual quotes as normal quoted values
  5494. result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
  5495. }
  5496. else {
  5497. if (i === value.length - 1) {
  5498. item = item.trim();
  5499. }
  5500. // Treat like quoted values, but replace vars like unquoted expressions
  5501. const quote = new tree.Quoted('\'', item, true, index, fileInfo);
  5502. const variableRegex = /@([\w-]+)/g;
  5503. const propRegex = /\$([\w-]+)/g;
  5504. if (variableRegex.test(item)) {
  5505. warn('@[ident] in unknown values will not be evaluated as variables in the future. Use @{[ident]}', index, 'DEPRECATED', 'variable-in-unknown-value');
  5506. }
  5507. if (propRegex.test(item)) {
  5508. warn('$[ident] in unknown values will not be evaluated as property references in the future. Use ${[ident]}', index, 'DEPRECATED', 'property-in-unknown-value');
  5509. }
  5510. quote.variableRegex = /@([\w-]+)|@{([\w-]+)}/g;
  5511. quote.propRegex = /\$([\w-]+)|\${([\w-]+)}/g;
  5512. result.push(quote);
  5513. }
  5514. }
  5515. parserInput.forget();
  5516. return new tree.Expression(result, true);
  5517. }
  5518. parserInput.restore();
  5519. },
  5520. //
  5521. // An @import atrule
  5522. //
  5523. // @import "lib";
  5524. //
  5525. // Depending on our environment, importing is done differently:
  5526. // In the browser, it's an XHR request, in Node, it would be a
  5527. // file-system operation. The function used for importing is
  5528. // stored in `import`, which we pass to the Import constructor.
  5529. //
  5530. 'import': function () {
  5531. let path;
  5532. let features;
  5533. const index = parserInput.i;
  5534. const dir = parserInput.$re(/^@import\s+/);
  5535. if (dir) {
  5536. const options = (dir ? this.importOptions() : null) || {};
  5537. if ((path = this.entities.quoted() || this.entities.url())) {
  5538. features = this.mediaFeatures({});
  5539. if (!parserInput.$char(';')) {
  5540. parserInput.i = index;
  5541. error('missing semi-colon or unrecognised media features on import');
  5542. }
  5543. features = features && new(tree.Value)(features);
  5544. return new(tree.Import)(path, features, options, index + currentIndex, fileInfo);
  5545. }
  5546. else {
  5547. parserInput.i = index;
  5548. error('malformed import statement');
  5549. }
  5550. }
  5551. },
  5552. importOptions: function() {
  5553. let o;
  5554. const options = {};
  5555. let optionName;
  5556. let value;
  5557. // list of options, surrounded by parens
  5558. if (!parserInput.$char('(')) { return null; }
  5559. do {
  5560. o = this.importOption();
  5561. if (o) {
  5562. optionName = o;
  5563. value = true;
  5564. switch (optionName) {
  5565. case 'css':
  5566. optionName = 'less';
  5567. value = false;
  5568. break;
  5569. case 'once':
  5570. optionName = 'multiple';
  5571. value = false;
  5572. break;
  5573. }
  5574. options[optionName] = value;
  5575. if (!parserInput.$char(',')) { break; }
  5576. }
  5577. } while (o);
  5578. expectChar(')');
  5579. return options;
  5580. },
  5581. importOption: function() {
  5582. const opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
  5583. if (opt) {
  5584. return opt[1];
  5585. }
  5586. },
  5587. mediaFeature: function (syntaxOptions) {
  5588. const entities = this.entities;
  5589. const nodes = [];
  5590. let e;
  5591. let p;
  5592. let rangeP;
  5593. let spacing = false;
  5594. parserInput.save();
  5595. do {
  5596. parserInput.save();
  5597. if (parserInput.$re(/^[0-9a-z-]*\s+\(/)) {
  5598. spacing = true;
  5599. }
  5600. parserInput.restore();
  5601. e = entities.declarationCall.bind(this)() || entities.keyword() || entities.variable() || entities.mixinLookup();
  5602. if (e) {
  5603. nodes.push(e);
  5604. if (e.type === 'Variable' ||
  5605. (e.type === 'Keyword' && /^(and|or|not|only)$/i.test(e.value))) {
  5606. spacing = true;
  5607. }
  5608. } else if (parserInput.$char('(')) {
  5609. p = this.property();
  5610. parserInput.save();
  5611. if (!p && syntaxOptions.queryInParens && parserInput.$re(/^[0-9a-z-]*\s*([<>]=|<=|>=|[<>]|=)/)) {
  5612. parserInput.restore();
  5613. p = this.condition();
  5614. parserInput.save();
  5615. rangeP = this.atomicCondition(null, p.rvalue);
  5616. if (!rangeP) {
  5617. parserInput.restore();
  5618. }
  5619. } else {
  5620. parserInput.restore();
  5621. e = this.value();
  5622. }
  5623. if (parserInput.$char(')')) {
  5624. if (p && !e) {
  5625. nodes.push(new (tree.Paren)(new (tree.QueryInParens)(p.op, p.lvalue, p.rvalue, rangeP ? rangeP.op : null, rangeP ? rangeP.rvalue : null, p._index)));
  5626. e = p;
  5627. } else if (p && e) {
  5628. nodes.push(new (tree.Paren)(new (tree.Declaration)(p, e, null, null, parserInput.i + currentIndex, fileInfo, true)));
  5629. if (!spacing) {
  5630. nodes[nodes.length - 1].noSpacing = true;
  5631. }
  5632. spacing = false;
  5633. } else if (e) {
  5634. nodes.push(new(tree.Paren)(e));
  5635. spacing = false;
  5636. } else {
  5637. error('badly formed media feature definition');
  5638. }
  5639. } else {
  5640. error('Missing closing \')\'', 'Parse');
  5641. }
  5642. }
  5643. } while (e);
  5644. parserInput.forget();
  5645. if (nodes.length > 0) {
  5646. return new(tree.Expression)(nodes);
  5647. }
  5648. },
  5649. mediaFeatures: function (syntaxOptions) {
  5650. const entities = this.entities;
  5651. const features = [];
  5652. let e;
  5653. do {
  5654. e = this.mediaFeature(syntaxOptions);
  5655. if (e) {
  5656. features.push(e);
  5657. if (!parserInput.$char(',')) { break; }
  5658. else if (!features[features.length - 1].noSpacing) {
  5659. features[features.length - 1].noSpacing = false;
  5660. }
  5661. } else {
  5662. e = entities.variable() || entities.mixinLookup();
  5663. if (e) {
  5664. features.push(e);
  5665. if (!parserInput.$char(',')) { break; }
  5666. else if (!features[features.length - 1].noSpacing) {
  5667. features[features.length - 1].noSpacing = false;
  5668. }
  5669. }
  5670. }
  5671. } while (e);
  5672. return features.length > 0 ? features : null;
  5673. },
  5674. prepareAndGetNestableAtRule: function (treeType, index, debugInfo, syntaxOptions) {
  5675. const features = this.mediaFeatures(syntaxOptions);
  5676. const rules = this.block();
  5677. if (!rules) {
  5678. error('media definitions require block statements after any features');
  5679. }
  5680. parserInput.forget();
  5681. const atRule = new (treeType)(rules, features, index + currentIndex, fileInfo);
  5682. if (context.dumpLineNumbers) {
  5683. atRule.debugInfo = debugInfo;
  5684. }
  5685. return atRule;
  5686. },
  5687. nestableAtRule: function () {
  5688. let debugInfo;
  5689. const index = parserInput.i;
  5690. if (context.dumpLineNumbers) {
  5691. debugInfo = getDebugInfo(index);
  5692. }
  5693. parserInput.save();
  5694. if (parserInput.$peekChar('@')) {
  5695. if (parserInput.$str('@media')) {
  5696. return this.prepareAndGetNestableAtRule(tree.Media, index, debugInfo, MediaSyntaxOptions);
  5697. }
  5698. if (parserInput.$str('@container')) {
  5699. return this.prepareAndGetNestableAtRule(tree.Container, index, debugInfo, ContainerSyntaxOptions);
  5700. }
  5701. }
  5702. parserInput.restore();
  5703. },
  5704. //
  5705. // A @plugin directive, used to import plugins dynamically.
  5706. //
  5707. // @plugin (args) "lib";
  5708. //
  5709. plugin: function () {
  5710. let path;
  5711. let args;
  5712. let options;
  5713. const index = parserInput.i;
  5714. const dir = parserInput.$re(/^@plugin\s+/);
  5715. if (dir) {
  5716. warn('The @plugin directive is deprecated and will be replaced in Less 5.x. Use --plugin CLI option or the programmatic plugin API instead.', index, 'DEPRECATED', 'at-plugin');
  5717. args = this.pluginArgs();
  5718. if (args) {
  5719. options = {
  5720. pluginArgs: args,
  5721. isPlugin: true
  5722. };
  5723. }
  5724. else {
  5725. options = { isPlugin: true };
  5726. }
  5727. if ((path = this.entities.quoted() || this.entities.url())) {
  5728. if (!parserInput.$char(';')) {
  5729. parserInput.i = index;
  5730. error('missing semi-colon on @plugin');
  5731. }
  5732. return new(tree.Import)(path, null, options, index + currentIndex, fileInfo);
  5733. }
  5734. else {
  5735. parserInput.i = index;
  5736. error('malformed @plugin statement');
  5737. }
  5738. }
  5739. },
  5740. pluginArgs: function() {
  5741. // list of options, surrounded by parens
  5742. parserInput.save();
  5743. if (!parserInput.$char('(')) {
  5744. parserInput.restore();
  5745. return null;
  5746. }
  5747. const args = parserInput.$re(/^\s*([^);]+)\)\s*/);
  5748. if (args[1]) {
  5749. parserInput.forget();
  5750. return args[1].trim();
  5751. }
  5752. else {
  5753. parserInput.restore();
  5754. return null;
  5755. }
  5756. },
  5757. atruleUnknown: function (value, name, hasBlock) {
  5758. value = this.permissiveValue(/^[{;]/);
  5759. hasBlock = (parserInput.currentChar() === '{');
  5760. if (!value) {
  5761. if (!hasBlock && parserInput.currentChar() !== ';') {
  5762. error(''.concat(name, ' rule is missing block or ending semi-colon'));
  5763. }
  5764. }
  5765. else if (!value.value) {
  5766. value = null;
  5767. }
  5768. return [value, hasBlock];
  5769. },
  5770. atruleBlock: function (rules, value, isRooted, isKeywordList) {
  5771. rules = this.blockRuleset();
  5772. parserInput.save();
  5773. if (!rules && !isRooted) {
  5774. value = this.entity();
  5775. rules = this.blockRuleset();
  5776. }
  5777. if (!rules && !isRooted) {
  5778. parserInput.restore();
  5779. var e = [];
  5780. value = this.entity();
  5781. while (parserInput.$char(',')) {
  5782. e.push(value);
  5783. value = this.entity();
  5784. }
  5785. if (value && e.length > 0) {
  5786. e.push(value);
  5787. value = e;
  5788. isKeywordList = true;
  5789. }
  5790. else {
  5791. rules = this.blockRuleset();
  5792. }
  5793. }
  5794. else {
  5795. parserInput.forget();
  5796. }
  5797. return [rules, value, isKeywordList];
  5798. },
  5799. //
  5800. // A CSS AtRule
  5801. //
  5802. // @charset "utf-8";
  5803. //
  5804. atrule: function () {
  5805. const index = parserInput.i;
  5806. let name;
  5807. let value;
  5808. let rules;
  5809. let nonVendorSpecificName;
  5810. let hasIdentifier;
  5811. let hasExpression;
  5812. let hasUnknown;
  5813. let hasBlock = true;
  5814. let isRooted = true;
  5815. let isKeywordList = false;
  5816. if (parserInput.currentChar() !== '@') { return; }
  5817. value = this['import']() || this.plugin() || this.nestableAtRule();
  5818. if (value) {
  5819. return value;
  5820. }
  5821. parserInput.save();
  5822. name = parserInput.$re(/^@[a-z-]+/);
  5823. if (!name) { return; }
  5824. nonVendorSpecificName = name;
  5825. if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
  5826. nonVendorSpecificName = `@${name.slice(name.indexOf('-', 2) + 1)}`;
  5827. }
  5828. switch (nonVendorSpecificName) {
  5829. case '@charset':
  5830. hasIdentifier = true;
  5831. hasBlock = false;
  5832. break;
  5833. case '@namespace':
  5834. hasExpression = true;
  5835. hasBlock = false;
  5836. break;
  5837. case '@keyframes':
  5838. case '@counter-style':
  5839. hasIdentifier = true;
  5840. break;
  5841. case '@document':
  5842. case '@supports':
  5843. hasUnknown = true;
  5844. isRooted = false;
  5845. break;
  5846. case '@starting-style':
  5847. isRooted = false;
  5848. break;
  5849. case '@layer':
  5850. isRooted = false;
  5851. break;
  5852. default:
  5853. hasUnknown = true;
  5854. break;
  5855. }
  5856. parserInput.commentStore.length = 0;
  5857. if (hasIdentifier) {
  5858. value = this.entity();
  5859. if (!value) {
  5860. error(`expected ${name} identifier`);
  5861. }
  5862. } else if (hasExpression) {
  5863. value = this.expression();
  5864. if (!value) {
  5865. error(`expected ${name} expression`);
  5866. }
  5867. } else if (hasUnknown) {
  5868. const unknownPackage = this.atruleUnknown(value, name, hasBlock);
  5869. value = unknownPackage[0];
  5870. hasBlock = unknownPackage[1];
  5871. }
  5872. if (hasBlock) {
  5873. let blockPackage = this.atruleBlock(rules, value, isRooted, isKeywordList);
  5874. rules = blockPackage[0];
  5875. value = blockPackage[1];
  5876. isKeywordList = blockPackage[2];
  5877. if (!rules && !hasUnknown) {
  5878. parserInput.restore();
  5879. name = parserInput.$re(/^@[a-z-]+/);
  5880. const unknownPackage = this.atruleUnknown(value, name, hasBlock);
  5881. value = unknownPackage[0];
  5882. hasBlock = unknownPackage[1];
  5883. if (hasBlock) {
  5884. blockPackage = this.atruleBlock(rules, value, isRooted, isKeywordList);
  5885. rules = blockPackage[0];
  5886. value = blockPackage[1];
  5887. isKeywordList = blockPackage[2];
  5888. }
  5889. }
  5890. }
  5891. if (rules || isKeywordList || (!hasBlock && value && parserInput.$char(';'))) {
  5892. parserInput.forget();
  5893. return new(tree.AtRule)(name, value, rules, index + currentIndex, fileInfo,
  5894. context.dumpLineNumbers ? getDebugInfo(index) : null,
  5895. isRooted
  5896. );
  5897. }
  5898. parserInput.restore('at-rule options not recognised');
  5899. },
  5900. //
  5901. // A Value is a comma-delimited list of Expressions
  5902. //
  5903. // font-family: Baskerville, Georgia, serif;
  5904. //
  5905. // In a Rule, a Value represents everything after the `:`,
  5906. // and before the `;`.
  5907. //
  5908. value: function () {
  5909. let e;
  5910. const expressions = [];
  5911. const index = parserInput.i;
  5912. do {
  5913. e = this.expression();
  5914. if (e) {
  5915. expressions.push(e);
  5916. if (!parserInput.$char(',')) { break; }
  5917. }
  5918. } while (e);
  5919. if (expressions.length > 0) {
  5920. return new(tree.Value)(expressions, index + currentIndex);
  5921. }
  5922. },
  5923. important: function () {
  5924. if (parserInput.currentChar() === '!') {
  5925. return parserInput.$re(/^! *important/);
  5926. }
  5927. },
  5928. sub: function () {
  5929. let a;
  5930. let e;
  5931. parserInput.save();
  5932. if (parserInput.$char('(')) {
  5933. a = this.addition();
  5934. if (a && parserInput.$char(')')) {
  5935. parserInput.forget();
  5936. e = new(tree.Expression)([a]);
  5937. e.parens = true;
  5938. return e;
  5939. }
  5940. parserInput.restore('Expected \')\'');
  5941. return;
  5942. }
  5943. parserInput.restore();
  5944. },
  5945. colorOperand: function () {
  5946. parserInput.save();
  5947. // hsl or rgb or lch operand
  5948. const match = parserInput.$re(/^[lchrgbs]\s+/);
  5949. if (match) {
  5950. parserInput.forget();
  5951. return new tree.Keyword(match[0]);
  5952. }
  5953. parserInput.restore();
  5954. },
  5955. multiplication: function () {
  5956. let m;
  5957. let a;
  5958. let op;
  5959. let operation;
  5960. let isSpaced;
  5961. m = this.operand();
  5962. if (m) {
  5963. isSpaced = parserInput.isWhitespace(-1);
  5964. while (true) {
  5965. if (parserInput.peek(/^\/[*/]/)) {
  5966. break;
  5967. }
  5968. parserInput.save();
  5969. op = parserInput.$char('/') || parserInput.$char('*');
  5970. if (!op) {
  5971. let index = parserInput.i;
  5972. op = parserInput.$str('./');
  5973. if (op) {
  5974. warn('./ operator is deprecated', index, 'DEPRECATED', 'dot-slash-operator');
  5975. }
  5976. }
  5977. if (!op) { parserInput.forget(); break; }
  5978. a = this.operand();
  5979. if (!a) { parserInput.restore(); break; }
  5980. parserInput.forget();
  5981. m.parensInOp = true;
  5982. a.parensInOp = true;
  5983. operation = new(tree.Operation)(op, [operation || m, a], isSpaced);
  5984. isSpaced = parserInput.isWhitespace(-1);
  5985. }
  5986. return operation || m;
  5987. }
  5988. },
  5989. addition: function () {
  5990. let m;
  5991. let a;
  5992. let op;
  5993. let operation;
  5994. let isSpaced;
  5995. m = this.multiplication();
  5996. if (m) {
  5997. isSpaced = parserInput.isWhitespace(-1);
  5998. while (true) {
  5999. op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-')));
  6000. if (!op) {
  6001. break;
  6002. }
  6003. a = this.multiplication();
  6004. if (!a) {
  6005. break;
  6006. }
  6007. m.parensInOp = true;
  6008. a.parensInOp = true;
  6009. operation = new(tree.Operation)(op, [operation || m, a], isSpaced);
  6010. isSpaced = parserInput.isWhitespace(-1);
  6011. }
  6012. return operation || m;
  6013. }
  6014. },
  6015. conditions: function () {
  6016. let a;
  6017. let b;
  6018. const index = parserInput.i;
  6019. let condition;
  6020. a = this.condition(true);
  6021. if (a) {
  6022. while (true) {
  6023. if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
  6024. break;
  6025. }
  6026. b = this.condition(true);
  6027. if (!b) {
  6028. break;
  6029. }
  6030. condition = new(tree.Condition)('or', condition || a, b, index + currentIndex);
  6031. }
  6032. return condition || a;
  6033. }
  6034. },
  6035. condition: function (needsParens) {
  6036. let result;
  6037. let logical;
  6038. let next;
  6039. function or() {
  6040. return parserInput.$str('or');
  6041. }
  6042. result = this.conditionAnd(needsParens);
  6043. if (!result) {
  6044. return ;
  6045. }
  6046. logical = or();
  6047. if (logical) {
  6048. next = this.condition(needsParens);
  6049. if (next) {
  6050. result = new(tree.Condition)(logical, result, next);
  6051. } else {
  6052. return ;
  6053. }
  6054. }
  6055. return result;
  6056. },
  6057. conditionAnd: function (needsParens) {
  6058. let result;
  6059. let logical;
  6060. let next;
  6061. const self = this;
  6062. function insideCondition() {
  6063. const cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
  6064. if (!cond && !needsParens) {
  6065. return self.atomicCondition(needsParens);
  6066. }
  6067. return cond;
  6068. }
  6069. function and() {
  6070. return parserInput.$str('and');
  6071. }
  6072. result = insideCondition();
  6073. if (!result) {
  6074. return ;
  6075. }
  6076. logical = and();
  6077. if (logical) {
  6078. next = this.conditionAnd(needsParens);
  6079. if (next) {
  6080. result = new(tree.Condition)(logical, result, next);
  6081. } else {
  6082. return ;
  6083. }
  6084. }
  6085. return result;
  6086. },
  6087. negatedCondition: function (needsParens) {
  6088. if (parserInput.$str('not')) {
  6089. const result = this.parenthesisCondition(needsParens);
  6090. if (result) {
  6091. result.negate = !result.negate;
  6092. }
  6093. return result;
  6094. }
  6095. },
  6096. parenthesisCondition: function (needsParens) {
  6097. function tryConditionFollowedByParenthesis(me) {
  6098. let body;
  6099. parserInput.save();
  6100. body = me.condition(needsParens);
  6101. if (!body) {
  6102. parserInput.restore();
  6103. return ;
  6104. }
  6105. if (!parserInput.$char(')')) {
  6106. parserInput.restore();
  6107. return ;
  6108. }
  6109. parserInput.forget();
  6110. return body;
  6111. }
  6112. let body;
  6113. parserInput.save();
  6114. if (!parserInput.$str('(')) {
  6115. parserInput.restore();
  6116. return ;
  6117. }
  6118. body = tryConditionFollowedByParenthesis(this);
  6119. if (body) {
  6120. parserInput.forget();
  6121. return body;
  6122. }
  6123. body = this.atomicCondition(needsParens);
  6124. if (!body) {
  6125. parserInput.restore();
  6126. return ;
  6127. }
  6128. if (!parserInput.$char(')')) {
  6129. parserInput.restore(`expected ')' got '${parserInput.currentChar()}'`);
  6130. return ;
  6131. }
  6132. parserInput.forget();
  6133. return body;
  6134. },
  6135. atomicCondition: function (needsParens, preparsedCond) {
  6136. const entities = this.entities;
  6137. const index = parserInput.i;
  6138. let a;
  6139. let b;
  6140. let c;
  6141. let op;
  6142. const cond = (function() {
  6143. return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
  6144. }).bind(this);
  6145. if (preparsedCond) {
  6146. a = preparsedCond;
  6147. } else {
  6148. a = cond();
  6149. }
  6150. if (a) {
  6151. if (parserInput.$char('>')) {
  6152. if (parserInput.$char('=')) {
  6153. op = '>=';
  6154. } else {
  6155. op = '>';
  6156. }
  6157. } else
  6158. if (parserInput.$char('<')) {
  6159. if (parserInput.$char('=')) {
  6160. op = '<=';
  6161. } else {
  6162. op = '<';
  6163. }
  6164. } else
  6165. if (parserInput.$char('=')) {
  6166. if (parserInput.$char('>')) {
  6167. op = '=>';
  6168. } else if (parserInput.$char('<')) {
  6169. op = '=<';
  6170. } else {
  6171. op = '=';
  6172. }
  6173. }
  6174. if (op) {
  6175. b = cond();
  6176. if (b) {
  6177. c = new(tree.Condition)(op, a, b, index + currentIndex, false);
  6178. } else {
  6179. error('expected expression');
  6180. }
  6181. } else if (!preparsedCond) {
  6182. c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index + currentIndex, false);
  6183. }
  6184. return c;
  6185. }
  6186. },
  6187. //
  6188. // An operand is anything that can be part of an operation,
  6189. // such as a Color, or a Variable
  6190. //
  6191. operand: function () {
  6192. const entities = this.entities;
  6193. let negate;
  6194. if (parserInput.peek(/^-[@$(]/)) {
  6195. negate = parserInput.$char('-');
  6196. }
  6197. let o = this.sub() || entities.dimension() ||
  6198. entities.color() || entities.variable() ||
  6199. entities.property() || entities.call() ||
  6200. entities.quoted(true) || entities.colorKeyword() ||
  6201. this.colorOperand() || entities.mixinLookup();
  6202. if (negate) {
  6203. o.parensInOp = true;
  6204. o = new(tree.Negative)(o);
  6205. }
  6206. return o;
  6207. },
  6208. //
  6209. // Expressions either represent mathematical operations,
  6210. // or white-space delimited Entities.
  6211. //
  6212. // 1px solid black
  6213. // @var * 2
  6214. //
  6215. expression: function () {
  6216. const entities = [];
  6217. let e;
  6218. let delim;
  6219. const index = parserInput.i;
  6220. do {
  6221. e = this.comment();
  6222. if (e && !e.isLineComment) {
  6223. entities.push(e);
  6224. continue;
  6225. }
  6226. e = this.addition() || this.entity();
  6227. if (e instanceof tree.Comment) {
  6228. e = null;
  6229. }
  6230. if (e) {
  6231. entities.push(e);
  6232. // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
  6233. if (!parserInput.peek(/^\/[/*]/)) {
  6234. delim = parserInput.$char('/');
  6235. if (delim) {
  6236. entities.push(new(tree.Anonymous)(delim, index + currentIndex));
  6237. }
  6238. }
  6239. }
  6240. } while (e);
  6241. if (entities.length > 0) {
  6242. return new(tree.Expression)(entities);
  6243. }
  6244. },
  6245. property: function () {
  6246. const name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
  6247. if (name) {
  6248. return name[1];
  6249. }
  6250. },
  6251. ruleProperty: function () {
  6252. let name = [];
  6253. const index = [];
  6254. let s;
  6255. let k;
  6256. parserInput.save();
  6257. const simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
  6258. if (simpleProperty) {
  6259. name = [new(tree.Keyword)(simpleProperty[1])];
  6260. parserInput.forget();
  6261. return name;
  6262. }
  6263. function match(re) {
  6264. const i = parserInput.i;
  6265. const chunk = parserInput.$re(re);
  6266. if (chunk) {
  6267. index.push(i);
  6268. return name.push(chunk[1]);
  6269. }
  6270. }
  6271. match(/^(\*?)/);
  6272. while (true) {
  6273. if (!match(/^((?:[\w-]+)|(?:[@$]\{[\w-]+\}))/)) {
  6274. break;
  6275. }
  6276. }
  6277. if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) {
  6278. parserInput.forget();
  6279. // at last, we have the complete match now. move forward,
  6280. // convert name particles to tree objects and return:
  6281. if (name[0] === '') {
  6282. name.shift();
  6283. index.shift();
  6284. }
  6285. for (k = 0; k < name.length; k++) {
  6286. s = name[k];
  6287. name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ?
  6288. new(tree.Keyword)(s) :
  6289. (s.charAt(0) === '@' ?
  6290. new(tree.Variable)(`@${s.slice(2, -1)}`, index[k] + currentIndex, fileInfo) :
  6291. new(tree.Property)(`$${s.slice(2, -1)}`, index[k] + currentIndex, fileInfo));
  6292. }
  6293. return name;
  6294. }
  6295. parserInput.restore();
  6296. }
  6297. }
  6298. };
  6299. };
  6300. Parser.serializeVars = vars => {
  6301. let s = '';
  6302. for (const name in vars) {
  6303. if (Object.hasOwnProperty.call(vars, name)) {
  6304. const value = vars[name];
  6305. s += `${((name[0] === '@') ? '' : '@') + name}: ${value}${(String(value).slice(-1) === ';') ? '' : ';'}`;
  6306. }
  6307. }
  6308. return s;
  6309. };
  6310. // @ts-check
  6311. /** @import { EvalContext, CSSOutput, FileInfo, VisibilityInfo, TreeVisitor } from './node.js' */
  6312. class Selector extends Node {
  6313. get type() { return 'Selector'; }
  6314. /**
  6315. * @param {(Element | Selector)[] | string} [elements]
  6316. * @param {Node[] | null} [extendList]
  6317. * @param {Node | null} [condition]
  6318. * @param {number} [index]
  6319. * @param {FileInfo} [currentFileInfo]
  6320. * @param {VisibilityInfo} [visibilityInfo]
  6321. */
  6322. constructor(elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
  6323. super();
  6324. /** @type {Node[] | null | undefined} */
  6325. this.extendList = extendList;
  6326. /** @type {Node | null | undefined} */
  6327. this.condition = condition;
  6328. /** @type {boolean | Node} */
  6329. this.evaldCondition = !condition;
  6330. this._index = index;
  6331. this._fileInfo = currentFileInfo;
  6332. /** @type {Element[]} */
  6333. this.elements = this.getElements(elements);
  6334. /** @type {string[] | undefined} */
  6335. this.mixinElements_ = undefined;
  6336. /** @type {boolean | undefined} */
  6337. this.mediaEmpty = undefined;
  6338. this.copyVisibilityInfo(visibilityInfo);
  6339. this.setParent(this.elements, this);
  6340. }
  6341. /** @param {TreeVisitor} visitor */
  6342. accept(visitor) {
  6343. if (this.elements) {
  6344. this.elements = /** @type {Element[]} */ (visitor.visitArray(this.elements));
  6345. }
  6346. if (this.extendList) {
  6347. this.extendList = visitor.visitArray(this.extendList);
  6348. }
  6349. if (this.condition) {
  6350. this.condition = visitor.visit(this.condition);
  6351. }
  6352. }
  6353. /**
  6354. * @param {Element[]} elements
  6355. * @param {Node[] | null} [extendList]
  6356. * @param {boolean | Node} [evaldCondition]
  6357. */
  6358. createDerived(elements, extendList, evaldCondition) {
  6359. elements = this.getElements(elements);
  6360. const newSelector = new Selector(elements, extendList || this.extendList,
  6361. null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  6362. newSelector.evaldCondition = (!isNullOrUndefined(evaldCondition)) ? evaldCondition : this.evaldCondition;
  6363. newSelector.mediaEmpty = this.mediaEmpty;
  6364. return newSelector;
  6365. }
  6366. /**
  6367. * @param {(Element | Selector)[] | string | null | undefined} els
  6368. * @returns {Element[]}
  6369. */
  6370. getElements(els) {
  6371. if (!els) {
  6372. return [new Element('', '&', false, this._index, this._fileInfo)];
  6373. }
  6374. if (typeof els === 'string') {
  6375. const fileInfo = this._fileInfo;
  6376. const parse = this.parse;
  6377. new (/** @type {new (...args: unknown[]) => { parseNode: Function }} */ (/** @type {unknown} */ (Parser)))(parse.context, parse.importManager, fileInfo, this._index).parseNode(
  6378. els,
  6379. ['selector'],
  6380. function(/** @type {{ index: number, message: string } | null} */ err, /** @type {Selector[]} */ result) {
  6381. if (err) {
  6382. throw new LessError({
  6383. index: err.index,
  6384. message: err.message
  6385. }, parse.imports, /** @type {string} */ (/** @type {FileInfo} */ (fileInfo).filename));
  6386. }
  6387. els = result[0].elements;
  6388. });
  6389. }
  6390. return /** @type {Element[]} */ (els);
  6391. }
  6392. createEmptySelectors() {
  6393. const el = new Element('', '&', false, this._index, this._fileInfo), sels = [new Selector([el], null, null, this._index, this._fileInfo)];
  6394. sels[0].mediaEmpty = true;
  6395. return sels;
  6396. }
  6397. /**
  6398. * @param {Selector} other
  6399. * @returns {number}
  6400. */
  6401. match(other) {
  6402. const elements = this.elements;
  6403. const len = elements.length;
  6404. let olen;
  6405. let i;
  6406. /** @type {string[]} */
  6407. const mixinEls = other.mixinElements();
  6408. olen = mixinEls.length;
  6409. if (olen === 0 || len < olen) {
  6410. return 0;
  6411. } else {
  6412. for (i = 0; i < olen; i++) {
  6413. if (elements[i].value !== mixinEls[i]) {
  6414. return 0;
  6415. }
  6416. }
  6417. }
  6418. return olen; // return number of matched elements
  6419. }
  6420. /** @returns {string[]} */
  6421. mixinElements() {
  6422. if (this.mixinElements_) {
  6423. return this.mixinElements_;
  6424. }
  6425. /** @type {string[] | null} */
  6426. let elements = this.elements.map( function(v) {
  6427. return /** @type {string} */ (v.combinator.value) + (/** @type {{ value: string }} */ (v.value).value || v.value);
  6428. }).join('').match(/[,&#*.\w-]([\w-]|(\\.))*/g);
  6429. if (elements) {
  6430. if (elements[0] === '&') {
  6431. elements.shift();
  6432. }
  6433. } else {
  6434. elements = [];
  6435. }
  6436. return (this.mixinElements_ = elements);
  6437. }
  6438. isJustParentSelector() {
  6439. return !this.mediaEmpty &&
  6440. this.elements.length === 1 &&
  6441. this.elements[0].value === '&' &&
  6442. (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
  6443. }
  6444. /** @param {EvalContext} context */
  6445. eval(context) {
  6446. const evaldCondition = this.condition && this.condition.eval(context);
  6447. let elements = this.elements;
  6448. /** @type {Node[] | null | undefined} */
  6449. let extendList = this.extendList;
  6450. if (elements) {
  6451. const evaldElements = new Array(elements.length);
  6452. for (let i = 0; i < elements.length; i++) {
  6453. evaldElements[i] = elements[i].eval(context);
  6454. }
  6455. elements = evaldElements;
  6456. }
  6457. if (extendList) {
  6458. const evaldExtends = new Array(extendList.length);
  6459. for (let i = 0; i < extendList.length; i++) {
  6460. evaldExtends[i] = extendList[i].eval(context);
  6461. }
  6462. extendList = evaldExtends;
  6463. }
  6464. return this.createDerived(elements, extendList, evaldCondition);
  6465. }
  6466. /**
  6467. * @param {EvalContext} context
  6468. * @param {CSSOutput} output
  6469. */
  6470. genCSS(context, output) {
  6471. let i, element;
  6472. if ((!context || !/** @type {EvalContext & { firstSelector?: boolean }} */ (context).firstSelector) && this.elements[0].combinator.value === '') {
  6473. output.add(' ', this.fileInfo(), this.getIndex());
  6474. }
  6475. for (i = 0; i < this.elements.length; i++) {
  6476. element = this.elements[i];
  6477. element.genCSS(context, output);
  6478. }
  6479. }
  6480. getIsOutput() {
  6481. return this.evaldCondition;
  6482. }
  6483. }
  6484. // @ts-check
  6485. /** @import { EvalContext, CSSOutput } from './node.js' */
  6486. class Keyword extends Node {
  6487. get type() { return 'Keyword'; }
  6488. /** @param {string} value */
  6489. constructor(value) {
  6490. super();
  6491. this.value = value;
  6492. }
  6493. /**
  6494. * @param {EvalContext} context
  6495. * @param {CSSOutput} output
  6496. */
  6497. genCSS(context, output) {
  6498. if (this.value === '%') { throw { type: 'Syntax', message: 'Invalid % without number' }; }
  6499. output.add(/** @type {string} */ (this.value));
  6500. }
  6501. }
  6502. Keyword.True = new Keyword('true');
  6503. Keyword.False = new Keyword('false');
  6504. // @ts-check
  6505. const MATH$1 = Math$1;
  6506. /**
  6507. * @param {EvalContext} context
  6508. * @param {Node[]} name
  6509. * @returns {string}
  6510. */
  6511. function evalName(context, name) {
  6512. let value = '';
  6513. let i;
  6514. const n = name.length;
  6515. /** @type {CSSOutput} */
  6516. const output = {add: function (s) {value += s;}, isEmpty: function() { return value === ''; }};
  6517. for (i = 0; i < n; i++) {
  6518. name[i].eval(context).genCSS(context, output);
  6519. }
  6520. return value;
  6521. }
  6522. class Declaration extends Node {
  6523. get type() { return 'Declaration'; }
  6524. /**
  6525. * @param {string | Node[]} name
  6526. * @param {Node | string | null} value
  6527. * @param {string} [important]
  6528. * @param {string} [merge]
  6529. * @param {number} [index]
  6530. * @param {FileInfo} [currentFileInfo]
  6531. * @param {boolean} [inline]
  6532. * @param {boolean} [variable]
  6533. */
  6534. constructor(name, value, important, merge, index, currentFileInfo, inline, variable) {
  6535. super();
  6536. this.name = name;
  6537. this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
  6538. this.important = important ? ` ${important.trim()}` : '';
  6539. /** @type {string | undefined} */
  6540. this.merge = merge;
  6541. this._index = index;
  6542. this._fileInfo = currentFileInfo;
  6543. /** @type {boolean} */
  6544. this.inline = inline || false;
  6545. /** @type {boolean} */
  6546. this.variable = (variable !== undefined) ? variable
  6547. : (typeof name === 'string' && name.charAt(0) === '@');
  6548. /** @type {boolean} */
  6549. this.allowRoot = true;
  6550. this.setParent(this.value, this);
  6551. }
  6552. /**
  6553. * @param {EvalContext} context
  6554. * @param {CSSOutput} output
  6555. */
  6556. genCSS(context, output) {
  6557. output.add(/** @type {string} */ (this.name) + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
  6558. try {
  6559. /** @type {Node} */ (this.value).genCSS(context, output);
  6560. }
  6561. catch (e) {
  6562. const err = /** @type {{ index?: number, filename?: string }} */ (e);
  6563. err.index = this._index;
  6564. err.filename = this._fileInfo && this._fileInfo.filename;
  6565. throw e;
  6566. }
  6567. output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index);
  6568. }
  6569. /** @param {EvalContext} context */
  6570. eval(context) {
  6571. let mathBypass = false, prevMath, name = this.name, evaldValue, variable = this.variable;
  6572. if (typeof name !== 'string') {
  6573. // expand 'primitive' name directly to get
  6574. // things faster (~10% for benchmark.less):
  6575. name = (/** @type {Node[]} */ (name).length === 1) && (/** @type {Node[]} */ (name)[0] instanceof Keyword) ?
  6576. /** @type {string} */ (/** @type {Node[]} */ (name)[0].value) : evalName(context, /** @type {Node[]} */ (name));
  6577. variable = false; // never treat expanded interpolation as new variable name
  6578. }
  6579. // @todo remove when parens-division is default
  6580. if (name === 'font' && context.math === MATH$1.ALWAYS) {
  6581. mathBypass = true;
  6582. prevMath = context.math;
  6583. context.math = MATH$1.PARENS_DIVISION;
  6584. }
  6585. try {
  6586. context.importantScope.push({});
  6587. evaldValue = /** @type {Node} */ (this.value).eval(context);
  6588. if (!this.variable && evaldValue.type === 'DetachedRuleset') {
  6589. throw { message: 'Rulesets cannot be evaluated on a property.',
  6590. index: this.getIndex(), filename: this.fileInfo().filename };
  6591. }
  6592. let important = this.important;
  6593. const importantResult = context.importantScope.pop();
  6594. if (!important && importantResult && importantResult.important) {
  6595. important = importantResult.important;
  6596. }
  6597. return new Declaration(/** @type {string} */ (name),
  6598. evaldValue,
  6599. important,
  6600. this.merge,
  6601. this.getIndex(), this.fileInfo(), this.inline,
  6602. variable);
  6603. }
  6604. catch (e) {
  6605. const err = /** @type {{ index?: number, filename?: string }} */ (e);
  6606. if (typeof err.index !== 'number') {
  6607. err.index = this.getIndex();
  6608. err.filename = this.fileInfo().filename;
  6609. }
  6610. throw e;
  6611. }
  6612. finally {
  6613. if (mathBypass) {
  6614. context.math = prevMath;
  6615. }
  6616. }
  6617. }
  6618. makeImportant() {
  6619. return new Declaration(this.name,
  6620. /** @type {Node} */ (this.value),
  6621. '!important',
  6622. this.merge,
  6623. this.getIndex(), this.fileInfo(), this.inline);
  6624. }
  6625. }
  6626. const defaultFunc = {
  6627. eval: function () {
  6628. const v = this.value_;
  6629. const e = this.error_;
  6630. if (e) {
  6631. throw e;
  6632. }
  6633. if (!isNullOrUndefined(v)) {
  6634. return v ? Keyword.True : Keyword.False;
  6635. }
  6636. },
  6637. value: function (v) {
  6638. this.value_ = v;
  6639. },
  6640. error: function (e) {
  6641. this.error_ = e;
  6642. },
  6643. reset: function () {
  6644. this.value_ = this.error_ = null;
  6645. }
  6646. };
  6647. // @ts-check
  6648. /**
  6649. * @typedef {Node & {
  6650. * rules?: Node[],
  6651. * selectors?: Selector[],
  6652. * root?: boolean,
  6653. * firstRoot?: boolean,
  6654. * allowImports?: boolean,
  6655. * functionRegistry?: FunctionRegistry,
  6656. * originalRuleset?: Node,
  6657. * debugInfo?: { lineNumber: number, fileName: string },
  6658. * evalFirst?: boolean,
  6659. * isRuleset?: boolean,
  6660. * isCharset?: () => boolean,
  6661. * merge?: boolean | string,
  6662. * multiMedia?: boolean,
  6663. * parse?: { context: EvalContext, importManager: object },
  6664. * bubbleSelectors?: (selectors: Selector[]) => void
  6665. * }} RuleNode
  6666. */
  6667. class Ruleset extends Node {
  6668. get type() { return 'Ruleset'; }
  6669. /**
  6670. * @param {Selector[] | null} selectors
  6671. * @param {Node[] | null} rules
  6672. * @param {boolean} [strictImports]
  6673. * @param {VisibilityInfo} [visibilityInfo]
  6674. */
  6675. constructor(selectors, rules, strictImports, visibilityInfo) {
  6676. super();
  6677. /** @type {Selector[] | null} */
  6678. this.selectors = selectors;
  6679. /** @type {Node[] | null} */
  6680. this.rules = rules;
  6681. /** @type {Object<string, { rule: Node, path: Node[] }[]>} */
  6682. this._lookups = {};
  6683. /** @type {Object<string, Declaration> | null} */
  6684. this._variables = null;
  6685. /** @type {Object<string, Declaration[]> | null} */
  6686. this._properties = null;
  6687. /** @type {boolean | undefined} */
  6688. this.strictImports = strictImports;
  6689. this.copyVisibilityInfo(visibilityInfo);
  6690. this.allowRoot = true;
  6691. /** @type {boolean} */
  6692. this.isRuleset = true;
  6693. /** @type {boolean | undefined} */
  6694. this.root = undefined;
  6695. /** @type {boolean | undefined} */
  6696. this.firstRoot = undefined;
  6697. /** @type {boolean | undefined} */
  6698. this.allowImports = undefined;
  6699. /** @type {FunctionRegistry | undefined} */
  6700. this.functionRegistry = undefined;
  6701. /** @type {Node | undefined} */
  6702. this.originalRuleset = undefined;
  6703. /** @type {{ lineNumber: number, fileName: string } | undefined} */
  6704. this.debugInfo = undefined;
  6705. /** @type {Selector[][] | undefined} */
  6706. this.paths = undefined;
  6707. /** @type {Ruleset[] | null | undefined} */
  6708. this._rulesets = undefined;
  6709. /** @type {boolean | undefined} */
  6710. this.evalFirst = undefined;
  6711. this.setParent(this.selectors, this);
  6712. this.setParent(this.rules, this);
  6713. }
  6714. isRulesetLike() { return true; }
  6715. /** @param {TreeVisitor} visitor */
  6716. accept(visitor) {
  6717. if (this.paths) {
  6718. this.paths = /** @type {Selector[][]} */ (/** @type {unknown} */ (visitor.visitArray(/** @type {Node[]} */ (/** @type {unknown} */ (this.paths)), true)));
  6719. } else if (this.selectors) {
  6720. this.selectors = /** @type {Selector[]} */ (visitor.visitArray(this.selectors));
  6721. }
  6722. if (this.rules && this.rules.length) {
  6723. this.rules = visitor.visitArray(this.rules);
  6724. }
  6725. }
  6726. /** @param {EvalContext} context */
  6727. eval(context) {
  6728. /** @type {Selector[] | undefined} */
  6729. let selectors;
  6730. /** @type {number} */
  6731. let selCnt;
  6732. /** @type {Selector} */
  6733. let selector;
  6734. /** @type {number} */
  6735. let i;
  6736. /** @type {boolean | undefined} */
  6737. let hasVariable;
  6738. let hasOnePassingSelector = false;
  6739. if (this.selectors && (selCnt = this.selectors.length)) {
  6740. selectors = new Array(selCnt);
  6741. defaultFunc.error({
  6742. type: 'Syntax',
  6743. message: 'it is currently only allowed in parametric mixin guards,'
  6744. });
  6745. for (i = 0; i < selCnt; i++) {
  6746. selector = /** @type {Selector} */ (this.selectors[i].eval(context));
  6747. for (let j = 0; j < selector.elements.length; j++) {
  6748. if (selector.elements[j].isVariable) {
  6749. hasVariable = true;
  6750. break;
  6751. }
  6752. }
  6753. selectors[i] = selector;
  6754. if (selector.evaldCondition) {
  6755. hasOnePassingSelector = true;
  6756. }
  6757. }
  6758. if (hasVariable) {
  6759. const toParseSelectors = new Array(selCnt);
  6760. for (i = 0; i < selCnt; i++) {
  6761. selector = selectors[i];
  6762. toParseSelectors[i] = selector.toCSS(context);
  6763. }
  6764. const startingIndex = selectors[0].getIndex();
  6765. const selectorFileInfo = selectors[0].fileInfo();
  6766. new (/** @type {new (...args: [EvalContext, object, FileInfo, number]) => { parseNode: Function }} */ (/** @type {unknown} */ (Parser)))(context, /** @type {{ context: EvalContext, importManager: object }} */ (this.parse).importManager, selectorFileInfo, startingIndex).parseNode(
  6767. toParseSelectors.join(','),
  6768. ['selectors'],
  6769. function(/** @type {Error | null} */ err, /** @type {Node[]} */ result) {
  6770. if (result) {
  6771. selectors = /** @type {Selector[]} */ (flattenArray(result));
  6772. }
  6773. });
  6774. }
  6775. defaultFunc.reset();
  6776. } else {
  6777. hasOnePassingSelector = true;
  6778. }
  6779. let rules = this.rules ? copyArray(this.rules) : null;
  6780. const ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
  6781. /** @type {Node} */
  6782. let rule;
  6783. /** @type {Node} */
  6784. let subRule;
  6785. ruleset.originalRuleset = this;
  6786. ruleset.root = this.root;
  6787. ruleset.firstRoot = this.firstRoot;
  6788. ruleset.allowImports = this.allowImports;
  6789. if (this.debugInfo) {
  6790. ruleset.debugInfo = this.debugInfo;
  6791. }
  6792. if (!hasOnePassingSelector) {
  6793. /** @type {Node[]} */ (rules).length = 0;
  6794. }
  6795. // push the current ruleset to the frames stack
  6796. const ctxFrames = context.frames;
  6797. // inherit a function registry from the frames stack when possible;
  6798. // otherwise from the global registry
  6799. /** @type {FunctionRegistry | undefined} */
  6800. let foundRegistry;
  6801. for (let fi = 0, fn = ctxFrames.length; fi !== fn; ++fi) {
  6802. foundRegistry = /** @type {RuleNode} */ (ctxFrames[fi]).functionRegistry;
  6803. if (foundRegistry) { break; }
  6804. }
  6805. ruleset.functionRegistry = (foundRegistry || functionRegistry).inherit();
  6806. ctxFrames.unshift(ruleset);
  6807. // currrent selectors
  6808. /** @type {Selector[][] | undefined} */
  6809. let ctxSelectors = /** @type {EvalContext & { selectors?: Selector[][] }} */ (context).selectors;
  6810. if (!ctxSelectors) {
  6811. /** @type {EvalContext & { selectors?: Selector[][] }} */ (context).selectors = ctxSelectors = [];
  6812. }
  6813. ctxSelectors.unshift(this.selectors);
  6814. // Evaluate imports
  6815. if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
  6816. ruleset.evalImports(context);
  6817. }
  6818. // Store the frames around mixin definitions,
  6819. // so they can be evaluated like closures when the time comes.
  6820. const rsRules = /** @type {Node[]} */ (ruleset.rules);
  6821. for (i = 0; (rule = rsRules[i]); i++) {
  6822. if (/** @type {RuleNode} */ (rule).evalFirst) {
  6823. rsRules[i] = rule.eval(context);
  6824. }
  6825. }
  6826. const mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0;
  6827. // Evaluate mixin calls.
  6828. for (i = 0; (rule = rsRules[i]); i++) {
  6829. if (rule.type === 'MixinCall') {
  6830. /* jshint loopfunc:true */
  6831. rules = /** @type {Node[]} */ (/** @type {unknown} */ (rule.eval(context))).filter(function(/** @type {Node & { variable?: boolean }} */ r) {
  6832. if ((r instanceof Declaration) && r.variable) {
  6833. // do not pollute the scope if the variable is
  6834. // already there. consider returning false here
  6835. // but we need a way to "return" variable from mixins
  6836. return !(ruleset.variable(/** @type {string} */ (r.name)));
  6837. }
  6838. return true;
  6839. });
  6840. rsRules.splice.apply(rsRules, /** @type {[number, number, ...Node[]]} */ ([i, 1].concat(rules)));
  6841. i += rules.length - 1;
  6842. ruleset.resetCache();
  6843. } else if (rule.type === 'VariableCall') {
  6844. /* jshint loopfunc:true */
  6845. rules = /** @type {Node[]} */ (/** @type {RuleNode} */ (rule.eval(context)).rules).filter(function(/** @type {Node & { variable?: boolean }} */ r) {
  6846. if ((r instanceof Declaration) && r.variable) {
  6847. // do not pollute the scope at all
  6848. return false;
  6849. }
  6850. return true;
  6851. });
  6852. rsRules.splice.apply(rsRules, /** @type {[number, number, ...Node[]]} */ ([i, 1].concat(rules)));
  6853. i += rules.length - 1;
  6854. ruleset.resetCache();
  6855. }
  6856. }
  6857. // Evaluate everything else
  6858. for (i = 0; (rule = rsRules[i]); i++) {
  6859. if (!/** @type {RuleNode} */ (rule).evalFirst) {
  6860. rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
  6861. }
  6862. }
  6863. // Evaluate everything else
  6864. for (i = 0; (rule = rsRules[i]); i++) {
  6865. // for rulesets, check if it is a css guard and can be removed
  6866. if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
  6867. // check if it can be folded in (e.g. & where)
  6868. if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
  6869. rsRules.splice(i--, 1);
  6870. for (let j = 0; (subRule = rule.rules[j]); j++) {
  6871. if (subRule instanceof Node) {
  6872. subRule.copyVisibilityInfo(rule.visibilityInfo());
  6873. if (!(subRule instanceof Declaration) || !subRule.variable) {
  6874. rsRules.splice(++i, 0, subRule);
  6875. }
  6876. }
  6877. }
  6878. }
  6879. }
  6880. }
  6881. // Pop the stack
  6882. ctxFrames.shift();
  6883. ctxSelectors.shift();
  6884. if (context.mediaBlocks) {
  6885. for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
  6886. /** @type {RuleNode} */ (context.mediaBlocks[i]).bubbleSelectors(selectors);
  6887. }
  6888. }
  6889. return ruleset;
  6890. }
  6891. /** @param {EvalContext} context */
  6892. evalImports(context) {
  6893. const rules = this.rules;
  6894. /** @type {number} */
  6895. let i;
  6896. /** @type {Node | Node[]} */
  6897. let importRules;
  6898. if (!rules) { return; }
  6899. for (i = 0; i < rules.length; i++) {
  6900. if (rules[i].type === 'Import') {
  6901. importRules = rules[i].eval(context);
  6902. if (importRules && (/** @type {Node[]} */ (/** @type {unknown} */ (importRules)).length || /** @type {Node[]} */ (/** @type {unknown} */ (importRules)).length === 0)) {
  6903. const importArr = /** @type {Node[]} */ (/** @type {unknown} */ (importRules));
  6904. rules.splice(i, 1, ...importArr);
  6905. i += importArr.length - 1;
  6906. } else {
  6907. rules.splice(i, 1, importRules);
  6908. }
  6909. this.resetCache();
  6910. }
  6911. }
  6912. }
  6913. makeImportant() {
  6914. const result = new Ruleset(this.selectors, /** @type {Node[]} */ (this.rules).map(function (/** @type {Node & { makeImportant?: () => Node }} */ r) {
  6915. if (r.makeImportant) {
  6916. return r.makeImportant();
  6917. } else {
  6918. return r;
  6919. }
  6920. }), this.strictImports, this.visibilityInfo());
  6921. return result;
  6922. }
  6923. /** @param {Node[] | object[] | null} [args] */
  6924. matchArgs(args) {
  6925. return !args || args.length === 0;
  6926. }
  6927. /**
  6928. * @param {Node[] | object[] | null} args
  6929. * @param {EvalContext} context
  6930. */
  6931. matchCondition(args, context) {
  6932. const lastSelector = /** @type {Selector[]} */ (this.selectors)[/** @type {Selector[]} */ (this.selectors).length - 1];
  6933. if (!lastSelector.evaldCondition) {
  6934. return false;
  6935. }
  6936. if (lastSelector.condition &&
  6937. !lastSelector.condition.eval(
  6938. new contexts.Eval(context,
  6939. context.frames))) {
  6940. return false;
  6941. }
  6942. return true;
  6943. }
  6944. resetCache() {
  6945. this._rulesets = null;
  6946. this._variables = null;
  6947. this._properties = null;
  6948. this._lookups = {};
  6949. }
  6950. variables() {
  6951. if (!this._variables) {
  6952. this._variables = !this.rules ? {} : this.rules.reduce(function (/** @type {Object<string, Declaration>} */ hash, /** @type {Node} */ r) {
  6953. if (r instanceof Declaration && r.variable === true) {
  6954. hash[/** @type {string} */ (r.name)] = r;
  6955. }
  6956. // when evaluating variables in an import statement, imports have not been eval'd
  6957. // so we need to go inside import statements.
  6958. // guard against root being a string (in the case of inlined less)
  6959. if (r.type === 'Import' && /** @type {RuleNode} */ (r).root && /** @type {RuleNode & { root: Ruleset }} */ (r).root.variables) {
  6960. const vars = /** @type {RuleNode & { root: Ruleset }} */ (r).root.variables();
  6961. for (const name in vars) {
  6962. if (Object.prototype.hasOwnProperty.call(vars, name)) {
  6963. hash[name] = /** @type {Declaration} */ (/** @type {RuleNode & { root: Ruleset }} */ (r).root.variable(name));
  6964. }
  6965. }
  6966. }
  6967. return hash;
  6968. }, {});
  6969. }
  6970. return this._variables;
  6971. }
  6972. properties() {
  6973. if (!this._properties) {
  6974. this._properties = !this.rules ? {} : this.rules.reduce(function (/** @type {Object<string, Declaration[]>} */ hash, /** @type {Node} */ r) {
  6975. if (r instanceof Declaration && r.variable !== true) {
  6976. const name = (/** @type {Node[]} */ (r.name).length === 1) && (/** @type {Node[]} */ (r.name)[0] instanceof Keyword) ?
  6977. /** @type {string} */ (/** @type {Node[]} */ (r.name)[0].value) : /** @type {string} */ (r.name);
  6978. // Properties don't overwrite as they can merge
  6979. if (!hash[`$${name}`]) {
  6980. hash[`$${name}`] = [ r ];
  6981. }
  6982. else {
  6983. hash[`$${name}`].push(r);
  6984. }
  6985. }
  6986. return hash;
  6987. }, {});
  6988. }
  6989. return this._properties;
  6990. }
  6991. /** @param {string} name */
  6992. variable(name) {
  6993. const decl = this.variables()[name];
  6994. if (decl) {
  6995. return this.parseValue(decl);
  6996. }
  6997. }
  6998. /** @param {string} name */
  6999. property(name) {
  7000. const decl = this.properties()[name];
  7001. if (decl) {
  7002. return this.parseValue(decl);
  7003. }
  7004. }
  7005. lastDeclaration() {
  7006. for (let i = /** @type {Node[]} */ (this.rules).length; i > 0; i--) {
  7007. const decl = /** @type {Node[]} */ (this.rules)[i - 1];
  7008. if (decl instanceof Declaration) {
  7009. return this.parseValue(decl);
  7010. }
  7011. }
  7012. }
  7013. /** @param {Declaration | Declaration[]} toParse */
  7014. parseValue(toParse) {
  7015. const self = this;
  7016. /** @param {Declaration} decl */
  7017. function transformDeclaration(decl) {
  7018. if (decl.value instanceof Anonymous && !/** @type {Declaration & { parsed?: boolean }} */ (decl).parsed) {
  7019. if (typeof decl.value.value === 'string') {
  7020. new (/** @type {new (...args: [EvalContext, object, FileInfo, number]) => { parseNode: Function }} */ (/** @type {unknown} */ (Parser)))(/** @type {{ context: EvalContext, importManager: object }} */ (/** @type {Ruleset} */ (this).parse).context, /** @type {{ context: EvalContext, importManager: object }} */ (/** @type {Ruleset} */ (this).parse).importManager, decl.fileInfo(), decl.value.getIndex()).parseNode(
  7021. decl.value.value,
  7022. ['value', 'important'],
  7023. function(/** @type {Error | null} */ err, /** @type {Node[]} */ result) {
  7024. if (err) {
  7025. decl.parsed = /** @type {Node} */ (/** @type {unknown} */ (true));
  7026. }
  7027. if (result) {
  7028. decl.value = result[0];
  7029. /** @type {Declaration & { important?: string }} */ (decl).important = /** @type {string} */ (/** @type {unknown} */ (result[1])) || '';
  7030. decl.parsed = /** @type {Node} */ (/** @type {unknown} */ (true));
  7031. }
  7032. });
  7033. } else {
  7034. decl.parsed = /** @type {Node} */ (/** @type {unknown} */ (true));
  7035. }
  7036. return decl;
  7037. }
  7038. else {
  7039. return decl;
  7040. }
  7041. }
  7042. if (!Array.isArray(toParse)) {
  7043. return transformDeclaration.call(self, toParse);
  7044. }
  7045. else {
  7046. /** @type {Declaration[]} */
  7047. const nodes = [];
  7048. for (let ti = 0; ti < toParse.length; ti++) {
  7049. nodes.push(transformDeclaration.call(self, toParse[ti]));
  7050. }
  7051. return nodes;
  7052. }
  7053. }
  7054. rulesets() {
  7055. if (!this.rules) { return []; }
  7056. /** @type {Node[]} */
  7057. const filtRules = [];
  7058. const rules = this.rules;
  7059. /** @type {number} */
  7060. let i;
  7061. /** @type {Node} */
  7062. let rule;
  7063. for (i = 0; (rule = rules[i]); i++) {
  7064. if (/** @type {RuleNode} */ (rule).isRuleset) {
  7065. filtRules.push(rule);
  7066. }
  7067. }
  7068. return filtRules;
  7069. }
  7070. /** @param {Node} rule */
  7071. prependRule(rule) {
  7072. const rules = this.rules;
  7073. if (rules) {
  7074. rules.unshift(rule);
  7075. } else {
  7076. this.rules = [ rule ];
  7077. }
  7078. this.setParent(rule, this);
  7079. }
  7080. /**
  7081. * @param {Selector} selector
  7082. * @param {Ruleset | null} [self]
  7083. * @param {((rule: Node) => boolean)} [filter]
  7084. * @returns {{ rule: Node, path: Node[] }[]}
  7085. */
  7086. find(selector, self, filter) {
  7087. self = self || this;
  7088. /** @type {{ rule: Node, path: Node[] }[]} */
  7089. const rules = [];
  7090. /** @type {number | undefined} */
  7091. let match;
  7092. /** @type {{ rule: Node, path: Node[] }[]} */
  7093. let foundMixins;
  7094. const key = selector.toCSS(/** @type {EvalContext} */ ({}));
  7095. if (key in this._lookups) { return /** @type {{ rule: Node, path: Node[] }[]} */ (this._lookups[key]); }
  7096. this.rulesets().forEach(function (rule) {
  7097. if (rule !== self) {
  7098. for (let j = 0; j < /** @type {RuleNode} */ (rule).selectors.length; j++) {
  7099. match = selector.match(/** @type {RuleNode} */ (rule).selectors[j]);
  7100. if (match) {
  7101. if (selector.elements.length > match) {
  7102. if (!filter || filter(rule)) {
  7103. foundMixins = /** @type {Ruleset} */ (/** @type {unknown} */ (rule)).find(new Selector(selector.elements.slice(match)), self, filter);
  7104. for (let i = 0; i < foundMixins.length; ++i) {
  7105. foundMixins[i].path.push(rule);
  7106. }
  7107. Array.prototype.push.apply(rules, foundMixins);
  7108. }
  7109. } else {
  7110. rules.push({ rule, path: []});
  7111. }
  7112. break;
  7113. }
  7114. }
  7115. }
  7116. });
  7117. this._lookups[key] = rules;
  7118. return rules;
  7119. }
  7120. /**
  7121. * @param {EvalContext} context
  7122. * @param {CSSOutput} output
  7123. */
  7124. genCSS(context, output) {
  7125. /** @type {number} */
  7126. let i;
  7127. /** @type {number} */
  7128. let j;
  7129. /** @type {Node[]} */
  7130. const charsetRuleNodes = [];
  7131. /** @type {Node[]} */
  7132. let ruleNodes = [];
  7133. let // Line number debugging
  7134. debugInfo$1;
  7135. /** @type {Node} */
  7136. let rule;
  7137. /** @type {Selector[]} */
  7138. let path;
  7139. context.tabLevel = (context.tabLevel || 0);
  7140. if (!this.root) {
  7141. context.tabLevel++;
  7142. }
  7143. const tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
  7144. const tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
  7145. /** @type {string} */
  7146. let sep;
  7147. let charsetNodeIndex = 0;
  7148. let importNodeIndex = 0;
  7149. for (i = 0; (rule = /** @type {Node[]} */ (this.rules)[i]); i++) {
  7150. if (rule instanceof Comment) {
  7151. if (importNodeIndex === i) {
  7152. importNodeIndex++;
  7153. }
  7154. ruleNodes.push(rule);
  7155. } else if (/** @type {RuleNode} */ (rule).isCharset && /** @type {RuleNode} */ (rule).isCharset()) {
  7156. ruleNodes.splice(charsetNodeIndex, 0, rule);
  7157. charsetNodeIndex++;
  7158. importNodeIndex++;
  7159. } else if (rule.type === 'Import') {
  7160. ruleNodes.splice(importNodeIndex, 0, rule);
  7161. importNodeIndex++;
  7162. } else {
  7163. ruleNodes.push(rule);
  7164. }
  7165. }
  7166. ruleNodes = charsetRuleNodes.concat(ruleNodes);
  7167. // If this is the root node, we don't render
  7168. // a selector, or {}.
  7169. if (!this.root) {
  7170. debugInfo$1 = debugInfo(context, /** @type {{ debugInfo: { lineNumber: number, fileName: string } }} */ (/** @type {unknown} */ (this)), tabSetStr);
  7171. if (debugInfo$1) {
  7172. output.add(debugInfo$1);
  7173. output.add(tabSetStr);
  7174. }
  7175. const paths = /** @type {Selector[][]} */ (this.paths);
  7176. const pathCnt = paths.length;
  7177. /** @type {number} */
  7178. let pathSubCnt;
  7179. sep = context.compress ? ',' : (`,\n${tabSetStr}`);
  7180. for (i = 0; i < pathCnt; i++) {
  7181. path = paths[i];
  7182. if (!(pathSubCnt = path.length)) { continue; }
  7183. if (i > 0) { output.add(sep); }
  7184. /** @type {EvalContext & { firstSelector?: boolean }} */ (context).firstSelector = true;
  7185. path[0].genCSS(context, output);
  7186. /** @type {EvalContext & { firstSelector?: boolean }} */ (context).firstSelector = false;
  7187. for (j = 1; j < pathSubCnt; j++) {
  7188. path[j].genCSS(context, output);
  7189. }
  7190. }
  7191. output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
  7192. }
  7193. // Compile rules and rulesets
  7194. for (i = 0; (rule = ruleNodes[i]); i++) {
  7195. if (i + 1 === ruleNodes.length) {
  7196. context.lastRule = true;
  7197. }
  7198. const currentLastRule = context.lastRule;
  7199. if (rule.isRulesetLike()) {
  7200. context.lastRule = false;
  7201. }
  7202. if (rule.genCSS) {
  7203. rule.genCSS(context, output);
  7204. } else if (rule.value) {
  7205. output.add(/** @type {string} */ (rule.value).toString());
  7206. }
  7207. context.lastRule = currentLastRule;
  7208. if (!context.lastRule && rule.isVisible()) {
  7209. output.add(context.compress ? '' : (`\n${tabRuleStr}`));
  7210. } else {
  7211. context.lastRule = false;
  7212. }
  7213. }
  7214. if (!this.root) {
  7215. output.add((context.compress ? '}' : `\n${tabSetStr}}`));
  7216. context.tabLevel--;
  7217. }
  7218. if (!output.isEmpty() && !context.compress && this.firstRoot) {
  7219. output.add('\n');
  7220. }
  7221. }
  7222. /**
  7223. * @param {Selector[][]} paths
  7224. * @param {Selector[][]} context
  7225. * @param {Selector[]} selectors
  7226. */
  7227. joinSelectors(paths, context, selectors) {
  7228. for (let s = 0; s < selectors.length; s++) {
  7229. this.joinSelector(paths, context, selectors[s]);
  7230. }
  7231. }
  7232. /**
  7233. * @param {Selector[][]} paths
  7234. * @param {Selector[][]} context
  7235. * @param {Selector} selector
  7236. */
  7237. joinSelector(paths, context, selector) {
  7238. /**
  7239. * @param {Selector[]} elementsToPak
  7240. * @param {Element} originalElement
  7241. * @returns {Paren}
  7242. */
  7243. function createParenthesis(elementsToPak, originalElement) {
  7244. /** @type {Paren} */
  7245. let replacementParen;
  7246. /** @type {number} */
  7247. let j;
  7248. if (elementsToPak.length === 0) {
  7249. replacementParen = new Paren(elementsToPak[0]);
  7250. } else {
  7251. const insideParent = new Array(elementsToPak.length);
  7252. for (j = 0; j < elementsToPak.length; j++) {
  7253. insideParent[j] = new Element(
  7254. null,
  7255. elementsToPak[j],
  7256. originalElement.isVariable,
  7257. originalElement._index,
  7258. originalElement._fileInfo
  7259. );
  7260. }
  7261. replacementParen = new Paren(new Selector(insideParent));
  7262. }
  7263. return replacementParen;
  7264. }
  7265. /**
  7266. * @param {Paren | Selector} containedElement
  7267. * @param {Element} originalElement
  7268. * @returns {Selector}
  7269. */
  7270. function createSelector(containedElement, originalElement) {
  7271. /** @type {Element} */
  7272. let element;
  7273. /** @type {Selector} */
  7274. let selector;
  7275. element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  7276. selector = new Selector([element]);
  7277. return selector;
  7278. }
  7279. /**
  7280. * @param {Selector[]} beginningPath
  7281. * @param {Selector[]} addPath
  7282. * @param {Element} replacedElement
  7283. * @param {Selector} originalSelector
  7284. * @returns {Selector[]}
  7285. */
  7286. function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
  7287. /** @type {Selector[]} */
  7288. let newSelectorPath;
  7289. /** @type {Selector} */
  7290. let lastSelector;
  7291. /** @type {Selector} */
  7292. let newJoinedSelector;
  7293. // our new selector path
  7294. newSelectorPath = [];
  7295. // construct the joined selector - if & is the first thing this will be empty,
  7296. // if not newJoinedSelector will be the last set of elements in the selector
  7297. if (beginningPath.length > 0) {
  7298. newSelectorPath = copyArray(beginningPath);
  7299. lastSelector = newSelectorPath.pop();
  7300. newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
  7301. }
  7302. else {
  7303. newJoinedSelector = originalSelector.createDerived([]);
  7304. }
  7305. if (addPath.length > 0) {
  7306. // /deep/ is a CSS4 selector - (removed, so should deprecate)
  7307. // that is valid without anything in front of it
  7308. // so if the & does not have a combinator that is "" or " " then
  7309. // and there is a combinator on the parent, then grab that.
  7310. // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
  7311. let combinator = replacedElement.combinator;
  7312. const parentEl = addPath[0].elements[0];
  7313. if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
  7314. combinator = parentEl.combinator;
  7315. }
  7316. // join the elements so far with the first part of the parent
  7317. newJoinedSelector.elements.push(new Element(
  7318. combinator,
  7319. parentEl.value,
  7320. replacedElement.isVariable,
  7321. replacedElement._index,
  7322. replacedElement._fileInfo
  7323. ));
  7324. newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
  7325. }
  7326. // now add the joined selector - but only if it is not empty
  7327. if (newJoinedSelector.elements.length !== 0) {
  7328. newSelectorPath.push(newJoinedSelector);
  7329. }
  7330. // put together the parent selectors after the join (e.g. the rest of the parent)
  7331. if (addPath.length > 1) {
  7332. let restOfPath = addPath.slice(1);
  7333. restOfPath = restOfPath.map(function (/** @type {Selector} */ selector) {
  7334. return selector.createDerived(selector.elements, []);
  7335. });
  7336. newSelectorPath = newSelectorPath.concat(restOfPath);
  7337. }
  7338. return newSelectorPath;
  7339. }
  7340. /**
  7341. * @param {Selector[][]} beginningPath
  7342. * @param {Selector[]} addPaths
  7343. * @param {Element} replacedElement
  7344. * @param {Selector} originalSelector
  7345. * @param {Selector[][]} result
  7346. * @returns {Selector[][]}
  7347. */
  7348. function addAllReplacementsIntoPath( beginningPath, addPaths, replacedElement, originalSelector, result) {
  7349. /** @type {number} */
  7350. let j;
  7351. for (j = 0; j < beginningPath.length; j++) {
  7352. const newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
  7353. result.push(newSelectorPath);
  7354. }
  7355. return result;
  7356. }
  7357. /**
  7358. * @param {Element[]} elements
  7359. * @param {Selector[][]} selectors
  7360. */
  7361. function mergeElementsOnToSelectors(elements, selectors) {
  7362. /** @type {number} */
  7363. let i;
  7364. /** @type {Selector[]} */
  7365. let sel;
  7366. if (elements.length === 0) {
  7367. return ;
  7368. }
  7369. if (selectors.length === 0) {
  7370. selectors.push([ new Selector(elements) ]);
  7371. return;
  7372. }
  7373. for (i = 0; (sel = selectors[i]); i++) {
  7374. // if the previous thing in sel is a parent this needs to join on to it
  7375. if (sel.length > 0) {
  7376. sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
  7377. }
  7378. else {
  7379. sel.push(new Selector(elements));
  7380. }
  7381. }
  7382. }
  7383. /**
  7384. * @param {Selector[][]} paths
  7385. * @param {Selector[][]} context
  7386. * @param {Selector} inSelector
  7387. * @returns {boolean}
  7388. */
  7389. function replaceParentSelector(paths, context, inSelector) {
  7390. // The paths are [[Selector]]
  7391. // The first list is a list of comma separated selectors
  7392. // The inner list is a list of inheritance separated selectors
  7393. // e.g.
  7394. // .a, .b {
  7395. // .c {
  7396. // }
  7397. // }
  7398. // == [[.a] [.c]] [[.b] [.c]]
  7399. //
  7400. /** @type {number} */
  7401. let i;
  7402. /** @type {number} */
  7403. let j;
  7404. /** @type {number} */
  7405. let k;
  7406. /** @type {Element[]} */
  7407. let currentElements;
  7408. /** @type {Selector[][]} */
  7409. let newSelectors;
  7410. /** @type {Selector[][]} */
  7411. let selectorsMultiplied;
  7412. /** @type {Selector[]} */
  7413. let sel;
  7414. /** @type {Element} */
  7415. let el;
  7416. let hadParentSelector = false;
  7417. /** @type {number} */
  7418. let length;
  7419. /** @type {Selector} */
  7420. let lastSelector;
  7421. /**
  7422. * @param {Element} element
  7423. * @returns {Selector | null}
  7424. */
  7425. function findNestedSelector(element) {
  7426. /** @type {Node} */
  7427. let maybeSelector;
  7428. if (!(element.value instanceof Paren)) {
  7429. return null;
  7430. }
  7431. maybeSelector = /** @type {Node} */ (element.value.value);
  7432. if (!(maybeSelector instanceof Selector)) {
  7433. return null;
  7434. }
  7435. return maybeSelector;
  7436. }
  7437. // the elements from the current selector so far
  7438. currentElements = [];
  7439. // the current list of new selectors to add to the path.
  7440. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
  7441. // by the parents
  7442. newSelectors = [
  7443. []
  7444. ];
  7445. for (i = 0; (el = inSelector.elements[i]); i++) {
  7446. // non parent reference elements just get added
  7447. if (el.value !== '&') {
  7448. const nestedSelector = findNestedSelector(el);
  7449. if (nestedSelector !== null) {
  7450. // merge the current list of non parent selector elements
  7451. // on to the current list of selectors to add
  7452. mergeElementsOnToSelectors(currentElements, newSelectors);
  7453. /** @type {Selector[][]} */
  7454. const nestedPaths = [];
  7455. /** @type {boolean | undefined} */
  7456. let replaced;
  7457. /** @type {Selector[][]} */
  7458. const replacedNewSelectors = [];
  7459. // Check if this is a comma-separated selector list inside the paren
  7460. // e.g. :not(&.a, &.b) produces Selector([Selector, Anonymous(','), Selector])
  7461. const hasSubSelectors = nestedSelector.elements.some(e => e instanceof Selector);
  7462. if (hasSubSelectors) {
  7463. // Process each sub-selector individually
  7464. /** @type {(Element | Selector)[]} */
  7465. const resolvedElements = [];
  7466. for (const subEl of nestedSelector.elements) {
  7467. if (subEl instanceof Selector) {
  7468. /** @type {Selector[][]} */
  7469. const subPaths = [];
  7470. const subReplaced = replaceParentSelector(subPaths, context, subEl);
  7471. replaced = replaced || subReplaced;
  7472. if (subPaths.length > 0 && subPaths[0].length > 0) {
  7473. resolvedElements.push(subPaths[0][0]);
  7474. } else {
  7475. resolvedElements.push(subEl);
  7476. }
  7477. } else {
  7478. resolvedElements.push(subEl);
  7479. }
  7480. }
  7481. hadParentSelector = hadParentSelector || /** @type {boolean} */ (replaced);
  7482. const resolvedNestedSelector = new Selector(resolvedElements);
  7483. const replacementSelector = createSelector(createParenthesis([resolvedNestedSelector], el), el);
  7484. addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
  7485. } else {
  7486. replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
  7487. hadParentSelector = hadParentSelector || replaced;
  7488. // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
  7489. for (k = 0; k < nestedPaths.length; k++) {
  7490. const replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
  7491. addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
  7492. }
  7493. }
  7494. newSelectors = replacedNewSelectors;
  7495. currentElements = [];
  7496. } else {
  7497. currentElements.push(el);
  7498. }
  7499. } else {
  7500. hadParentSelector = true;
  7501. // the new list of selectors to add
  7502. selectorsMultiplied = [];
  7503. // merge the current list of non parent selector elements
  7504. // on to the current list of selectors to add
  7505. mergeElementsOnToSelectors(currentElements, newSelectors);
  7506. // loop through our current selectors
  7507. for (j = 0; j < newSelectors.length; j++) {
  7508. sel = newSelectors[j];
  7509. // if we don't have any parent paths, the & might be in a mixin so that it can be used
  7510. // whether there are parents or not
  7511. if (context.length === 0) {
  7512. // the combinator used on el should now be applied to the next element instead so that
  7513. // it is not lost
  7514. if (sel.length > 0) {
  7515. sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
  7516. }
  7517. selectorsMultiplied.push(sel);
  7518. }
  7519. else {
  7520. // and the parent selectors
  7521. for (k = 0; k < context.length; k++) {
  7522. // We need to put the current selectors
  7523. // then join the last selector's elements on to the parents selectors
  7524. const newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);
  7525. // add that to our new set of selectors
  7526. selectorsMultiplied.push(newSelectorPath);
  7527. }
  7528. }
  7529. }
  7530. // our new selectors has been multiplied, so reset the state
  7531. newSelectors = selectorsMultiplied;
  7532. currentElements = [];
  7533. }
  7534. }
  7535. // if we have any elements left over (e.g. .a& .b == .b)
  7536. // add them on to all the current selectors
  7537. mergeElementsOnToSelectors(currentElements, newSelectors);
  7538. for (i = 0; i < newSelectors.length; i++) {
  7539. length = newSelectors[i].length;
  7540. if (length > 0) {
  7541. paths.push(newSelectors[i]);
  7542. lastSelector = newSelectors[i][length - 1];
  7543. newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
  7544. }
  7545. }
  7546. return hadParentSelector;
  7547. }
  7548. /**
  7549. * @param {VisibilityInfo} visibilityInfo
  7550. * @param {Selector} deriveFrom
  7551. */
  7552. function deriveSelector(visibilityInfo, deriveFrom) {
  7553. const newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
  7554. newSelector.copyVisibilityInfo(visibilityInfo);
  7555. return newSelector;
  7556. }
  7557. // joinSelector code follows
  7558. /** @type {number} */
  7559. let i;
  7560. /** @type {Selector[][]} */
  7561. let newPaths;
  7562. /** @type {boolean} */
  7563. let hadParentSelector;
  7564. newPaths = [];
  7565. hadParentSelector = replaceParentSelector(newPaths, context, selector);
  7566. if (!hadParentSelector) {
  7567. if (context.length > 0) {
  7568. newPaths = [];
  7569. for (i = 0; i < context.length; i++) {
  7570. const concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
  7571. concatenated.push(selector);
  7572. newPaths.push(concatenated);
  7573. }
  7574. }
  7575. else {
  7576. newPaths = [[selector]];
  7577. }
  7578. }
  7579. for (i = 0; i < newPaths.length; i++) {
  7580. paths.push(newPaths[i]);
  7581. }
  7582. }
  7583. }
  7584. // @ts-check
  7585. /**
  7586. * @typedef {object} FunctionRegistry
  7587. * @property {(name: string, func: Function) => void} add
  7588. * @property {(functions: Object) => void} addMultiple
  7589. * @property {(name: string) => Function} get
  7590. * @property {() => Object} getLocalFunctions
  7591. * @property {() => FunctionRegistry} inherit
  7592. * @property {(base: FunctionRegistry) => FunctionRegistry} create
  7593. */
  7594. /**
  7595. * @typedef {Node & {
  7596. * features: Value,
  7597. * rules: Ruleset[],
  7598. * type: string,
  7599. * functionRegistry?: FunctionRegistry,
  7600. * multiMedia?: boolean,
  7601. * debugInfo?: { lineNumber: number, fileName: string },
  7602. * allowRoot?: boolean,
  7603. * _evaluated?: boolean,
  7604. * evalFunction: () => void,
  7605. * evalTop: (context: EvalContext) => Node | Ruleset,
  7606. * evalNested: (context: EvalContext) => Node | Ruleset,
  7607. * permute: (arr: Node[][]) => Node[][],
  7608. * bubbleSelectors: (selectors: Selector[] | undefined) => void,
  7609. * outputRuleset: (context: EvalContext, output: CSSOutput, rules: Node[]) => void
  7610. * }} NestableAtRuleThis
  7611. */
  7612. const NestableAtRulePrototype = {
  7613. isRulesetLike() {
  7614. return true;
  7615. },
  7616. /** @param {TreeVisitor} visitor */
  7617. accept(visitor) {
  7618. /** @type {NestableAtRuleThis} */
  7619. const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
  7620. if (self.features) {
  7621. self.features = /** @type {Value} */ (visitor.visit(self.features));
  7622. }
  7623. if (self.rules) {
  7624. self.rules = /** @type {Ruleset[]} */ (visitor.visitArray(self.rules));
  7625. }
  7626. },
  7627. evalFunction: function () {
  7628. /** @type {NestableAtRuleThis} */
  7629. const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
  7630. if (!self.features || !Array.isArray(self.features.value) || self.features.value.length < 1) {
  7631. return;
  7632. }
  7633. const exprValues = /** @type {Node[]} */ (self.features.value);
  7634. /** @type {Node | undefined} */
  7635. let expr;
  7636. /** @type {Node | undefined} */
  7637. let paren;
  7638. for (let index = 0; index < exprValues.length; ++index) {
  7639. expr = exprValues[index];
  7640. if ((expr.type === 'Keyword' || expr.type === 'Variable')
  7641. && index + 1 < exprValues.length
  7642. && (/** @type {Node & { noSpacing?: boolean }} */ (expr).noSpacing || /** @type {Node & { noSpacing?: boolean }} */ (expr).noSpacing == null)) {
  7643. paren = exprValues[index + 1];
  7644. if (paren.type === 'Paren' && /** @type {Node & { noSpacing?: boolean }} */ (paren).noSpacing) {
  7645. exprValues[index]= new Expression([expr, paren]);
  7646. exprValues.splice(index + 1, 1);
  7647. /** @type {Node & { noSpacing?: boolean }} */ (exprValues[index]).noSpacing = true;
  7648. }
  7649. }
  7650. }
  7651. },
  7652. /** @param {EvalContext} context */
  7653. evalTop(context) {
  7654. /** @type {NestableAtRuleThis} */
  7655. const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
  7656. self.evalFunction();
  7657. /** @type {Node | Ruleset} */
  7658. let result = self;
  7659. // Render all dependent Media blocks.
  7660. if (context.mediaBlocks.length > 1) {
  7661. const selectors = (new Selector([], null, null, self.getIndex(), self.fileInfo())).createEmptySelectors();
  7662. result = new Ruleset(selectors, context.mediaBlocks);
  7663. /** @type {Ruleset & { multiMedia?: boolean }} */ (result).multiMedia = true;
  7664. result.copyVisibilityInfo(self.visibilityInfo());
  7665. self.setParent(result, self);
  7666. }
  7667. delete context.mediaBlocks;
  7668. delete context.mediaPath;
  7669. return result;
  7670. },
  7671. /** @param {EvalContext} context */
  7672. evalNested(context) {
  7673. /** @type {NestableAtRuleThis} */
  7674. const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
  7675. self.evalFunction();
  7676. let i;
  7677. /** @type {Node | Node[]} */
  7678. let value;
  7679. const path = context.mediaPath.concat([self]);
  7680. // Extract the media-query conditions separated with `,` (OR).
  7681. for (i = 0; i < path.length; i++) {
  7682. if (path[i].type !== self.type) {
  7683. const blockIndex = context.mediaBlocks.indexOf(self);
  7684. if (blockIndex > -1) {
  7685. context.mediaBlocks.splice(blockIndex, 1);
  7686. }
  7687. return self;
  7688. }
  7689. value = /** @type {NestableAtRuleThis} */ (path[i]).features instanceof Value ?
  7690. /** @type {Node[]} */ (/** @type {NestableAtRuleThis} */ (path[i]).features.value) : /** @type {NestableAtRuleThis} */ (path[i]).features;
  7691. path[i] = /** @type {Node} */ (/** @type {unknown} */ (Array.isArray(value) ? value : [value]));
  7692. }
  7693. // Trace all permutations to generate the resulting media-query.
  7694. //
  7695. // (a, b and c) with nested (d, e) ->
  7696. // a and d
  7697. // a and e
  7698. // b and c and d
  7699. // b and c and e
  7700. self.features = new Value(self.permute(/** @type {Node[][]} */ (/** @type {unknown} */ (path))).map(
  7701. /** @param {Node | Node[]} path */
  7702. path => {
  7703. path = /** @type {Node[]} */ (path).map(
  7704. /** @param {Node & { toCSS?: Function }} fragment */
  7705. fragment => fragment.toCSS ? fragment : new Anonymous(/** @type {string} */ (/** @type {unknown} */ (fragment))));
  7706. for (i = /** @type {Node[]} */ (path).length - 1; i > 0; i--) {
  7707. /** @type {Node[]} */ (path).splice(i, 0, new Anonymous('and'));
  7708. }
  7709. return new Expression(/** @type {Node[]} */ (path));
  7710. }));
  7711. self.setParent(self.features, self);
  7712. // Fake a tree-node that doesn't output anything.
  7713. return new Ruleset([], []);
  7714. },
  7715. /**
  7716. * @param {Node[][]} arr
  7717. * @returns {Node[][]}
  7718. */
  7719. permute(arr) {
  7720. if (arr.length === 0) {
  7721. return [];
  7722. } else if (arr.length === 1) {
  7723. return /** @type {Node[][]} */ (/** @type {unknown} */ (arr[0]));
  7724. } else {
  7725. /** @type {Node[][]} */
  7726. const result = [];
  7727. const rest = this.permute(arr.slice(1));
  7728. for (let i = 0; i < rest.length; i++) {
  7729. for (let j = 0; j < arr[0].length; j++) {
  7730. result.push([arr[0][j]].concat(rest[i]));
  7731. }
  7732. }
  7733. return result;
  7734. }
  7735. },
  7736. /** @param {Selector[] | undefined} selectors */
  7737. bubbleSelectors(selectors) {
  7738. /** @type {NestableAtRuleThis} */
  7739. const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
  7740. if (!selectors) {
  7741. return;
  7742. }
  7743. self.rules = [new Ruleset(copyArray(selectors), [self.rules[0]])];
  7744. self.setParent(self.rules, self);
  7745. }
  7746. };
  7747. // @ts-check
  7748. /**
  7749. * @typedef {Node & {
  7750. * rules?: Node[],
  7751. * selectors?: Selector[],
  7752. * root?: boolean,
  7753. * allowImports?: boolean,
  7754. * functionRegistry?: FunctionRegistry,
  7755. * merge?: boolean,
  7756. * debugInfo?: { lineNumber: number, fileName: string },
  7757. * elements?: import('./element.js').default[]
  7758. * }} RulesetLikeNode
  7759. */
  7760. class AtRule extends Node {
  7761. get type() { return 'AtRule'; }
  7762. /**
  7763. * @param {string} [name]
  7764. * @param {Node | string} [value]
  7765. * @param {Node[] | Ruleset} [rules]
  7766. * @param {number} [index]
  7767. * @param {FileInfo} [currentFileInfo]
  7768. * @param {{ lineNumber: number, fileName: string }} [debugInfo]
  7769. * @param {boolean} [isRooted]
  7770. * @param {VisibilityInfo} [visibilityInfo]
  7771. */
  7772. constructor(
  7773. name,
  7774. value,
  7775. rules,
  7776. index,
  7777. currentFileInfo,
  7778. debugInfo,
  7779. isRooted,
  7780. visibilityInfo
  7781. ) {
  7782. super();
  7783. let i;
  7784. (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
  7785. /** @type {string | undefined} */
  7786. this.name = name;
  7787. this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
  7788. /** @type {boolean | undefined} */
  7789. this.simpleBlock = undefined;
  7790. /** @type {RulesetLikeNode[] | undefined} */
  7791. this.declarations = undefined;
  7792. /** @type {RulesetLikeNode[] | undefined} */
  7793. this.rules = undefined;
  7794. if (rules) {
  7795. if (Array.isArray(rules)) {
  7796. const allDeclarations = this.declarationsBlock(rules);
  7797. let allRulesetDeclarations = true;
  7798. rules.forEach(rule => {
  7799. if (rule.type === 'Ruleset' && /** @type {RulesetLikeNode} */ (rule).rules) allRulesetDeclarations = allRulesetDeclarations && this.declarationsBlock(/** @type {Node[]} */ (/** @type {RulesetLikeNode} */ (rule).rules), true);
  7800. });
  7801. if (allDeclarations && !isRooted) {
  7802. this.simpleBlock = true;
  7803. this.declarations = rules;
  7804. } else if (allRulesetDeclarations && rules.length === 1 && !isRooted && !value) {
  7805. this.simpleBlock = true;
  7806. this.declarations = /** @type {RulesetLikeNode} */ (rules[0]).rules ? /** @type {RulesetLikeNode} */ (rules[0]).rules : rules;
  7807. } else {
  7808. this.rules = rules;
  7809. }
  7810. } else {
  7811. const allDeclarations = this.declarationsBlock(/** @type {Node[]} */ (rules.rules));
  7812. if (allDeclarations && !isRooted && !value) {
  7813. this.simpleBlock = true;
  7814. this.declarations = rules.rules;
  7815. } else {
  7816. this.rules = [rules];
  7817. /** @type {RulesetLikeNode} */ (this.rules[0]).selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
  7818. }
  7819. }
  7820. if (!this.simpleBlock) {
  7821. for (i = 0; i < this.rules.length; i++) {
  7822. /** @type {RulesetLikeNode} */ (this.rules[i]).allowImports = true;
  7823. }
  7824. }
  7825. if (this.declarations) {
  7826. this.setParent(this.declarations, /** @type {Node} */ (/** @type {unknown} */ (this)));
  7827. }
  7828. if (this.rules) {
  7829. this.setParent(this.rules, /** @type {Node} */ (/** @type {unknown} */ (this)));
  7830. }
  7831. }
  7832. this._index = index;
  7833. this._fileInfo = currentFileInfo;
  7834. /** @type {{ lineNumber: number, fileName: string } | undefined} */
  7835. this.debugInfo = debugInfo;
  7836. /** @type {boolean} */
  7837. this.isRooted = isRooted || false;
  7838. this.copyVisibilityInfo(visibilityInfo);
  7839. this.allowRoot = true;
  7840. }
  7841. /**
  7842. * @param {Node[]} rules
  7843. * @param {boolean} [mergeable]
  7844. * @returns {boolean}
  7845. */
  7846. declarationsBlock(rules, mergeable = false) {
  7847. if (!mergeable) {
  7848. return rules.filter(function (/** @type {Node & { merge?: boolean }} */ node) { return (node.type === 'Declaration' || node.type === 'Comment') && !node.merge}).length === rules.length;
  7849. } else {
  7850. return rules.filter(function (/** @type {Node} */ node) { return (node.type === 'Declaration' || node.type === 'Comment'); }).length === rules.length;
  7851. }
  7852. }
  7853. /**
  7854. * @param {Node[]} rules
  7855. * @returns {boolean}
  7856. */
  7857. keywordList(rules) {
  7858. if (!Array.isArray(rules)) {
  7859. return false;
  7860. } else {
  7861. return rules.filter(function (/** @type {Node} */ node) { return (node.type === 'Keyword' || node.type === 'Comment'); }).length === rules.length;
  7862. }
  7863. }
  7864. /** @param {TreeVisitor} visitor */
  7865. accept(visitor) {
  7866. const value = this.value, rules = this.rules, declarations = this.declarations;
  7867. if (rules) {
  7868. this.rules = visitor.visitArray(rules);
  7869. } else if (declarations) {
  7870. this.declarations = visitor.visitArray(declarations);
  7871. }
  7872. if (value) {
  7873. this.value = visitor.visit(/** @type {Node} */ (value));
  7874. }
  7875. }
  7876. /** @override @returns {boolean} */
  7877. isRulesetLike() {
  7878. return /** @type {boolean} */ (/** @type {unknown} */ (this.rules || !this.isCharset()));
  7879. }
  7880. isCharset() {
  7881. return '@charset' === this.name;
  7882. }
  7883. /**
  7884. * @param {EvalContext} context
  7885. * @param {CSSOutput} output
  7886. */
  7887. genCSS(context, output) {
  7888. const value = this.value, rules = this.rules || this.declarations;
  7889. output.add(/** @type {string} */ (this.name), this.fileInfo(), this.getIndex());
  7890. if (value) {
  7891. output.add(' ');
  7892. /** @type {Node} */ (value).genCSS(context, output);
  7893. }
  7894. if (this.simpleBlock) {
  7895. this.outputRuleset(context, output, /** @type {Node[]} */ (this.declarations));
  7896. } else if (rules) {
  7897. this.outputRuleset(context, output, rules);
  7898. } else {
  7899. output.add(';');
  7900. }
  7901. }
  7902. /**
  7903. * @param {EvalContext} context
  7904. * @returns {Node}
  7905. */
  7906. eval(context) {
  7907. let mediaPathBackup, mediaBlocksBackup, value = this.value, rules = this.rules || this.declarations;
  7908. // media stored inside other atrule should not bubble over it
  7909. // backpup media bubbling information
  7910. mediaPathBackup = context.mediaPath;
  7911. mediaBlocksBackup = context.mediaBlocks;
  7912. // deleted media bubbling information
  7913. context.mediaPath = [];
  7914. context.mediaBlocks = [];
  7915. if (value) {
  7916. value = /** @type {Node} */ (value).eval(context);
  7917. }
  7918. if (rules) {
  7919. rules = this.evalRoot(context, rules);
  7920. }
  7921. if (Array.isArray(rules) && /** @type {RulesetLikeNode} */ (rules[0]).rules && Array.isArray(/** @type {RulesetLikeNode} */ (rules[0]).rules) && /** @type {Node[]} */ (/** @type {RulesetLikeNode} */ (rules[0]).rules).length) {
  7922. const allMergeableDeclarations = this.declarationsBlock(/** @type {Node[]} */ (/** @type {RulesetLikeNode} */ (rules[0]).rules), true);
  7923. if (allMergeableDeclarations && !this.isRooted && !value) {
  7924. mergeRules(/** @type {Node[]} */ (/** @type {RulesetLikeNode} */ (rules[0]).rules));
  7925. rules = /** @type {RulesetLikeNode[]} */ (/** @type {RulesetLikeNode} */ (rules[0]).rules);
  7926. rules.forEach(/** @param {RulesetLikeNode} rule */ rule => { rule.merge = false; });
  7927. }
  7928. }
  7929. if (this.simpleBlock && rules) {
  7930. /** @type {RulesetLikeNode} */ (rules[0]).functionRegistry = /** @type {RulesetLikeNode} */ (context.frames[0]).functionRegistry.inherit();
  7931. rules = rules.map(function (/** @type {Node} */ rule) { return rule.eval(context); });
  7932. }
  7933. // restore media bubbling information
  7934. context.mediaPath = mediaPathBackup;
  7935. context.mediaBlocks = mediaBlocksBackup;
  7936. return /** @type {Node} */ (/** @type {unknown} */ (new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo())));
  7937. }
  7938. /**
  7939. * @param {EvalContext} context
  7940. * @param {Node[]} rules
  7941. * @returns {Node[]}
  7942. */
  7943. evalRoot(context, rules) {
  7944. let ampersandCount = 0;
  7945. let noAmpersandCount = 0;
  7946. let noAmpersands = true;
  7947. if (!this.simpleBlock) {
  7948. rules = [rules[0].eval(context)];
  7949. }
  7950. /** @type {Selector[]} */
  7951. let precedingSelectors = [];
  7952. if (context.frames.length > 0) {
  7953. for (let index = 0; index < context.frames.length; index++) {
  7954. const frame = /** @type {RulesetLikeNode} */ (context.frames[index]);
  7955. if (
  7956. frame.type === 'Ruleset' &&
  7957. frame.rules &&
  7958. frame.rules.length > 0
  7959. ) {
  7960. if (frame && !frame.root && frame.selectors && frame.selectors.length > 0) {
  7961. precedingSelectors = precedingSelectors.concat(frame.selectors);
  7962. }
  7963. }
  7964. if (precedingSelectors.length > 0) {
  7965. const allAmpersandElements = precedingSelectors.every(
  7966. sel => sel.elements && sel.elements.length > 0 && sel.elements.every(
  7967. /** @param {import('./element.js').default} el */
  7968. el => el.value === '&'
  7969. )
  7970. );
  7971. if (allAmpersandElements) {
  7972. noAmpersands = false;
  7973. noAmpersandCount++;
  7974. } else {
  7975. ampersandCount++;
  7976. }
  7977. }
  7978. }
  7979. }
  7980. const mixedAmpersands = ampersandCount > 0 && noAmpersandCount > 0 && !noAmpersands;
  7981. if (
  7982. (this.isRooted && ampersandCount > 0 && noAmpersandCount === 0 && noAmpersands)
  7983. || !mixedAmpersands
  7984. ) {
  7985. /** @type {RulesetLikeNode} */ (rules[0]).root = true;
  7986. }
  7987. return rules;
  7988. }
  7989. /** @param {string} name */
  7990. variable(name) {
  7991. if (this.rules) {
  7992. // assuming that there is only one rule at this point - that is how parser constructs the rule
  7993. return Ruleset.prototype.variable.call(this.rules[0], name);
  7994. }
  7995. }
  7996. find() {
  7997. if (this.rules) {
  7998. // assuming that there is only one rule at this point - that is how parser constructs the rule
  7999. return Ruleset.prototype.find.apply(this.rules[0], arguments);
  8000. }
  8001. }
  8002. rulesets() {
  8003. if (this.rules) {
  8004. // assuming that there is only one rule at this point - that is how parser constructs the rule
  8005. return Ruleset.prototype.rulesets.apply(this.rules[0]);
  8006. }
  8007. }
  8008. /**
  8009. * @param {EvalContext} context
  8010. * @param {CSSOutput} output
  8011. * @param {Node[]} rules
  8012. */
  8013. outputRuleset(context, output, rules) {
  8014. const ruleCnt = rules.length;
  8015. let i;
  8016. context.tabLevel = (context.tabLevel | 0) + 1;
  8017. // Compressed
  8018. if (context.compress) {
  8019. output.add('{');
  8020. for (i = 0; i < ruleCnt; i++) {
  8021. rules[i].genCSS(context, output);
  8022. }
  8023. output.add('}');
  8024. context.tabLevel--;
  8025. return;
  8026. }
  8027. // Non-compressed
  8028. const tabSetStr = `\n${Array(context.tabLevel).join(' ')}`, tabRuleStr = `${tabSetStr} `;
  8029. if (!ruleCnt) {
  8030. output.add(` {${tabSetStr}}`);
  8031. } else {
  8032. output.add(` {${tabRuleStr}`);
  8033. rules[0].genCSS(context, output);
  8034. for (i = 1; i < ruleCnt; i++) {
  8035. output.add(tabRuleStr);
  8036. rules[i].genCSS(context, output);
  8037. }
  8038. output.add(`${tabSetStr}}`);
  8039. }
  8040. context.tabLevel--;
  8041. }
  8042. }
  8043. // Apply shared methods from NestableAtRulePrototype that AtRule doesn't override
  8044. const { evalFunction, evalTop, evalNested, permute, bubbleSelectors } = NestableAtRulePrototype;
  8045. Object.assign(AtRule.prototype, { evalFunction, evalTop, evalNested, permute, bubbleSelectors });
  8046. // @ts-check
  8047. class DetachedRuleset extends Node {
  8048. get type() { return 'DetachedRuleset'; }
  8049. /**
  8050. * @param {Node} ruleset
  8051. * @param {Node[]} [frames]
  8052. */
  8053. constructor(ruleset, frames) {
  8054. super();
  8055. this.ruleset = ruleset;
  8056. this.frames = frames;
  8057. this.evalFirst = true;
  8058. this.setParent(this.ruleset, this);
  8059. }
  8060. /** @param {TreeVisitor} visitor */
  8061. accept(visitor) {
  8062. this.ruleset = visitor.visit(this.ruleset);
  8063. }
  8064. /**
  8065. * @param {EvalContext} context
  8066. * @returns {DetachedRuleset}
  8067. */
  8068. eval(context) {
  8069. const frames = this.frames || copyArray(context.frames);
  8070. return new DetachedRuleset(this.ruleset, frames);
  8071. }
  8072. /**
  8073. * @param {EvalContext} context
  8074. * @returns {Node}
  8075. */
  8076. callEval(context) {
  8077. return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
  8078. }
  8079. }
  8080. // @ts-check
  8081. const MATH = Math$1;
  8082. class Operation extends Node {
  8083. get type() { return 'Operation'; }
  8084. /**
  8085. * @param {string} op
  8086. * @param {Node[]} operands
  8087. * @param {boolean} isSpaced
  8088. */
  8089. constructor(op, operands, isSpaced) {
  8090. super();
  8091. this.op = op.trim();
  8092. this.operands = operands;
  8093. this.isSpaced = isSpaced;
  8094. }
  8095. /** @param {TreeVisitor} visitor */
  8096. accept(visitor) {
  8097. this.operands = visitor.visitArray(this.operands);
  8098. }
  8099. /**
  8100. * @param {EvalContext} context
  8101. * @returns {Node}
  8102. */
  8103. eval(context) {
  8104. let a = this.operands[0].eval(context), b = this.operands[1].eval(context), op;
  8105. if (context.isMathOn(this.op)) {
  8106. op = this.op === './' ? '/' : this.op;
  8107. if (a instanceof Dimension && b instanceof Color) {
  8108. a = /** @type {Dimension} */ (a).toColor();
  8109. }
  8110. if (b instanceof Dimension && a instanceof Color) {
  8111. b = /** @type {Dimension} */ (b).toColor();
  8112. }
  8113. if (!/** @type {Dimension | Color} */ (a).operate || !/** @type {Dimension | Color} */ (b).operate) {
  8114. if (
  8115. (a instanceof Operation || b instanceof Operation)
  8116. && /** @type {Operation} */ (a).op === '/' && context.math === MATH.PARENS_DIVISION
  8117. ) {
  8118. return new Operation(this.op, [a, b], this.isSpaced);
  8119. }
  8120. throw { type: 'Operation',
  8121. message: 'Operation on an invalid type' };
  8122. }
  8123. if (a instanceof Dimension) {
  8124. return a.operate(context, op, /** @type {Dimension} */ (b));
  8125. }
  8126. return /** @type {Color} */ (a).operate(context, op, /** @type {Color} */ (b));
  8127. } else {
  8128. return new Operation(this.op, [a, b], this.isSpaced);
  8129. }
  8130. }
  8131. /**
  8132. * @param {EvalContext} context
  8133. * @param {CSSOutput} output
  8134. */
  8135. genCSS(context, output) {
  8136. this.operands[0].genCSS(context, output);
  8137. if (this.isSpaced) {
  8138. output.add(' ');
  8139. }
  8140. output.add(this.op);
  8141. if (this.isSpaced) {
  8142. output.add(' ');
  8143. }
  8144. this.operands[1].genCSS(context, output);
  8145. }
  8146. }
  8147. class functionCaller {
  8148. constructor(name, context, index, currentFileInfo) {
  8149. this.name = name.toLowerCase();
  8150. this.index = index;
  8151. this.context = context;
  8152. this.currentFileInfo = currentFileInfo;
  8153. this.func = context.frames[0].functionRegistry.get(this.name);
  8154. }
  8155. isValid() {
  8156. return Boolean(this.func);
  8157. }
  8158. call(args) {
  8159. if (!(Array.isArray(args))) {
  8160. args = [args];
  8161. }
  8162. const evalArgs = this.func.evalArgs;
  8163. if (evalArgs !== false) {
  8164. args = args.map(a => a.eval(this.context));
  8165. }
  8166. const commentFilter = item => !(item.type === 'Comment');
  8167. // This code is terrible and should be replaced as per this issue...
  8168. // https://github.com/less/less.js/issues/2477
  8169. args = args
  8170. .filter(commentFilter)
  8171. .map(item => {
  8172. if (item.type === 'Expression') {
  8173. const subNodes = item.value.filter(commentFilter);
  8174. if (subNodes.length === 1) {
  8175. // https://github.com/less/less.js/issues/3616
  8176. if (item.parens && subNodes[0].op === '/') {
  8177. return item;
  8178. }
  8179. return subNodes[0];
  8180. } else {
  8181. return new Expression(subNodes);
  8182. }
  8183. }
  8184. return item;
  8185. });
  8186. if (evalArgs === false) {
  8187. return this.func(this.context, ...args);
  8188. }
  8189. return this.func(...args);
  8190. }
  8191. }
  8192. // @ts-check
  8193. //
  8194. // A function call node.
  8195. //
  8196. class Call extends Node {
  8197. get type() { return 'Call'; }
  8198. /**
  8199. * @param {string} name
  8200. * @param {Node[]} args
  8201. * @param {number} index
  8202. * @param {FileInfo} currentFileInfo
  8203. */
  8204. constructor(name, args, index, currentFileInfo) {
  8205. super();
  8206. this.name = name;
  8207. this.args = args;
  8208. this.calc = name === 'calc';
  8209. this._index = index;
  8210. this._fileInfo = currentFileInfo;
  8211. }
  8212. /** @param {TreeVisitor} visitor */
  8213. accept(visitor) {
  8214. if (this.args) {
  8215. this.args = visitor.visitArray(this.args);
  8216. }
  8217. }
  8218. //
  8219. // When evaluating a function call,
  8220. // we either find the function in the functionRegistry,
  8221. // in which case we call it, passing the evaluated arguments,
  8222. // if this returns null or we cannot find the function, we
  8223. // simply print it out as it appeared originally [2].
  8224. //
  8225. // The reason why we evaluate the arguments, is in the case where
  8226. // we try to pass a variable to a function, like: `saturate(@color)`.
  8227. // The function should receive the value, not the variable.
  8228. //
  8229. /**
  8230. * @param {EvalContext} context
  8231. * @returns {Node}
  8232. */
  8233. eval(context) {
  8234. /**
  8235. * Turn off math for calc(), and switch back on for evaluating nested functions
  8236. */
  8237. const currentMathContext = context.mathOn;
  8238. context.mathOn = !this.calc;
  8239. if (this.calc || context.inCalc) {
  8240. context.enterCalc();
  8241. }
  8242. const exitCalc = () => {
  8243. if (this.calc || context.inCalc) {
  8244. context.exitCalc();
  8245. }
  8246. context.mathOn = currentMathContext;
  8247. };
  8248. /** @type {Node | string | boolean | null | undefined} */
  8249. let result;
  8250. const funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
  8251. if (funcCaller.isValid()) {
  8252. try {
  8253. result = funcCaller.call(this.args);
  8254. exitCalc();
  8255. } catch (e) {
  8256. // eslint-disable-next-line no-prototype-builtins
  8257. if (/** @type {Record<string, unknown>} */ (e).hasOwnProperty('line') && /** @type {Record<string, unknown>} */ (e).hasOwnProperty('column')) {
  8258. throw e;
  8259. }
  8260. throw {
  8261. type: /** @type {Record<string, string>} */ (e).type || 'Runtime',
  8262. message: `Error evaluating function \`${this.name}\`${/** @type {Error} */ (e).message ? `: ${/** @type {Error} */ (e).message}` : ''}`,
  8263. index: this.getIndex(),
  8264. filename: this.fileInfo().filename,
  8265. line: /** @type {Record<string, number>} */ (e).lineNumber,
  8266. column: /** @type {Record<string, number>} */ (e).columnNumber
  8267. };
  8268. }
  8269. }
  8270. if (result !== null && result !== undefined) {
  8271. // Results that that are not nodes are cast as Anonymous nodes
  8272. // Falsy values or booleans are returned as empty nodes
  8273. if (!(result instanceof Node)) {
  8274. if (!result || result === true) {
  8275. result = new Anonymous(null);
  8276. }
  8277. else {
  8278. result = new Anonymous(result.toString());
  8279. }
  8280. }
  8281. result._index = this._index;
  8282. result._fileInfo = this._fileInfo;
  8283. return result;
  8284. }
  8285. const args = this.args.map(a => a.eval(context));
  8286. exitCalc();
  8287. return new Call(this.name, args, this.getIndex(), this.fileInfo());
  8288. }
  8289. /**
  8290. * @param {EvalContext} context
  8291. * @param {CSSOutput} output
  8292. */
  8293. genCSS(context, output) {
  8294. output.add(`${this.name}(`, this.fileInfo(), this.getIndex());
  8295. for (let i = 0; i < this.args.length; i++) {
  8296. this.args[i].genCSS(context, output);
  8297. if (i + 1 < this.args.length) {
  8298. output.add(', ');
  8299. }
  8300. }
  8301. output.add(')');
  8302. }
  8303. }
  8304. // @ts-check
  8305. class Variable extends Node {
  8306. get type() { return 'Variable'; }
  8307. /**
  8308. * @param {string} name
  8309. * @param {number} [index]
  8310. * @param {FileInfo} [currentFileInfo]
  8311. */
  8312. constructor(name, index, currentFileInfo) {
  8313. super();
  8314. this.name = name;
  8315. this._index = index;
  8316. this._fileInfo = currentFileInfo;
  8317. /** @type {boolean | undefined} */
  8318. this.evaluating = undefined;
  8319. }
  8320. /**
  8321. * @param {EvalContext} context
  8322. * @returns {Node}
  8323. */
  8324. eval(context) {
  8325. let variable, name = this.name;
  8326. if (name.indexOf('@@') === 0) {
  8327. name = `@${new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value}`;
  8328. }
  8329. if (this.evaluating) {
  8330. throw { type: 'Name',
  8331. message: `Recursive variable definition for ${name}`,
  8332. filename: this.fileInfo().filename,
  8333. index: this.getIndex() };
  8334. }
  8335. this.evaluating = true;
  8336. variable = this.find(context.frames, function (frame) {
  8337. const v = /** @type {Ruleset} */ (frame).variable(name);
  8338. if (v) {
  8339. if (v.important) {
  8340. const importantScope = context.importantScope[context.importantScope.length - 1];
  8341. importantScope.important = v.important;
  8342. }
  8343. // If in calc, wrap vars in a function call to cascade evaluate args first
  8344. if (context.inCalc) {
  8345. return (new Call('_SELF', [v.value], 0, undefined)).eval(context);
  8346. }
  8347. else {
  8348. return v.value.eval(context);
  8349. }
  8350. }
  8351. });
  8352. if (variable) {
  8353. this.evaluating = false;
  8354. return variable;
  8355. } else {
  8356. throw { type: 'Name',
  8357. message: `variable ${name} is undefined`,
  8358. filename: this.fileInfo().filename,
  8359. index: this.getIndex() };
  8360. }
  8361. }
  8362. /**
  8363. * @param {Node[]} obj
  8364. * @param {(frame: Node) => Node | undefined} fun
  8365. * @returns {Node | null}
  8366. */
  8367. find(obj, fun) {
  8368. for (let i = 0, r; i < obj.length; i++) {
  8369. r = fun.call(obj, obj[i]);
  8370. if (r) { return r; }
  8371. }
  8372. return null;
  8373. }
  8374. }
  8375. // @ts-check
  8376. class Property extends Node {
  8377. get type() { return 'Property'; }
  8378. /**
  8379. * @param {string} name
  8380. * @param {number} index
  8381. * @param {FileInfo} currentFileInfo
  8382. */
  8383. constructor(name, index, currentFileInfo) {
  8384. super();
  8385. this.name = name;
  8386. this._index = index;
  8387. this._fileInfo = currentFileInfo;
  8388. /** @type {boolean | undefined} */
  8389. this.evaluating = undefined;
  8390. }
  8391. /**
  8392. * @param {EvalContext} context
  8393. * @returns {Node}
  8394. */
  8395. eval(context) {
  8396. let property;
  8397. const name = this.name;
  8398. // TODO: shorten this reference
  8399. const mergeRules = /** @type {{ less: { visitors: { ToCSSVisitor: { prototype: { _mergeRules: (rules: Declaration[]) => void } } } } }} */ (context.pluginManager).less.visitors.ToCSSVisitor.prototype._mergeRules;
  8400. if (this.evaluating) {
  8401. throw { type: 'Name',
  8402. message: `Recursive property reference for ${name}`,
  8403. filename: this.fileInfo().filename,
  8404. index: this.getIndex() };
  8405. }
  8406. this.evaluating = true;
  8407. property = this.find(context.frames, function (/** @type {Node} */ frame) {
  8408. let v;
  8409. const vArr = /** @type {Ruleset} */ (frame).property(name);
  8410. if (vArr) {
  8411. for (let i = 0; i < vArr.length; i++) {
  8412. v = vArr[i];
  8413. vArr[i] = new Declaration(v.name,
  8414. v.value,
  8415. v.important,
  8416. v.merge,
  8417. v.index,
  8418. v.currentFileInfo,
  8419. v.inline,
  8420. v.variable
  8421. );
  8422. }
  8423. mergeRules(vArr);
  8424. v = vArr[vArr.length - 1];
  8425. if (v.important) {
  8426. const importantScope = context.importantScope[context.importantScope.length - 1];
  8427. importantScope.important = v.important;
  8428. }
  8429. v = v.value.eval(context);
  8430. return v;
  8431. }
  8432. });
  8433. if (property) {
  8434. this.evaluating = false;
  8435. return property;
  8436. } else {
  8437. throw { type: 'Name',
  8438. message: `Property '${name}' is undefined`,
  8439. filename: this.currentFileInfo.filename,
  8440. index: this.index };
  8441. }
  8442. }
  8443. /**
  8444. * @param {Node[]} obj
  8445. * @param {(frame: Node) => Node | undefined} fun
  8446. * @returns {Node | null}
  8447. */
  8448. find(obj, fun) {
  8449. for (let i = 0, r; i < obj.length; i++) {
  8450. r = fun.call(obj, obj[i]);
  8451. if (r) { return r; }
  8452. }
  8453. return null;
  8454. }
  8455. }
  8456. // @ts-check
  8457. class Attribute extends Node {
  8458. get type() { return 'Attribute'; }
  8459. /**
  8460. * @param {string | Node} key
  8461. * @param {string} op
  8462. * @param {string | Node} value
  8463. * @param {string} cif
  8464. */
  8465. constructor(key, op, value, cif) {
  8466. super();
  8467. this.key = key;
  8468. this.op = op;
  8469. this.value = value;
  8470. this.cif = cif;
  8471. }
  8472. /**
  8473. * @param {EvalContext} context
  8474. * @returns {Attribute}
  8475. */
  8476. eval(context) {
  8477. return new Attribute(
  8478. /** @type {Node} */ (this.key).eval ? /** @type {Node} */ (this.key).eval(context) : /** @type {string} */ (this.key),
  8479. this.op,
  8480. (this.value && /** @type {Node} */ (this.value).eval) ? /** @type {Node} */ (this.value).eval(context) : this.value,
  8481. this.cif
  8482. );
  8483. }
  8484. /**
  8485. * @param {EvalContext} context
  8486. * @param {CSSOutput} output
  8487. */
  8488. genCSS(context, output) {
  8489. output.add(this.toCSS(context));
  8490. }
  8491. /**
  8492. * @param {EvalContext} context
  8493. * @returns {string}
  8494. */
  8495. toCSS(context) {
  8496. let value = /** @type {Node} */ (this.key).toCSS ? /** @type {Node} */ (this.key).toCSS(context) : /** @type {string} */ (this.key);
  8497. if (this.op) {
  8498. value += this.op;
  8499. value += (/** @type {Node} */ (this.value).toCSS ? /** @type {Node} */ (this.value).toCSS(context) : /** @type {string} */ (this.value));
  8500. }
  8501. if (this.cif) {
  8502. value = value + ' ' + this.cif;
  8503. }
  8504. return `[${value}]`;
  8505. }
  8506. }
  8507. // @ts-check
  8508. class Quoted extends Node {
  8509. get type() { return 'Quoted'; }
  8510. /**
  8511. * @param {string} str
  8512. * @param {string} [content]
  8513. * @param {boolean} [escaped]
  8514. * @param {number} [index]
  8515. * @param {FileInfo} [currentFileInfo]
  8516. */
  8517. constructor(str, content, escaped, index, currentFileInfo) {
  8518. super();
  8519. /** @type {boolean} */
  8520. this.escaped = (escaped === undefined) ? true : escaped;
  8521. /** @type {string} */
  8522. this.value = content || '';
  8523. /** @type {string} */
  8524. this.quote = str.charAt(0);
  8525. this._index = index;
  8526. this._fileInfo = currentFileInfo;
  8527. /** @type {RegExp} */
  8528. this.variableRegex = /@\{([\w-]+)\}/g;
  8529. /** @type {RegExp} */
  8530. this.propRegex = /\$\{([\w-]+)\}/g;
  8531. /** @type {boolean | undefined} */
  8532. this.allowRoot = escaped;
  8533. }
  8534. /**
  8535. * @param {EvalContext} context
  8536. * @param {CSSOutput} output
  8537. */
  8538. genCSS(context, output) {
  8539. if (!this.escaped) {
  8540. output.add(this.quote, this.fileInfo(), this.getIndex());
  8541. }
  8542. output.add(/** @type {string} */ (this.value));
  8543. if (!this.escaped) {
  8544. output.add(this.quote);
  8545. }
  8546. }
  8547. /** @returns {RegExpMatchArray | null} */
  8548. containsVariables() {
  8549. return /** @type {string} */ (this.value).match(this.variableRegex);
  8550. }
  8551. /** @param {EvalContext} context */
  8552. eval(context) {
  8553. const that = this;
  8554. let value = /** @type {string} */ (this.value);
  8555. /**
  8556. * @param {string} _
  8557. * @param {string} name1
  8558. * @param {string} name2
  8559. * @returns {string}
  8560. */
  8561. const variableReplacement = function (_, name1, name2) {
  8562. const v = new Variable(`@${name1 ?? name2}`, that.getIndex(), that.fileInfo()).eval(context);
  8563. return (v instanceof Quoted) ? /** @type {string} */ (v.value) : v.toCSS(context);
  8564. };
  8565. /**
  8566. * @param {string} _
  8567. * @param {string} name1
  8568. * @param {string} name2
  8569. * @returns {string}
  8570. */
  8571. const propertyReplacement = function (_, name1, name2) {
  8572. const v = new Property(`$${name1 ?? name2}`, that.getIndex(), that.fileInfo()).eval(context);
  8573. return (v instanceof Quoted) ? /** @type {string} */ (v.value) : v.toCSS(context);
  8574. };
  8575. /**
  8576. * @param {string} value
  8577. * @param {RegExp} regexp
  8578. * @param {(substring: string, ...args: string[]) => string} replacementFnc
  8579. * @returns {string}
  8580. */
  8581. function iterativeReplace(value, regexp, replacementFnc) {
  8582. let evaluatedValue = value;
  8583. do {
  8584. value = evaluatedValue.toString();
  8585. evaluatedValue = value.replace(regexp, replacementFnc);
  8586. } while (value !== evaluatedValue);
  8587. return evaluatedValue;
  8588. }
  8589. value = iterativeReplace(value, this.variableRegex, variableReplacement);
  8590. value = iterativeReplace(value, this.propRegex, propertyReplacement);
  8591. return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
  8592. }
  8593. /**
  8594. * @param {Node} other
  8595. * @returns {number | undefined}
  8596. */
  8597. compare(other) {
  8598. // when comparing quoted strings allow the quote to differ
  8599. if (other.type === 'Quoted' && !this.escaped && !/** @type {Quoted} */ (other).escaped) {
  8600. return Node.numericCompare(
  8601. /** @type {string} */ (this.value),
  8602. /** @type {string} */ (other.value)
  8603. );
  8604. } else {
  8605. return other.toCSS && this.toCSS(/** @type {EvalContext} */ ({})) === other.toCSS(/** @type {EvalContext} */ ({})) ? 0 : undefined;
  8606. }
  8607. }
  8608. }
  8609. // @ts-check
  8610. /**
  8611. * @param {string} path
  8612. * @returns {string}
  8613. */
  8614. function escapePath(path) {
  8615. return path.replace(/[()'"\s]/g, function(match) { return `\\${match}`; });
  8616. }
  8617. class URL extends Node {
  8618. get type() { return 'Url'; }
  8619. /**
  8620. * @param {Node} val
  8621. * @param {number} index
  8622. * @param {FileInfo} currentFileInfo
  8623. * @param {boolean} [isEvald]
  8624. */
  8625. constructor(val, index, currentFileInfo, isEvald) {
  8626. super();
  8627. this.value = val;
  8628. this._index = index;
  8629. this._fileInfo = currentFileInfo;
  8630. /** @type {boolean | undefined} */
  8631. this.isEvald = isEvald;
  8632. }
  8633. /** @param {TreeVisitor} visitor */
  8634. accept(visitor) {
  8635. this.value = visitor.visit(/** @type {Node} */ (this.value));
  8636. }
  8637. /**
  8638. * @param {EvalContext} context
  8639. * @param {CSSOutput} output
  8640. */
  8641. genCSS(context, output) {
  8642. output.add('url(');
  8643. /** @type {Node} */ (this.value).genCSS(context, output);
  8644. output.add(')');
  8645. }
  8646. /** @param {EvalContext} context */
  8647. eval(context) {
  8648. const val = /** @type {Node} */ (this.value).eval(context);
  8649. let rootpath;
  8650. if (!this.isEvald) {
  8651. // Add the rootpath if the URL requires a rewrite
  8652. rootpath = this.fileInfo() && this.fileInfo().rootpath;
  8653. if (typeof rootpath === 'string' &&
  8654. typeof val.value === 'string' &&
  8655. context.pathRequiresRewrite(/** @type {string} */ (val.value))) {
  8656. if (!/** @type {import('./quoted.js').default} */ (val).quote) {
  8657. rootpath = escapePath(rootpath);
  8658. }
  8659. val.value = context.rewritePath(/** @type {string} */ (val.value), rootpath);
  8660. } else {
  8661. val.value = context.normalizePath(/** @type {string} */ (val.value));
  8662. }
  8663. // Add url args if enabled
  8664. if (context.urlArgs) {
  8665. if (!/** @type {string} */ (val.value).match(/^\s*data:/)) {
  8666. const delimiter = /** @type {string} */ (val.value).indexOf('?') === -1 ? '?' : '&';
  8667. const urlArgs = delimiter + context.urlArgs;
  8668. if (/** @type {string} */ (val.value).indexOf('#') !== -1) {
  8669. val.value = /** @type {string} */ (val.value).replace('#', `${urlArgs}#`);
  8670. } else {
  8671. val.value += urlArgs;
  8672. }
  8673. }
  8674. }
  8675. }
  8676. return new URL(val, this.getIndex(), this.fileInfo(), true);
  8677. }
  8678. }
  8679. // @ts-check
  8680. class Media extends AtRule {
  8681. get type() { return 'Media'; }
  8682. /**
  8683. * @param {Node[] | null} value
  8684. * @param {Node[]} features
  8685. * @param {number} [index]
  8686. * @param {FileInfo} [currentFileInfo]
  8687. * @param {VisibilityInfo} [visibilityInfo]
  8688. */
  8689. constructor(value, features, index, currentFileInfo, visibilityInfo) {
  8690. super();
  8691. this._index = index;
  8692. this._fileInfo = currentFileInfo;
  8693. const selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
  8694. /** @type {Value} */
  8695. this.features = new Value(features);
  8696. /** @type {RulesetLikeNode[]} */
  8697. this.rules = [new Ruleset(selectors, value)];
  8698. /** @type {RulesetLikeNode} */ (this.rules[0]).allowImports = true;
  8699. this.copyVisibilityInfo(visibilityInfo);
  8700. this.allowRoot = true;
  8701. this.setParent(selectors, /** @type {Node} */ (/** @type {unknown} */ (this)));
  8702. this.setParent(this.features, /** @type {Node} */ (/** @type {unknown} */ (this)));
  8703. this.setParent(this.rules, /** @type {Node} */ (/** @type {unknown} */ (this)));
  8704. }
  8705. /**
  8706. * @param {EvalContext} context
  8707. * @param {CSSOutput} output
  8708. */
  8709. genCSS(context, output) {
  8710. output.add('@media ', this._fileInfo, this._index);
  8711. this.features.genCSS(context, output);
  8712. this.outputRuleset(context, output, this.rules);
  8713. }
  8714. /**
  8715. * @param {EvalContext} context
  8716. * @returns {Node}
  8717. */
  8718. eval(context) {
  8719. if (!context.mediaBlocks) {
  8720. context.mediaBlocks = [];
  8721. context.mediaPath = [];
  8722. }
  8723. const media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
  8724. if (this.debugInfo) {
  8725. /** @type {RulesetLikeNode} */ (this.rules[0]).debugInfo = this.debugInfo;
  8726. media.debugInfo = this.debugInfo;
  8727. }
  8728. media.features = /** @type {Value} */ (this.features.eval(context));
  8729. context.mediaPath.push(/** @type {Node} */ (/** @type {unknown} */ (media)));
  8730. context.mediaBlocks.push(/** @type {Node} */ (/** @type {unknown} */ (media)));
  8731. const fr = /** @type {RulesetLikeNode} */ (context.frames[0]).functionRegistry;
  8732. if (fr) {
  8733. /** @type {RulesetLikeNode} */ (this.rules[0]).functionRegistry = fr.inherit();
  8734. }
  8735. context.frames.unshift(this.rules[0]);
  8736. media.rules = [/** @type {RulesetLikeNode} */ (this.rules[0].eval(context))];
  8737. context.frames.shift();
  8738. context.mediaPath.pop();
  8739. return context.mediaPath.length === 0 ? /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (media)).evalTop(context) :
  8740. /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (media)).evalNested(context);
  8741. }
  8742. }
  8743. // Apply NestableAtRulePrototype methods (accept, isRulesetLike override AtRule's versions)
  8744. Object.assign(Media.prototype, NestableAtRulePrototype);
  8745. // @ts-check
  8746. /**
  8747. * @typedef {object} ImportOptions
  8748. * @property {boolean} [less]
  8749. * @property {boolean} [inline]
  8750. * @property {boolean} [isPlugin]
  8751. * @property {boolean} [reference]
  8752. */
  8753. //
  8754. // CSS @import node
  8755. //
  8756. // The general strategy here is that we don't want to wait
  8757. // for the parsing to be completed, before we start importing
  8758. // the file. That's because in the context of a browser,
  8759. // most of the time will be spent waiting for the server to respond.
  8760. //
  8761. // On creation, we push the import path to our import queue, though
  8762. // `import,push`, we also pass it a callback, which it'll call once
  8763. // the file has been fetched, and parsed.
  8764. //
  8765. class Import extends Node {
  8766. get type() { return 'Import'; }
  8767. /**
  8768. * @param {Node} path
  8769. * @param {Node | null} features
  8770. * @param {ImportOptions} options
  8771. * @param {number} index
  8772. * @param {FileInfo} [currentFileInfo]
  8773. * @param {VisibilityInfo} [visibilityInfo]
  8774. */
  8775. constructor(path, features, options, index, currentFileInfo, visibilityInfo) {
  8776. super();
  8777. /** @type {ImportOptions} */
  8778. this.options = options;
  8779. this._index = index;
  8780. this._fileInfo = currentFileInfo;
  8781. this.path = path;
  8782. /** @type {Node | null} */
  8783. this.features = features;
  8784. /** @type {boolean} */
  8785. this.allowRoot = true;
  8786. /** @type {boolean | undefined} */
  8787. this.css = undefined;
  8788. /** @type {boolean | undefined} */
  8789. this.layerCss = undefined;
  8790. /** @type {(Ruleset & { imports?: object, filename?: string, functions?: object, functionRegistry?: { addMultiple: (fns: object) => void } }) | undefined} */
  8791. this.root = undefined;
  8792. /** @type {string | undefined} */
  8793. this.importedFilename = undefined;
  8794. /** @type {boolean | (() => boolean) | undefined} */
  8795. this.skip = undefined;
  8796. /** @type {{ message: string, index: number, filename: string } | undefined} */
  8797. this.error = undefined;
  8798. if (this.options.less !== undefined || this.options.inline) {
  8799. this.css = !this.options.less || this.options.inline;
  8800. } else {
  8801. const pathValue = this.getPath();
  8802. if (pathValue && /[#.&?]css([?;].*)?$/.test(pathValue)) {
  8803. this.css = true;
  8804. }
  8805. }
  8806. this.copyVisibilityInfo(visibilityInfo);
  8807. if (this.features) {
  8808. this.setParent(this.features, /** @type {Node} */ (this));
  8809. }
  8810. this.setParent(this.path, /** @type {Node} */ (this));
  8811. }
  8812. /** @param {TreeVisitor} visitor */
  8813. accept(visitor) {
  8814. if (this.features) {
  8815. this.features = visitor.visit(this.features);
  8816. }
  8817. this.path = visitor.visit(this.path);
  8818. if (!this.options.isPlugin && !this.options.inline && this.root) {
  8819. this.root = /** @type {Ruleset} */ (visitor.visit(this.root));
  8820. }
  8821. }
  8822. /**
  8823. * @param {EvalContext} context
  8824. * @param {CSSOutput} output
  8825. */
  8826. genCSS(context, output) {
  8827. if (this.css && this.path._fileInfo.reference === undefined) {
  8828. output.add('@import ', this._fileInfo, this._index);
  8829. this.path.genCSS(context, output);
  8830. if (this.features) {
  8831. output.add(' ');
  8832. this.features.genCSS(context, output);
  8833. }
  8834. output.add(';');
  8835. }
  8836. }
  8837. /** @returns {string | undefined} */
  8838. getPath() {
  8839. return (this.path instanceof URL) ?
  8840. /** @type {string} */ (/** @type {Node} */ (this.path.value).value) :
  8841. /** @type {string | undefined} */ (this.path.value);
  8842. }
  8843. /** @returns {boolean | RegExpMatchArray | null} */
  8844. isVariableImport() {
  8845. let path = this.path;
  8846. if (path instanceof URL) {
  8847. path = /** @type {Node} */ (path.value);
  8848. }
  8849. if (path instanceof Quoted) {
  8850. return path.containsVariables();
  8851. }
  8852. return true;
  8853. }
  8854. /** @param {EvalContext} context */
  8855. evalForImport(context) {
  8856. let path = this.path;
  8857. if (path instanceof URL) {
  8858. path = /** @type {Node} */ (path.value);
  8859. }
  8860. return new Import(path.eval(context), this.features, this.options, this._index || 0, this._fileInfo, this.visibilityInfo());
  8861. }
  8862. /** @param {EvalContext} context */
  8863. evalPath(context) {
  8864. const path = this.path.eval(context);
  8865. const fileInfo = this._fileInfo;
  8866. if (!(path instanceof URL)) {
  8867. // Add the rootpath if the URL requires a rewrite
  8868. const pathValue = /** @type {string} */ (path.value);
  8869. if (fileInfo &&
  8870. pathValue &&
  8871. context.pathRequiresRewrite(pathValue)) {
  8872. path.value = context.rewritePath(pathValue, fileInfo.rootpath);
  8873. } else {
  8874. path.value = context.normalizePath(/** @type {string} */ (path.value));
  8875. }
  8876. }
  8877. return path;
  8878. }
  8879. /** @param {EvalContext} context */
  8880. // @ts-ignore - Import.eval returns Node | Node[] | Import (wider than Node.eval's Node return)
  8881. eval(context) {
  8882. const result = this.doEval(context);
  8883. if (this.options.reference || this.blocksVisibility()) {
  8884. if (Array.isArray(result)) {
  8885. result.forEach(function (node) {
  8886. node.addVisibilityBlock();
  8887. });
  8888. } else {
  8889. /** @type {Node} */ (result).addVisibilityBlock();
  8890. }
  8891. }
  8892. return result;
  8893. }
  8894. /** @param {EvalContext} context */
  8895. doEval(context) {
  8896. /** @type {Ruleset | undefined} */
  8897. let ruleset;
  8898. const features = this.features && this.features.eval(context);
  8899. if (this.options.isPlugin) {
  8900. if (this.root && this.root.eval) {
  8901. try {
  8902. this.root.eval(context);
  8903. }
  8904. catch (e) {
  8905. const err = /** @type {{ message: string }} */ (e);
  8906. err.message = 'Plugin error during evaluation';
  8907. throw new LessError(
  8908. /** @type {{ message: string, index?: number, filename?: string }} */ (e),
  8909. /** @type {{ imports: object }} */ (/** @type {unknown} */ (this.root)).imports,
  8910. /** @type {{ filename: string }} */ (/** @type {unknown} */ (this.root)).filename
  8911. );
  8912. }
  8913. }
  8914. const frame0 = /** @type {Ruleset & { functionRegistry?: { addMultiple: (fns: object) => void } }} */ (context.frames[0]);
  8915. const registry = frame0 && frame0.functionRegistry;
  8916. if (registry && this.root && this.root.functions) {
  8917. registry.addMultiple(this.root.functions);
  8918. }
  8919. return [];
  8920. }
  8921. if (this.skip) {
  8922. if (typeof this.skip === 'function') {
  8923. this.skip = this.skip();
  8924. }
  8925. if (this.skip) {
  8926. return [];
  8927. }
  8928. }
  8929. if (this.features) {
  8930. let featureValue = /** @type {Node[]} */ (this.features.value);
  8931. if (Array.isArray(featureValue) && featureValue.length >= 1) {
  8932. const expr = featureValue[0];
  8933. if (expr.type === 'Expression' && Array.isArray(expr.value) && /** @type {Node[]} */ (expr.value).length >= 2) {
  8934. featureValue = /** @type {Node[]} */ (expr.value);
  8935. const isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
  8936. && featureValue[1].type === 'Paren';
  8937. if (isLayer) {
  8938. this.css = false;
  8939. }
  8940. }
  8941. }
  8942. }
  8943. if (this.options.inline) {
  8944. const contents = new Anonymous(
  8945. /** @type {string} */ (/** @type {unknown} */ (this.root)),
  8946. 0,
  8947. {
  8948. filename: this.importedFilename,
  8949. reference: this.path._fileInfo && this.path._fileInfo.reference
  8950. },
  8951. true,
  8952. true
  8953. );
  8954. return this.features ? new Media([contents], /** @type {Node[]} */ (this.features.value)) : [contents];
  8955. } else if (this.css || this.layerCss) {
  8956. const newImport = new Import(this.evalPath(context), features, this.options, this._index || 0);
  8957. if (this.layerCss) {
  8958. newImport.css = this.layerCss;
  8959. newImport.path._fileInfo = this._fileInfo;
  8960. }
  8961. if (!newImport.css && this.error) {
  8962. throw this.error;
  8963. }
  8964. return newImport;
  8965. } else if (this.root) {
  8966. if (this.features) {
  8967. let featureValue = /** @type {Node[]} */ (this.features.value);
  8968. if (Array.isArray(featureValue) && featureValue.length === 1) {
  8969. const expr = featureValue[0];
  8970. if (expr.type === 'Expression' && Array.isArray(expr.value) && /** @type {Node[]} */ (expr.value).length >= 2) {
  8971. featureValue = /** @type {Node[]} */ (expr.value);
  8972. const isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
  8973. && featureValue[1].type === 'Paren';
  8974. if (isLayer) {
  8975. this.layerCss = true;
  8976. featureValue[0] = new Expression(/** @type {Node[]} */ (featureValue.slice(0, 2)));
  8977. featureValue.splice(1, 1);
  8978. /** @type {Expression} */ (featureValue[0]).noSpacing = true;
  8979. return this;
  8980. }
  8981. }
  8982. }
  8983. }
  8984. ruleset = new Ruleset(null, copyArray(this.root.rules));
  8985. ruleset.evalImports(context);
  8986. return this.features ? new Media(ruleset.rules, /** @type {Node[]} */ (this.features.value)) : ruleset.rules;
  8987. } else {
  8988. if (this.features) {
  8989. let featureValue = /** @type {Node[]} */ (this.features.value);
  8990. if (Array.isArray(featureValue) && featureValue.length >= 1) {
  8991. featureValue = /** @type {Node[]} */ (featureValue[0].value);
  8992. if (Array.isArray(featureValue) && featureValue.length >= 2) {
  8993. const isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
  8994. && featureValue[1].type === 'Paren';
  8995. if (isLayer) {
  8996. this.css = true;
  8997. featureValue[0] = new Expression(/** @type {Node[]} */ (featureValue.slice(0, 2)));
  8998. featureValue.splice(1, 1);
  8999. /** @type {Expression} */ (featureValue[0]).noSpacing = true;
  9000. return this;
  9001. }
  9002. }
  9003. }
  9004. }
  9005. return [];
  9006. }
  9007. }
  9008. }
  9009. // @ts-check
  9010. class JsEvalNode extends Node {
  9011. /**
  9012. * @param {string} expression
  9013. * @param {EvalContext} context
  9014. * @returns {string | number | boolean}
  9015. */
  9016. evaluateJavaScript(expression, context) {
  9017. let result;
  9018. const that = this;
  9019. /** @type {Record<string, { value: Node, toJS: () => string }>} */
  9020. const evalContext = {};
  9021. if (!context.javascriptEnabled) {
  9022. throw { message: 'Inline JavaScript is not enabled. Is it set in your options?',
  9023. filename: this.fileInfo().filename,
  9024. index: this.getIndex() };
  9025. }
  9026. expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
  9027. return that.jsify(new Variable(`@${name}`, that.getIndex(), that.fileInfo()).eval(context));
  9028. });
  9029. /** @type {Function} */
  9030. let expressionFunc;
  9031. try {
  9032. expressionFunc = new Function(`return (${expression})`);
  9033. } catch (e) {
  9034. throw { message: `JavaScript evaluation error: ${/** @type {Error} */ (e).message} from \`${expression}\`` ,
  9035. filename: this.fileInfo().filename,
  9036. index: this.getIndex() };
  9037. }
  9038. const variables = /** @type {Node & { variables: () => Record<string, { value: Node }> }} */ (context.frames[0]).variables();
  9039. for (const k in variables) {
  9040. // eslint-disable-next-line no-prototype-builtins
  9041. if (variables.hasOwnProperty(k)) {
  9042. evalContext[k.slice(1)] = {
  9043. value: variables[k].value,
  9044. toJS: function () {
  9045. return this.value.eval(context).toCSS(context);
  9046. }
  9047. };
  9048. }
  9049. }
  9050. try {
  9051. result = expressionFunc.call(evalContext);
  9052. } catch (e) {
  9053. throw { message: `JavaScript evaluation error: '${/** @type {Error} */ (e).name}: ${/** @type {Error} */ (e).message.replace(/["]/g, '\'')}'` ,
  9054. filename: this.fileInfo().filename,
  9055. index: this.getIndex() };
  9056. }
  9057. return result;
  9058. }
  9059. /**
  9060. * @param {Node} obj
  9061. * @returns {string}
  9062. */
  9063. jsify(obj) {
  9064. if (Array.isArray(obj.value) && (obj.value.length > 1)) {
  9065. return `[${obj.value.map(function (v) { return v.toCSS(/** @type {EvalContext} */ (undefined)); }).join(', ')}]`;
  9066. } else {
  9067. return obj.toCSS(/** @type {EvalContext} */ (undefined));
  9068. }
  9069. }
  9070. }
  9071. // @ts-check
  9072. class JavaScript extends JsEvalNode {
  9073. get type() { return 'JavaScript'; }
  9074. /**
  9075. * @param {string} string
  9076. * @param {boolean} escaped
  9077. * @param {number} index
  9078. * @param {FileInfo} currentFileInfo
  9079. */
  9080. constructor(string, escaped, index, currentFileInfo) {
  9081. super();
  9082. this.escaped = escaped;
  9083. this.expression = string;
  9084. this._index = index;
  9085. this._fileInfo = currentFileInfo;
  9086. }
  9087. /**
  9088. * @param {EvalContext} context
  9089. * @returns {Dimension | Quoted | Anonymous}
  9090. */
  9091. eval(context) {
  9092. const result = this.evaluateJavaScript(this.expression, context);
  9093. const type = typeof result;
  9094. if (type === 'number' && !isNaN(/** @type {number} */ (result))) {
  9095. return new Dimension(/** @type {number} */ (result));
  9096. } else if (type === 'string') {
  9097. return new Quoted(`"${result}"`, /** @type {string} */ (result), this.escaped, this._index);
  9098. } else if (Array.isArray(result)) {
  9099. return new Anonymous(/** @type {string[]} */ (result).join(', '));
  9100. } else {
  9101. return new Anonymous(/** @type {string} */ (result));
  9102. }
  9103. }
  9104. }
  9105. // @ts-check
  9106. class Assignment extends Node {
  9107. get type() { return 'Assignment'; }
  9108. /**
  9109. * @param {string} key
  9110. * @param {Node} val
  9111. */
  9112. constructor(key, val) {
  9113. super();
  9114. this.key = key;
  9115. this.value = val;
  9116. }
  9117. /** @param {TreeVisitor} visitor */
  9118. accept(visitor) {
  9119. this.value = visitor.visit(/** @type {Node} */ (this.value));
  9120. }
  9121. /**
  9122. * @param {EvalContext} context
  9123. * @returns {Assignment}
  9124. */
  9125. eval(context) {
  9126. if (/** @type {Node} */ (this.value).eval) {
  9127. return new Assignment(this.key, /** @type {Node} */ (this.value).eval(context));
  9128. }
  9129. return this;
  9130. }
  9131. /**
  9132. * @param {EvalContext} context
  9133. * @param {CSSOutput} output
  9134. */
  9135. genCSS(context, output) {
  9136. output.add(`${this.key}=`);
  9137. if (/** @type {Node} */ (this.value).genCSS) {
  9138. /** @type {Node} */ (this.value).genCSS(context, output);
  9139. } else {
  9140. output.add(/** @type {string} */ (/** @type {unknown} */ (this.value)));
  9141. }
  9142. }
  9143. }
  9144. // @ts-check
  9145. class Condition extends Node {
  9146. get type() { return 'Condition'; }
  9147. /**
  9148. * @param {string} op
  9149. * @param {Node} l
  9150. * @param {Node} r
  9151. * @param {number} i
  9152. * @param {boolean} negate
  9153. */
  9154. constructor(op, l, r, i, negate) {
  9155. super();
  9156. this.op = op.trim();
  9157. this.lvalue = l;
  9158. this.rvalue = r;
  9159. this._index = i;
  9160. this.negate = negate;
  9161. }
  9162. /** @param {TreeVisitor} visitor */
  9163. accept(visitor) {
  9164. this.lvalue = visitor.visit(this.lvalue);
  9165. this.rvalue = visitor.visit(this.rvalue);
  9166. }
  9167. /**
  9168. * @param {EvalContext} context
  9169. * @returns {boolean}
  9170. * @suppress {checkTypes}
  9171. */
  9172. // @ts-ignore - Condition.eval returns boolean, not Node (used as guard condition)
  9173. eval(context) {
  9174. const a = this.lvalue.eval(context);
  9175. const b = this.rvalue.eval(context);
  9176. /** @type {boolean} */
  9177. let result;
  9178. switch (this.op) {
  9179. case 'and': result = Boolean(a && b); break;
  9180. case 'or': result = Boolean(a || b); break;
  9181. default:
  9182. switch (Node.compare(a, b)) {
  9183. case -1:
  9184. result = this.op === '<' || this.op === '=<' || this.op === '<=';
  9185. break;
  9186. case 0:
  9187. result = this.op === '=' || this.op === '>=' || this.op === '=<' || this.op === '<=';
  9188. break;
  9189. case 1:
  9190. result = this.op === '>' || this.op === '>=';
  9191. break;
  9192. default:
  9193. result = false;
  9194. }
  9195. }
  9196. return this.negate ? !result : result;
  9197. }
  9198. }
  9199. // @ts-check
  9200. class QueryInParens extends Node {
  9201. get type() { return 'QueryInParens'; }
  9202. /**
  9203. * @param {string} op
  9204. * @param {Node} l
  9205. * @param {Node} m
  9206. * @param {string | null} op2
  9207. * @param {Node | null} r
  9208. * @param {number} i
  9209. */
  9210. constructor(op, l, m, op2, r, i) {
  9211. super();
  9212. this.op = op.trim();
  9213. this.lvalue = l;
  9214. this.mvalue = m;
  9215. this.op2 = op2 ? op2.trim() : null;
  9216. /** @type {Node | null} */
  9217. this.rvalue = r;
  9218. this._index = i;
  9219. }
  9220. /** @param {TreeVisitor} visitor */
  9221. accept(visitor) {
  9222. this.lvalue = visitor.visit(this.lvalue);
  9223. this.mvalue = visitor.visit(this.mvalue);
  9224. if (this.rvalue) {
  9225. this.rvalue = visitor.visit(this.rvalue);
  9226. }
  9227. }
  9228. /** @param {EvalContext} context */
  9229. eval(context) {
  9230. const node = new QueryInParens(
  9231. this.op,
  9232. this.lvalue.eval(context),
  9233. this.mvalue.eval(context),
  9234. this.op2,
  9235. this.rvalue ? this.rvalue.eval(context) : null,
  9236. this._index || 0
  9237. );
  9238. return node;
  9239. }
  9240. /**
  9241. * @param {EvalContext} context
  9242. * @param {CSSOutput} output
  9243. */
  9244. genCSS(context, output) {
  9245. this.lvalue.genCSS(context, output);
  9246. output.add(' ' + this.op + ' ');
  9247. this.mvalue.genCSS(context, output);
  9248. if (this.rvalue) {
  9249. output.add(' ' + this.op2 + ' ');
  9250. this.rvalue.genCSS(context, output);
  9251. }
  9252. }
  9253. }
  9254. // @ts-check
  9255. /**
  9256. * @typedef {Ruleset & {
  9257. * allowImports?: boolean,
  9258. * debugInfo?: { lineNumber: number, fileName: string },
  9259. * functionRegistry?: FunctionRegistry
  9260. * }} RulesetWithExtras
  9261. */
  9262. class Container extends AtRule {
  9263. get type() { return 'Container'; }
  9264. /**
  9265. * @param {Node[] | null} value
  9266. * @param {Node[]} features
  9267. * @param {number} index
  9268. * @param {FileInfo} currentFileInfo
  9269. * @param {VisibilityInfo} visibilityInfo
  9270. */
  9271. constructor(value, features, index, currentFileInfo, visibilityInfo) {
  9272. super();
  9273. this._index = index;
  9274. this._fileInfo = currentFileInfo;
  9275. const selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
  9276. /** @type {Value} */
  9277. this.features = new Value(features);
  9278. /** @type {RulesetWithExtras[]} */
  9279. this.rules = [new Ruleset(selectors, value)];
  9280. this.rules[0].allowImports = true;
  9281. this.copyVisibilityInfo(visibilityInfo);
  9282. this.allowRoot = true;
  9283. this.setParent(selectors, /** @type {Node} */ (/** @type {unknown} */ (this)));
  9284. this.setParent(this.features, /** @type {Node} */ (/** @type {unknown} */ (this)));
  9285. this.setParent(this.rules, /** @type {Node} */ (/** @type {unknown} */ (this)));
  9286. /** @type {boolean | undefined} */
  9287. this._evaluated = undefined;
  9288. }
  9289. /**
  9290. * @param {EvalContext} context
  9291. * @param {CSSOutput} output
  9292. */
  9293. genCSS(context, output) {
  9294. output.add('@container ', this._fileInfo, this._index);
  9295. this.features.genCSS(context, output);
  9296. this.outputRuleset(context, output, this.rules);
  9297. }
  9298. /**
  9299. * @param {EvalContext} context
  9300. * @returns {Node}
  9301. */
  9302. eval(context) {
  9303. if (this._evaluated) {
  9304. return /** @type {Node} */ (/** @type {unknown} */ (this));
  9305. }
  9306. if (!context.mediaBlocks) {
  9307. context.mediaBlocks = [];
  9308. context.mediaPath = [];
  9309. }
  9310. const media = new Container(null, [], this._index, this._fileInfo, this.visibilityInfo());
  9311. media._evaluated = true;
  9312. if (this.debugInfo) {
  9313. this.rules[0].debugInfo = this.debugInfo;
  9314. media.debugInfo = this.debugInfo;
  9315. }
  9316. media.features = /** @type {Value} */ (this.features.eval(context));
  9317. context.mediaPath.push(/** @type {Node} */ (/** @type {unknown} */ (media)));
  9318. context.mediaBlocks.push(/** @type {Node} */ (/** @type {unknown} */ (media)));
  9319. const fr = /** @type {RulesetWithExtras} */ (context.frames[0]).functionRegistry;
  9320. if (fr) {
  9321. this.rules[0].functionRegistry = fr.inherit();
  9322. }
  9323. context.frames.unshift(this.rules[0]);
  9324. media.rules = [/** @type {RulesetWithExtras} */ (this.rules[0].eval(context))];
  9325. context.frames.shift();
  9326. context.mediaPath.pop();
  9327. return context.mediaPath.length === 0 ? /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (media)).evalTop(context) :
  9328. /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (media)).evalNested(context);
  9329. }
  9330. }
  9331. // Apply NestableAtRulePrototype methods (accept, isRulesetLike override AtRule's versions)
  9332. Object.assign(Container.prototype, NestableAtRulePrototype);
  9333. // @ts-check
  9334. class UnicodeDescriptor extends Node {
  9335. get type() { return 'UnicodeDescriptor'; }
  9336. /** @param {string} value */
  9337. constructor(value) {
  9338. super();
  9339. this.value = value;
  9340. }
  9341. }
  9342. // @ts-check
  9343. class Negative extends Node {
  9344. get type() { return 'Negative'; }
  9345. /** @param {Node} node */
  9346. constructor(node) {
  9347. super();
  9348. this.value = node;
  9349. }
  9350. /**
  9351. * @param {EvalContext} context
  9352. * @param {CSSOutput} output
  9353. */
  9354. genCSS(context, output) {
  9355. output.add('-');
  9356. /** @type {Node} */ (this.value).genCSS(context, output);
  9357. }
  9358. /**
  9359. * @param {EvalContext} context
  9360. * @returns {Node}
  9361. */
  9362. eval(context) {
  9363. if (context.isMathOn('*')) {
  9364. return (new Operation('*', [new Dimension(-1), /** @type {Node} */ (this.value)], false)).eval(context);
  9365. }
  9366. return new Negative(/** @type {Node} */ (this.value).eval(context));
  9367. }
  9368. }
  9369. // @ts-check
  9370. class Extend extends Node {
  9371. get type() { return 'Extend'; }
  9372. /**
  9373. * @param {Selector} selector
  9374. * @param {string} option
  9375. * @param {number} index
  9376. * @param {FileInfo} currentFileInfo
  9377. * @param {VisibilityInfo} [visibilityInfo]
  9378. */
  9379. constructor(selector, option, index, currentFileInfo, visibilityInfo) {
  9380. super();
  9381. this.selector = selector;
  9382. this.option = option;
  9383. this.object_id = Extend.next_id++;
  9384. /** @type {number[]} */
  9385. this.parent_ids = [this.object_id];
  9386. this._index = index;
  9387. this._fileInfo = currentFileInfo;
  9388. this.copyVisibilityInfo(visibilityInfo);
  9389. /** @type {boolean} */
  9390. this.allowRoot = true;
  9391. /** @type {boolean} */
  9392. this.allowBefore = false;
  9393. /** @type {boolean} */
  9394. this.allowAfter = false;
  9395. switch (option) {
  9396. case '!all':
  9397. case 'all':
  9398. this.allowBefore = true;
  9399. this.allowAfter = true;
  9400. break;
  9401. default:
  9402. this.allowBefore = false;
  9403. this.allowAfter = false;
  9404. break;
  9405. }
  9406. this.setParent(this.selector, this);
  9407. }
  9408. /** @param {TreeVisitor} visitor */
  9409. accept(visitor) {
  9410. this.selector = /** @type {Selector} */ (visitor.visit(this.selector));
  9411. }
  9412. /** @param {EvalContext} context */
  9413. eval(context) {
  9414. return new Extend(/** @type {Selector} */ (this.selector.eval(context)), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  9415. }
  9416. // remove when Nodes have JSDoc types
  9417. // eslint-disable-next-line no-unused-vars
  9418. /** @param {EvalContext} [context] */
  9419. clone(context) {
  9420. return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  9421. }
  9422. // it concatenates (joins) all selectors in selector array
  9423. /** @param {Selector[]} selectors */
  9424. findSelfSelectors(selectors) {
  9425. /** @type {import('./element.js').default[]} */
  9426. let selfElements = [];
  9427. let i, selectorElements;
  9428. for (i = 0; i < selectors.length; i++) {
  9429. selectorElements = selectors[i].elements;
  9430. // duplicate the logic in genCSS function inside the selector node.
  9431. // future TODO - move both logics into the selector joiner visitor
  9432. if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
  9433. selectorElements[0].combinator.value = ' ';
  9434. }
  9435. selfElements = selfElements.concat(selectors[i].elements);
  9436. }
  9437. /** @type {Selector[]} */
  9438. this.selfSelectors = [new Selector(selfElements)];
  9439. this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
  9440. }
  9441. }
  9442. Extend.next_id = 0;
  9443. // @ts-check
  9444. class VariableCall extends Node {
  9445. get type() { return 'VariableCall'; }
  9446. /**
  9447. * @param {string} variable
  9448. * @param {number} index
  9449. * @param {FileInfo} currentFileInfo
  9450. */
  9451. constructor(variable, index, currentFileInfo) {
  9452. super();
  9453. this.variable = variable;
  9454. this._index = index;
  9455. this._fileInfo = currentFileInfo;
  9456. this.allowRoot = true;
  9457. }
  9458. /**
  9459. * @param {EvalContext} context
  9460. * @returns {Node}
  9461. */
  9462. eval(context) {
  9463. let rules;
  9464. /** @type {DetachedRuleset | Node} */
  9465. let detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
  9466. const error = new LessError({message: `Could not evaluate variable call ${this.variable}`});
  9467. if (!(/** @type {DetachedRuleset} */ (detachedRuleset)).ruleset) {
  9468. const dr = /** @type {Node & { rules?: Node[] }} */ (detachedRuleset);
  9469. if (dr.rules) {
  9470. rules = detachedRuleset;
  9471. }
  9472. else if (Array.isArray(detachedRuleset)) {
  9473. rules = new Ruleset(null, detachedRuleset);
  9474. }
  9475. else if (Array.isArray(detachedRuleset.value)) {
  9476. rules = new Ruleset(null, detachedRuleset.value);
  9477. }
  9478. else {
  9479. throw error;
  9480. }
  9481. detachedRuleset = new DetachedRuleset(rules);
  9482. }
  9483. const dr = /** @type {DetachedRuleset} */ (detachedRuleset);
  9484. if (dr.ruleset) {
  9485. return dr.callEval(context);
  9486. }
  9487. throw error;
  9488. }
  9489. }
  9490. // @ts-check
  9491. class NamespaceValue extends Node {
  9492. get type() { return 'NamespaceValue'; }
  9493. /**
  9494. * @param {Node} ruleCall
  9495. * @param {string[]} lookups
  9496. * @param {number} index
  9497. * @param {FileInfo} fileInfo
  9498. */
  9499. constructor(ruleCall, lookups, index, fileInfo) {
  9500. super();
  9501. this.value = ruleCall;
  9502. this.lookups = lookups;
  9503. this._index = index;
  9504. this._fileInfo = fileInfo;
  9505. }
  9506. /**
  9507. * @param {EvalContext} context
  9508. * @returns {Node}
  9509. */
  9510. eval(context) {
  9511. let i, name;
  9512. /** @type {Ruleset | Node | Node[]} */
  9513. let rules = this.value.eval(context);
  9514. for (i = 0; i < this.lookups.length; i++) {
  9515. name = this.lookups[i];
  9516. if (Array.isArray(rules)) {
  9517. rules = new Ruleset([new Selector()], rules);
  9518. }
  9519. const rs = /** @type {Ruleset} */ (rules);
  9520. if (name === '') {
  9521. rules = rs.lastDeclaration();
  9522. }
  9523. else if (name.charAt(0) === '@') {
  9524. if (name.charAt(1) === '@') {
  9525. name = `@${new Variable(name.slice(1)).eval(context).value}`;
  9526. }
  9527. if (rs.variables) {
  9528. rules = rs.variable(name);
  9529. }
  9530. if (!rules) {
  9531. throw { type: 'Name',
  9532. message: `variable ${name} not found`,
  9533. filename: this.fileInfo().filename,
  9534. index: this.getIndex() };
  9535. }
  9536. }
  9537. else {
  9538. if (name.substring(0, 2) === '$@') {
  9539. name = `$${new Variable(name.slice(1)).eval(context).value}`;
  9540. }
  9541. else {
  9542. name = name.charAt(0) === '$' ? name : `$${name}`;
  9543. }
  9544. if (rs.properties) {
  9545. rules = rs.property(name);
  9546. }
  9547. if (!rules) {
  9548. throw { type: 'Name',
  9549. message: `property "${name.slice(1)}" not found`,
  9550. filename: this.fileInfo().filename,
  9551. index: this.getIndex() };
  9552. }
  9553. const rulesArr = /** @type {Node[]} */ (rules);
  9554. rules = rulesArr[rulesArr.length - 1];
  9555. }
  9556. const current = /** @type {Node} */ (rules);
  9557. if (current.value) {
  9558. rules = /** @type {Node} */ (current.eval(context).value);
  9559. }
  9560. const currentNode = /** @type {Node & { ruleset?: Node }} */ (rules);
  9561. if (currentNode.ruleset) {
  9562. rules = currentNode.ruleset.eval(context);
  9563. }
  9564. }
  9565. return /** @type {Node} */ (rules);
  9566. }
  9567. }
  9568. // @ts-check
  9569. /**
  9570. * @typedef {object} MixinParam
  9571. * @property {string} [name]
  9572. * @property {Node} [value]
  9573. * @property {boolean} [variadic]
  9574. */
  9575. /**
  9576. * @typedef {Ruleset & {
  9577. * functionRegistry?: FunctionRegistry,
  9578. * originalRuleset?: Node
  9579. * }} RulesetWithRegistry
  9580. */
  9581. class Definition extends Ruleset {
  9582. get type() { return 'MixinDefinition'; }
  9583. /**
  9584. * @param {string | undefined} name
  9585. * @param {MixinParam[]} params
  9586. * @param {Node[]} rules
  9587. * @param {Node | null} [condition]
  9588. * @param {boolean} [variadic]
  9589. * @param {Node[] | null} [frames]
  9590. * @param {VisibilityInfo} [visibilityInfo]
  9591. */
  9592. constructor(name, params, rules, condition, variadic, frames, visibilityInfo) {
  9593. super(null, null);
  9594. /** @type {string} */
  9595. this.name = name || 'anonymous mixin';
  9596. this.selectors = [new Selector([new Element(null, name, false, this._index, this._fileInfo)])];
  9597. /** @type {MixinParam[]} */
  9598. this.params = params;
  9599. /** @type {Node | null | undefined} */
  9600. this.condition = condition;
  9601. /** @type {boolean | undefined} */
  9602. this.variadic = variadic;
  9603. /** @type {number} */
  9604. this.arity = params.length;
  9605. this.rules = rules;
  9606. this._lookups = {};
  9607. /** @type {string[]} */
  9608. const optionalParameters = [];
  9609. /** @type {number} */
  9610. this.required = params.reduce(function (/** @type {number} */ count, /** @type {MixinParam} */ p) {
  9611. if (!p.name || (p.name && !p.value)) {
  9612. return count + 1;
  9613. }
  9614. else {
  9615. optionalParameters.push(p.name);
  9616. return count;
  9617. }
  9618. }, 0);
  9619. /** @type {string[]} */
  9620. this.optionalParameters = optionalParameters;
  9621. /** @type {Node[] | null | undefined} */
  9622. this.frames = frames;
  9623. this.copyVisibilityInfo(visibilityInfo);
  9624. this.allowRoot = true;
  9625. /** @type {boolean} */
  9626. this.evalFirst = true;
  9627. }
  9628. /** @param {TreeVisitor} visitor */
  9629. accept(visitor) {
  9630. if (this.params && this.params.length) {
  9631. this.params = /** @type {MixinParam[]} */ (/** @type {unknown} */ (visitor.visitArray(/** @type {Node[]} */ (/** @type {unknown} */ (this.params)))));
  9632. }
  9633. this.rules = visitor.visitArray(this.rules);
  9634. if (this.condition) {
  9635. this.condition = visitor.visit(this.condition);
  9636. }
  9637. }
  9638. /**
  9639. * @param {EvalContext} context
  9640. * @param {EvalContext} mixinEnv
  9641. * @param {MixinArg[] | null} args
  9642. * @param {Node[]} evaldArguments
  9643. * @returns {Ruleset}
  9644. */
  9645. evalParams(context, mixinEnv, args, evaldArguments) {
  9646. /* jshint boss:true */
  9647. const frame = new Ruleset(null, null);
  9648. /** @type {Node[] | undefined} */
  9649. let varargs;
  9650. /** @type {MixinArg | undefined} */
  9651. let arg;
  9652. const params = /** @type {MixinParam[]} */ (copyArray(this.params));
  9653. /** @type {number} */
  9654. let i;
  9655. /** @type {number} */
  9656. let j;
  9657. /** @type {Node | undefined} */
  9658. let val;
  9659. /** @type {string | undefined} */
  9660. let name;
  9661. /** @type {boolean} */
  9662. let isNamedFound;
  9663. /** @type {number} */
  9664. let argIndex;
  9665. let argsLength = 0;
  9666. if (mixinEnv.frames && mixinEnv.frames[0] && /** @type {RulesetWithRegistry} */ (mixinEnv.frames[0]).functionRegistry) {
  9667. /** @type {RulesetWithRegistry} */ (frame).functionRegistry = /** @type {FunctionRegistry} */ (/** @type {RulesetWithRegistry} */ (mixinEnv.frames[0]).functionRegistry).inherit();
  9668. }
  9669. mixinEnv = new contexts.Eval(mixinEnv, /** @type {Node[]} */ ([frame]).concat(/** @type {Node[]} */ (mixinEnv.frames)));
  9670. if (args) {
  9671. args = /** @type {MixinArg[]} */ (copyArray(args));
  9672. argsLength = args.length;
  9673. for (i = 0; i < argsLength; i++) {
  9674. arg = args[i];
  9675. if (name = (arg && arg.name)) {
  9676. isNamedFound = false;
  9677. for (j = 0; j < params.length; j++) {
  9678. if (!evaldArguments[j] && name === params[j].name) {
  9679. evaldArguments[j] = arg.value.eval(context);
  9680. frame.prependRule(new Declaration(name, arg.value.eval(context)));
  9681. isNamedFound = true;
  9682. break;
  9683. }
  9684. }
  9685. if (isNamedFound) {
  9686. args.splice(i, 1);
  9687. i--;
  9688. continue;
  9689. } else {
  9690. throw { type: 'Runtime', message: `Named argument for ${this.name} ${args[i].name} not found` };
  9691. }
  9692. }
  9693. }
  9694. }
  9695. argIndex = 0;
  9696. for (i = 0; i < params.length; i++) {
  9697. if (evaldArguments[i]) { continue; }
  9698. arg = args && args[argIndex];
  9699. if (name = params[i].name) {
  9700. if (params[i].variadic) {
  9701. varargs = [];
  9702. for (j = argIndex; j < argsLength; j++) {
  9703. varargs.push(/** @type {MixinArg[]} */ (args)[j].value.eval(context));
  9704. }
  9705. frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
  9706. } else {
  9707. val = arg && arg.value;
  9708. if (val) {
  9709. // This was a mixin call, pass in a detached ruleset of it's eval'd rules
  9710. if (Array.isArray(val)) {
  9711. val = /** @type {Node} */ (/** @type {unknown} */ (new DetachedRuleset(new Ruleset(null, /** @type {Node[]} */ (val)))));
  9712. }
  9713. else {
  9714. val = val.eval(context);
  9715. }
  9716. } else if (params[i].value) {
  9717. val = /** @type {Node} */ (params[i].value).eval(mixinEnv);
  9718. frame.resetCache();
  9719. } else {
  9720. throw { type: 'Runtime', message: `wrong number of arguments for ${this.name} (${argsLength} for ${this.arity})` };
  9721. }
  9722. frame.prependRule(new Declaration(name, val));
  9723. evaldArguments[i] = val;
  9724. }
  9725. }
  9726. if (params[i].variadic && args) {
  9727. for (j = argIndex; j < argsLength; j++) {
  9728. evaldArguments[j] = args[j].value.eval(context);
  9729. }
  9730. }
  9731. argIndex++;
  9732. }
  9733. return frame;
  9734. }
  9735. /** @returns {Ruleset} */
  9736. makeImportant() {
  9737. const rules = !this.rules ? this.rules : this.rules.map(function (/** @type {Node & { makeImportant?: (important?: boolean) => Node }} */ r) {
  9738. if (r.makeImportant) {
  9739. return r.makeImportant(true);
  9740. } else {
  9741. return r;
  9742. }
  9743. });
  9744. const result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
  9745. return /** @type {Ruleset} */ (/** @type {unknown} */ (result));
  9746. }
  9747. /**
  9748. * @param {EvalContext} context
  9749. * @returns {Definition}
  9750. */
  9751. eval(context) {
  9752. return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
  9753. }
  9754. /**
  9755. * @param {EvalContext} context
  9756. * @param {MixinArg[]} args
  9757. * @param {string | undefined} important
  9758. * @returns {Ruleset}
  9759. */
  9760. evalCall(context, args, important) {
  9761. /** @type {Node[]} */
  9762. const _arguments = [];
  9763. const mixinFrames = this.frames ? /** @type {Node[]} */ (this.frames).concat(/** @type {Node[]} */ (context.frames)) : /** @type {Node[]} */ (context.frames);
  9764. const frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
  9765. /** @type {Node[]} */
  9766. let rules;
  9767. /** @type {Ruleset} */
  9768. let ruleset;
  9769. frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
  9770. rules = copyArray(this.rules);
  9771. ruleset = new Ruleset(null, rules);
  9772. /** @type {RulesetWithRegistry} */ (ruleset).originalRuleset = this;
  9773. ruleset = /** @type {Ruleset} */ (ruleset.eval(new contexts.Eval(context, /** @type {Node[]} */ ([this, frame]).concat(mixinFrames))));
  9774. if (important) {
  9775. ruleset = /** @type {Ruleset} */ (ruleset.makeImportant());
  9776. }
  9777. return ruleset;
  9778. }
  9779. /**
  9780. * @param {MixinArg[] | null} args
  9781. * @param {EvalContext} context
  9782. * @returns {boolean}
  9783. */
  9784. matchCondition(args, context) {
  9785. if (this.condition && !this.condition.eval(
  9786. new contexts.Eval(context,
  9787. /** @type {Node[]} */ ([this.evalParams(context, /* the parameter variables */
  9788. new contexts.Eval(context, this.frames ? /** @type {Node[]} */ (this.frames).concat(/** @type {Node[]} */ (context.frames)) : context.frames), args, [])])
  9789. .concat(/** @type {Node[]} */ (this.frames || [])) // the parent namespace/mixin frames
  9790. .concat(/** @type {Node[]} */ (context.frames))))) { // the current environment frames
  9791. return false;
  9792. }
  9793. return true;
  9794. }
  9795. /**
  9796. * @param {MixinArg[] | null} args
  9797. * @param {EvalContext} [context]
  9798. * @returns {boolean}
  9799. */
  9800. matchArgs(args, context) {
  9801. const allArgsCnt = (args && args.length) || 0;
  9802. let len;
  9803. const optionalParameters = this.optionalParameters;
  9804. const requiredArgsCnt = !args ? 0 : args.reduce(function (/** @type {number} */ count, /** @type {MixinArg} */ p) {
  9805. if (optionalParameters.indexOf(p.name) < 0) {
  9806. return count + 1;
  9807. } else {
  9808. return count;
  9809. }
  9810. }, 0);
  9811. if (!this.variadic) {
  9812. if (requiredArgsCnt < this.required) {
  9813. return false;
  9814. }
  9815. if (allArgsCnt > this.params.length) {
  9816. return false;
  9817. }
  9818. } else {
  9819. if (requiredArgsCnt < (this.required - 1)) {
  9820. return false;
  9821. }
  9822. }
  9823. // check patterns
  9824. len = Math.min(requiredArgsCnt, this.arity);
  9825. for (let i = 0; i < len; i++) {
  9826. if (!this.params[i].name && !this.params[i].variadic) {
  9827. if (/** @type {MixinArg[]} */ (args)[i].value.eval(context).toCSS(/** @type {EvalContext} */ ({})) != /** @type {Node} */ (this.params[i].value).eval(context).toCSS(/** @type {EvalContext} */ ({}))) {
  9828. return false;
  9829. }
  9830. }
  9831. }
  9832. return true;
  9833. }
  9834. }
  9835. // @ts-check
  9836. /**
  9837. * @typedef {{ name?: string, value: Node, expand?: boolean }} MixinArg
  9838. */
  9839. /**
  9840. * @typedef {Node & {
  9841. * rules?: Node[],
  9842. * selectors?: Selector[],
  9843. * originalRuleset?: Node,
  9844. * matchArgs: (args: MixinArg[] | null, context: EvalContext) => boolean,
  9845. * matchCondition?: (args: MixinArg[] | null, context: EvalContext) => boolean,
  9846. * find: (selector: Selector, self?: Node | null, filter?: (rule: Node) => boolean) => Array<{ rule: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, path: Node[] }>,
  9847. * functionRegistry?: FunctionRegistry
  9848. * }} MixinSearchFrame
  9849. */
  9850. class MixinCall extends Node {
  9851. get type() { return 'MixinCall'; }
  9852. /**
  9853. * @param {import('./element.js').default[]} elements
  9854. * @param {MixinArg[]} [args]
  9855. * @param {number} [index]
  9856. * @param {FileInfo} [currentFileInfo]
  9857. * @param {string} [important]
  9858. */
  9859. constructor(elements, args, index, currentFileInfo, important) {
  9860. super();
  9861. /** @type {Selector} */
  9862. this.selector = new Selector(elements);
  9863. /** @type {MixinArg[]} */
  9864. this.arguments = args || [];
  9865. this._index = index;
  9866. this._fileInfo = currentFileInfo;
  9867. /** @type {string | undefined} */
  9868. this.important = important;
  9869. this.allowRoot = true;
  9870. this.setParent(this.selector, /** @type {Node} */ (/** @type {unknown} */ (this)));
  9871. }
  9872. /** @param {TreeVisitor} visitor */
  9873. accept(visitor) {
  9874. if (this.selector) {
  9875. this.selector = /** @type {Selector} */ (visitor.visit(this.selector));
  9876. }
  9877. if (this.arguments.length) {
  9878. this.arguments = /** @type {MixinArg[]} */ (/** @type {unknown} */ (visitor.visitArray(/** @type {Node[]} */ (/** @type {unknown} */ (this.arguments)))));
  9879. }
  9880. }
  9881. /**
  9882. * @param {EvalContext} context
  9883. * @returns {Node}
  9884. */
  9885. eval(context) {
  9886. /** @type {{ rule: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, path: Node[] }[] | undefined} */
  9887. let mixins;
  9888. /** @type {Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }} */
  9889. let mixin;
  9890. /** @type {Node[]} */
  9891. let mixinPath;
  9892. /** @type {MixinArg[]} */
  9893. const args = [];
  9894. /** @type {MixinArg} */
  9895. let arg;
  9896. /** @type {Node} */
  9897. let argValue;
  9898. /** @type {Node[]} */
  9899. const rules = [];
  9900. let match = false;
  9901. /** @type {number} */
  9902. let i;
  9903. /** @type {number} */
  9904. let m;
  9905. /** @type {number} */
  9906. let f;
  9907. /** @type {boolean} */
  9908. let isRecursive;
  9909. /** @type {boolean | undefined} */
  9910. let isOneFound;
  9911. /** @type {{ mixin: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, group: number }[]} */
  9912. const candidates = [];
  9913. /** @type {{ mixin: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, group: number } | number} */
  9914. let candidate;
  9915. /** @type {boolean[]} */
  9916. const conditionResult = [];
  9917. /** @type {number | undefined} */
  9918. let defaultResult;
  9919. const defFalseEitherCase = -1;
  9920. const defNone = 0;
  9921. const defTrue = 1;
  9922. const defFalse = 2;
  9923. /** @type {number[]} */
  9924. let count;
  9925. /** @type {Node | undefined} */
  9926. let originalRuleset;
  9927. /** @type {((rule: MixinSearchFrame) => boolean) | undefined} */
  9928. let noArgumentsFilter;
  9929. this.selector = /** @type {Selector} */ (this.selector.eval(context));
  9930. /**
  9931. * @param {Node & { matchCondition?: Function }} mixin
  9932. * @param {Node[]} mixinPath
  9933. */
  9934. function calcDefGroup(mixin, mixinPath) {
  9935. /** @type {number} */
  9936. let f;
  9937. /** @type {number} */
  9938. let p;
  9939. /** @type {Node & { matchCondition?: Function }} */
  9940. let namespace;
  9941. for (f = 0; f < 2; f++) {
  9942. conditionResult[f] = true;
  9943. defaultFunc.value(f);
  9944. for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
  9945. namespace = mixinPath[p];
  9946. if (namespace.matchCondition) {
  9947. conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
  9948. }
  9949. }
  9950. if (mixin.matchCondition) {
  9951. conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
  9952. }
  9953. }
  9954. if (conditionResult[0] || conditionResult[1]) {
  9955. if (conditionResult[0] != conditionResult[1]) {
  9956. return conditionResult[1] ?
  9957. defTrue : defFalse;
  9958. }
  9959. return defNone;
  9960. }
  9961. return defFalseEitherCase;
  9962. }
  9963. for (i = 0; i < this.arguments.length; i++) {
  9964. arg = this.arguments[i];
  9965. argValue = arg.value.eval(context);
  9966. if (arg.expand && Array.isArray(argValue.value)) {
  9967. const expandedValues = /** @type {Node[]} */ (argValue.value);
  9968. for (m = 0; m < expandedValues.length; m++) {
  9969. args.push({value: expandedValues[m]});
  9970. }
  9971. } else {
  9972. args.push({name: arg.name, value: argValue});
  9973. }
  9974. }
  9975. noArgumentsFilter = function(/** @type {MixinSearchFrame} */ rule) {return rule.matchArgs(null, context);};
  9976. for (i = 0; i < context.frames.length; i++) {
  9977. if ((mixins = /** @type {MixinSearchFrame} */ (context.frames[i]).find(this.selector, null, /** @type {(rule: Node) => boolean} */ (/** @type {unknown} */ (noArgumentsFilter)))).length > 0) {
  9978. isOneFound = true;
  9979. // To make `default()` function independent of definition order we have two "subpasses" here.
  9980. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
  9981. // and build candidate list with corresponding flags. Then, when we know all possible matches,
  9982. // we make a final decision.
  9983. for (m = 0; m < mixins.length; m++) {
  9984. mixin = mixins[m].rule;
  9985. mixinPath = mixins[m].path;
  9986. isRecursive = false;
  9987. for (f = 0; f < context.frames.length; f++) {
  9988. if ((!(mixin instanceof Definition)) && mixin === (/** @type {Node & { originalRuleset?: Node }} */ (context.frames[f]).originalRuleset || context.frames[f])) {
  9989. isRecursive = true;
  9990. break;
  9991. }
  9992. }
  9993. if (isRecursive) {
  9994. continue;
  9995. }
  9996. if (mixin.matchArgs(args, context)) {
  9997. candidate = {mixin, group: calcDefGroup(mixin, mixinPath)};
  9998. if (/** @type {{ mixin: Node, group: number }} */ (candidate).group !== defFalseEitherCase) {
  9999. candidates.push(/** @type {{ mixin: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, group: number }} */ (candidate));
  10000. }
  10001. match = true;
  10002. }
  10003. }
  10004. defaultFunc.reset();
  10005. count = [0, 0, 0];
  10006. for (m = 0; m < candidates.length; m++) {
  10007. count[candidates[m].group]++;
  10008. }
  10009. if (count[defNone] > 0) {
  10010. defaultResult = defFalse;
  10011. } else {
  10012. defaultResult = defTrue;
  10013. if ((count[defTrue] + count[defFalse]) > 1) {
  10014. throw { type: 'Runtime',
  10015. message: `Ambiguous use of \`default()\` found when matching for \`${this.format(args)}\``,
  10016. index: this.getIndex(), filename: this.fileInfo().filename };
  10017. }
  10018. }
  10019. for (m = 0; m < candidates.length; m++) {
  10020. candidate = candidates[m].group;
  10021. if ((candidate === defNone) || (candidate === defaultResult)) {
  10022. try {
  10023. mixin = candidates[m].mixin;
  10024. if (!(mixin instanceof Definition)) {
  10025. originalRuleset = /** @type {Node & { originalRuleset?: Node }} */ (mixin).originalRuleset || mixin;
  10026. mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
  10027. /** @type {Node & { originalRuleset?: Node }} */ (mixin).originalRuleset = originalRuleset;
  10028. }
  10029. const newRules = /** @type {MixinDefinition} */ (mixin).evalCall(context, args, this.important).rules;
  10030. this._setVisibilityToReplacement(newRules);
  10031. Array.prototype.push.apply(rules, newRules);
  10032. } catch (e) {
  10033. throw { .../** @type {object} */ (e), index: this.getIndex(), filename: this.fileInfo().filename };
  10034. }
  10035. }
  10036. }
  10037. if (match) {
  10038. return /** @type {Node} */ (/** @type {unknown} */ (rules));
  10039. }
  10040. }
  10041. }
  10042. if (isOneFound) {
  10043. throw { type: 'Runtime',
  10044. message: `No matching definition was found for \`${this.format(args)}\``,
  10045. index: this.getIndex(), filename: this.fileInfo().filename };
  10046. } else {
  10047. throw { type: 'Name',
  10048. message: `${this.selector.toCSS(/** @type {EvalContext} */ ({})).trim()} is undefined`,
  10049. index: this.getIndex(), filename: this.fileInfo().filename };
  10050. }
  10051. }
  10052. /** @param {Node[]} replacement */
  10053. _setVisibilityToReplacement(replacement) {
  10054. /** @type {number} */
  10055. let i;
  10056. /** @type {Node} */
  10057. let rule;
  10058. if (this.blocksVisibility()) {
  10059. for (i = 0; i < replacement.length; i++) {
  10060. rule = replacement[i];
  10061. rule.addVisibilityBlock();
  10062. }
  10063. }
  10064. }
  10065. /** @param {MixinArg[]} args */
  10066. format(args) {
  10067. return `${this.selector.toCSS(/** @type {EvalContext} */ ({})).trim()}(${args ? args.map(function (/** @type {MixinArg} */ a) {
  10068. let argValue = '';
  10069. if (a.name) {
  10070. argValue += `${a.name}:`;
  10071. }
  10072. if (a.value.toCSS) {
  10073. argValue += a.value.toCSS(/** @type {EvalContext} */ ({}));
  10074. } else {
  10075. argValue += '???';
  10076. }
  10077. return argValue;
  10078. }).join(', ') : ''})`;
  10079. }
  10080. }
  10081. // @ts-check
  10082. var tree = {
  10083. Node, Color, AtRule, DetachedRuleset, Operation,
  10084. Dimension, Unit, Keyword, Variable, Property,
  10085. Ruleset, Element, Attribute, Combinator, Selector,
  10086. Quoted, Expression, Declaration, Call, URL, Import,
  10087. Comment, Anonymous, Value, JavaScript, Assignment,
  10088. Condition, Paren, Media, Container, QueryInParens,
  10089. UnicodeDescriptor, Negative, Extend, VariableCall,
  10090. NamespaceValue,
  10091. mixin: {
  10092. Call: MixinCall,
  10093. Definition: Definition
  10094. }
  10095. };
  10096. class AbstractPluginLoader {
  10097. constructor() {
  10098. // Implemented by Node.js plugin loader
  10099. this.require = function() {
  10100. return null;
  10101. };
  10102. }
  10103. evalPlugin(contents, context, imports, pluginOptions, fileInfo) {
  10104. let loader, registry, pluginObj, localModule, pluginManager, filename, result;
  10105. pluginManager = context.pluginManager;
  10106. if (fileInfo) {
  10107. if (typeof fileInfo === 'string') {
  10108. filename = fileInfo;
  10109. }
  10110. else {
  10111. filename = fileInfo.filename;
  10112. }
  10113. }
  10114. const shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
  10115. if (filename) {
  10116. pluginObj = pluginManager.get(filename);
  10117. if (pluginObj) {
  10118. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  10119. if (result) {
  10120. return result;
  10121. }
  10122. try {
  10123. if (pluginObj.use) {
  10124. pluginObj.use.call(this.context, pluginObj);
  10125. }
  10126. }
  10127. catch (e) {
  10128. e.message = e.message || 'Error during @plugin call';
  10129. return new LessError(e, imports, filename);
  10130. }
  10131. return pluginObj;
  10132. }
  10133. }
  10134. localModule = {
  10135. exports: {},
  10136. pluginManager,
  10137. fileInfo
  10138. };
  10139. registry = functionRegistry.create();
  10140. const registerPlugin = function(obj) {
  10141. pluginObj = obj;
  10142. };
  10143. try {
  10144. loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
  10145. loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
  10146. }
  10147. catch (e) {
  10148. return new LessError(e, imports, filename);
  10149. }
  10150. if (!pluginObj) {
  10151. pluginObj = localModule.exports;
  10152. }
  10153. pluginObj = this.validatePlugin(pluginObj, filename, shortname);
  10154. if (pluginObj instanceof LessError) {
  10155. return pluginObj;
  10156. }
  10157. if (pluginObj) {
  10158. pluginObj.imports = imports;
  10159. pluginObj.filename = filename;
  10160. // For < 3.x (or unspecified minVersion) - setOptions() before install()
  10161. if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
  10162. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  10163. if (result) {
  10164. return result;
  10165. }
  10166. }
  10167. // Run on first load
  10168. pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
  10169. pluginObj.functions = registry.getLocalFunctions();
  10170. // Need to call setOptions again because the pluginObj might have functions
  10171. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  10172. if (result) {
  10173. return result;
  10174. }
  10175. // Run every @plugin call
  10176. try {
  10177. if (pluginObj.use) {
  10178. pluginObj.use.call(this.context, pluginObj);
  10179. }
  10180. }
  10181. catch (e) {
  10182. e.message = e.message || 'Error during @plugin call';
  10183. return new LessError(e, imports, filename);
  10184. }
  10185. }
  10186. else {
  10187. return new LessError({ message: 'Not a valid plugin' }, imports, filename);
  10188. }
  10189. return pluginObj;
  10190. }
  10191. trySetOptions(plugin, filename, name, options) {
  10192. if (options && !plugin.setOptions) {
  10193. return new LessError({
  10194. message: `Options have been provided but the plugin ${name} does not support any options.`
  10195. });
  10196. }
  10197. try {
  10198. plugin.setOptions && plugin.setOptions(options);
  10199. }
  10200. catch (e) {
  10201. return new LessError(e);
  10202. }
  10203. }
  10204. validatePlugin(plugin, filename, name) {
  10205. if (plugin) {
  10206. // support plugins being a function
  10207. // so that the plugin can be more usable programmatically
  10208. if (typeof plugin === 'function') {
  10209. plugin = new plugin();
  10210. }
  10211. if (plugin.minVersion) {
  10212. if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
  10213. return new LessError({
  10214. message: `Plugin ${name} requires version ${this.versionToString(plugin.minVersion)}`
  10215. });
  10216. }
  10217. }
  10218. return plugin;
  10219. }
  10220. return null;
  10221. }
  10222. compareVersion(aVersion, bVersion) {
  10223. if (typeof aVersion === 'string') {
  10224. aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
  10225. aVersion.shift();
  10226. }
  10227. for (let i = 0; i < aVersion.length; i++) {
  10228. if (aVersion[i] !== bVersion[i]) {
  10229. return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
  10230. }
  10231. }
  10232. return 0;
  10233. }
  10234. versionToString(version) {
  10235. let versionString = '';
  10236. for (let i = 0; i < version.length; i++) {
  10237. versionString += (versionString ? '.' : '') + version[i];
  10238. }
  10239. return versionString;
  10240. }
  10241. printUsage(plugins) {
  10242. for (let i = 0; i < plugins.length; i++) {
  10243. const plugin = plugins[i];
  10244. if (plugin.printUsage) {
  10245. plugin.printUsage();
  10246. }
  10247. }
  10248. }
  10249. }
  10250. function boolean(condition) {
  10251. return condition ? Keyword.True : Keyword.False;
  10252. }
  10253. /**
  10254. * Functions with evalArgs set to false are sent context
  10255. * as the first argument.
  10256. */
  10257. function If(context, condition, trueValue, falseValue) {
  10258. return condition.eval(context) ? trueValue.eval(context)
  10259. : (falseValue ? falseValue.eval(context) : new Anonymous);
  10260. }
  10261. If.evalArgs = false;
  10262. function isdefined(context, variable) {
  10263. try {
  10264. variable.eval(context);
  10265. return Keyword.True;
  10266. } catch (e) {
  10267. return Keyword.False;
  10268. }
  10269. }
  10270. isdefined.evalArgs = false;
  10271. var boolean$1 = { isdefined, boolean, 'if': If };
  10272. let colorFunctions;
  10273. function clamp(val) {
  10274. return Math.min(1, Math.max(0, val));
  10275. }
  10276. function hsla(origColor, hsl) {
  10277. const color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
  10278. if (color) {
  10279. if (origColor.value &&
  10280. /^(rgb|hsl)/.test(origColor.value)) {
  10281. color.value = origColor.value;
  10282. } else {
  10283. color.value = 'rgb';
  10284. }
  10285. return color;
  10286. }
  10287. }
  10288. function toHSL(color) {
  10289. if (color.toHSL) {
  10290. return color.toHSL();
  10291. } else {
  10292. throw new Error('Argument cannot be evaluated to a color');
  10293. }
  10294. }
  10295. function toHSV(color) {
  10296. if (color.toHSV) {
  10297. return color.toHSV();
  10298. } else {
  10299. throw new Error('Argument cannot be evaluated to a color');
  10300. }
  10301. }
  10302. function number$1(n) {
  10303. if (n instanceof Dimension) {
  10304. return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
  10305. } else if (typeof n === 'number') {
  10306. return n;
  10307. } else {
  10308. throw {
  10309. type: 'Argument',
  10310. message: 'color functions take numbers as parameters'
  10311. };
  10312. }
  10313. }
  10314. function scaled(n, size) {
  10315. if (n instanceof Dimension && n.unit.is('%')) {
  10316. return parseFloat(n.value * size / 100);
  10317. } else {
  10318. return number$1(n);
  10319. }
  10320. }
  10321. colorFunctions = {
  10322. rgb: function (r, g, b) {
  10323. let a = 1;
  10324. /**
  10325. * Comma-less syntax
  10326. * e.g. rgb(0 128 255 / 50%)
  10327. */
  10328. if (r instanceof Expression) {
  10329. const val = r.value;
  10330. r = val[0];
  10331. g = val[1];
  10332. b = val[2];
  10333. /**
  10334. * @todo - should this be normalized in
  10335. * function caller? Or parsed differently?
  10336. */
  10337. if (b instanceof Operation) {
  10338. const op = b;
  10339. b = op.operands[0];
  10340. a = op.operands[1];
  10341. }
  10342. }
  10343. const color = colorFunctions.rgba(r, g, b, a);
  10344. if (color) {
  10345. color.value = 'rgb';
  10346. return color;
  10347. }
  10348. },
  10349. rgba: function (r, g, b, a) {
  10350. try {
  10351. if (r instanceof Color) {
  10352. if (g) {
  10353. a = number$1(g);
  10354. } else {
  10355. a = r.alpha;
  10356. }
  10357. return new Color(r.rgb, a, 'rgba');
  10358. }
  10359. const rgb = [r, g, b].map(c => scaled(c, 255));
  10360. a = number$1(a);
  10361. return new Color(rgb, a, 'rgba');
  10362. }
  10363. catch (e) {}
  10364. },
  10365. hsl: function (h, s, l) {
  10366. let a = 1;
  10367. if (h instanceof Expression) {
  10368. const val = h.value;
  10369. h = val[0];
  10370. s = val[1];
  10371. l = val[2];
  10372. if (l instanceof Operation) {
  10373. const op = l;
  10374. l = op.operands[0];
  10375. a = op.operands[1];
  10376. }
  10377. }
  10378. const color = colorFunctions.hsla(h, s, l, a);
  10379. if (color) {
  10380. color.value = 'hsl';
  10381. return color;
  10382. }
  10383. },
  10384. hsla: function (h, s, l, a) {
  10385. let m1;
  10386. let m2;
  10387. function hue(h) {
  10388. h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
  10389. if (h * 6 < 1) {
  10390. return m1 + (m2 - m1) * h * 6;
  10391. }
  10392. else if (h * 2 < 1) {
  10393. return m2;
  10394. }
  10395. else if (h * 3 < 2) {
  10396. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  10397. }
  10398. else {
  10399. return m1;
  10400. }
  10401. }
  10402. try {
  10403. if (h instanceof Color) {
  10404. if (s) {
  10405. a = number$1(s);
  10406. } else {
  10407. a = h.alpha;
  10408. }
  10409. return new Color(h.rgb, a, 'hsla');
  10410. }
  10411. h = (number$1(h) % 360) / 360;
  10412. s = clamp(number$1(s));l = clamp(number$1(l));a = clamp(number$1(a));
  10413. m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  10414. m1 = l * 2 - m2;
  10415. const rgb = [
  10416. hue(h + 1 / 3) * 255,
  10417. hue(h) * 255,
  10418. hue(h - 1 / 3) * 255
  10419. ];
  10420. a = number$1(a);
  10421. return new Color(rgb, a, 'hsla');
  10422. }
  10423. catch (e) {}
  10424. },
  10425. hsv: function(h, s, v) {
  10426. return colorFunctions.hsva(h, s, v, 1.0);
  10427. },
  10428. hsva: function(h, s, v, a) {
  10429. h = ((number$1(h) % 360) / 360) * 360;
  10430. s = number$1(s);v = number$1(v);a = number$1(a);
  10431. let i;
  10432. let f;
  10433. i = Math.floor((h / 60) % 6);
  10434. f = (h / 60) - i;
  10435. const vs = [v,
  10436. v * (1 - s),
  10437. v * (1 - f * s),
  10438. v * (1 - (1 - f) * s)];
  10439. const perm = [[0, 3, 1],
  10440. [2, 0, 1],
  10441. [1, 0, 3],
  10442. [1, 2, 0],
  10443. [3, 1, 0],
  10444. [0, 1, 2]];
  10445. return colorFunctions.rgba(vs[perm[i][0]] * 255,
  10446. vs[perm[i][1]] * 255,
  10447. vs[perm[i][2]] * 255,
  10448. a);
  10449. },
  10450. hue: function (color) {
  10451. return new Dimension(toHSL(color).h);
  10452. },
  10453. saturation: function (color) {
  10454. return new Dimension(toHSL(color).s * 100, '%');
  10455. },
  10456. lightness: function (color) {
  10457. return new Dimension(toHSL(color).l * 100, '%');
  10458. },
  10459. hsvhue: function(color) {
  10460. return new Dimension(toHSV(color).h);
  10461. },
  10462. hsvsaturation: function (color) {
  10463. return new Dimension(toHSV(color).s * 100, '%');
  10464. },
  10465. hsvvalue: function (color) {
  10466. return new Dimension(toHSV(color).v * 100, '%');
  10467. },
  10468. red: function (color) {
  10469. return new Dimension(color.rgb[0]);
  10470. },
  10471. green: function (color) {
  10472. return new Dimension(color.rgb[1]);
  10473. },
  10474. blue: function (color) {
  10475. return new Dimension(color.rgb[2]);
  10476. },
  10477. alpha: function (color) {
  10478. return new Dimension(toHSL(color).a);
  10479. },
  10480. luma: function (color) {
  10481. return new Dimension(color.luma() * color.alpha * 100, '%');
  10482. },
  10483. luminance: function (color) {
  10484. const luminance =
  10485. (0.2126 * color.rgb[0] / 255) +
  10486. (0.7152 * color.rgb[1] / 255) +
  10487. (0.0722 * color.rgb[2] / 255);
  10488. return new Dimension(luminance * color.alpha * 100, '%');
  10489. },
  10490. saturate: function (color, amount, method) {
  10491. // filter: saturate(3.2);
  10492. // should be kept as is, so check for color
  10493. if (!color.rgb) {
  10494. return null;
  10495. }
  10496. const hsl = toHSL(color);
  10497. if (typeof method !== 'undefined' && method.value === 'relative') {
  10498. hsl.s += hsl.s * amount.value / 100;
  10499. }
  10500. else {
  10501. hsl.s += amount.value / 100;
  10502. }
  10503. hsl.s = clamp(hsl.s);
  10504. return hsla(color, hsl);
  10505. },
  10506. desaturate: function (color, amount, method) {
  10507. const hsl = toHSL(color);
  10508. if (typeof method !== 'undefined' && method.value === 'relative') {
  10509. hsl.s -= hsl.s * amount.value / 100;
  10510. }
  10511. else {
  10512. hsl.s -= amount.value / 100;
  10513. }
  10514. hsl.s = clamp(hsl.s);
  10515. return hsla(color, hsl);
  10516. },
  10517. lighten: function (color, amount, method) {
  10518. const hsl = toHSL(color);
  10519. if (typeof method !== 'undefined' && method.value === 'relative') {
  10520. hsl.l += hsl.l * amount.value / 100;
  10521. }
  10522. else {
  10523. hsl.l += amount.value / 100;
  10524. }
  10525. hsl.l = clamp(hsl.l);
  10526. return hsla(color, hsl);
  10527. },
  10528. darken: function (color, amount, method) {
  10529. const hsl = toHSL(color);
  10530. if (typeof method !== 'undefined' && method.value === 'relative') {
  10531. hsl.l -= hsl.l * amount.value / 100;
  10532. }
  10533. else {
  10534. hsl.l -= amount.value / 100;
  10535. }
  10536. hsl.l = clamp(hsl.l);
  10537. return hsla(color, hsl);
  10538. },
  10539. fadein: function (color, amount, method) {
  10540. const hsl = toHSL(color);
  10541. if (typeof method !== 'undefined' && method.value === 'relative') {
  10542. hsl.a += hsl.a * amount.value / 100;
  10543. }
  10544. else {
  10545. hsl.a += amount.value / 100;
  10546. }
  10547. hsl.a = clamp(hsl.a);
  10548. return hsla(color, hsl);
  10549. },
  10550. fadeout: function (color, amount, method) {
  10551. const hsl = toHSL(color);
  10552. if (typeof method !== 'undefined' && method.value === 'relative') {
  10553. hsl.a -= hsl.a * amount.value / 100;
  10554. }
  10555. else {
  10556. hsl.a -= amount.value / 100;
  10557. }
  10558. hsl.a = clamp(hsl.a);
  10559. return hsla(color, hsl);
  10560. },
  10561. fade: function (color, amount) {
  10562. const hsl = toHSL(color);
  10563. hsl.a = amount.value / 100;
  10564. hsl.a = clamp(hsl.a);
  10565. return hsla(color, hsl);
  10566. },
  10567. spin: function (color, amount) {
  10568. const hsl = toHSL(color);
  10569. const hue = (hsl.h + amount.value) % 360;
  10570. hsl.h = hue < 0 ? 360 + hue : hue;
  10571. return hsla(color, hsl);
  10572. },
  10573. //
  10574. // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
  10575. // http://sass-lang.com
  10576. //
  10577. mix: function (color1, color2, weight) {
  10578. if (!weight) {
  10579. weight = new Dimension(50);
  10580. }
  10581. const p = weight.value / 100.0;
  10582. const w = p * 2 - 1;
  10583. const a = toHSL(color1).a - toHSL(color2).a;
  10584. const w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  10585. const w2 = 1 - w1;
  10586. const rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
  10587. color1.rgb[1] * w1 + color2.rgb[1] * w2,
  10588. color1.rgb[2] * w1 + color2.rgb[2] * w2];
  10589. const alpha = color1.alpha * p + color2.alpha * (1 - p);
  10590. return new Color(rgb, alpha);
  10591. },
  10592. greyscale: function (color) {
  10593. return colorFunctions.desaturate(color, new Dimension(100));
  10594. },
  10595. contrast: function (color, dark, light, threshold) {
  10596. // filter: contrast(3.2);
  10597. // should be kept as is, so check for color
  10598. if (!color.rgb) {
  10599. return null;
  10600. }
  10601. if (typeof light === 'undefined') {
  10602. light = colorFunctions.rgba(255, 255, 255, 1.0);
  10603. }
  10604. if (typeof dark === 'undefined') {
  10605. dark = colorFunctions.rgba(0, 0, 0, 1.0);
  10606. }
  10607. // Figure out which is actually light and dark:
  10608. if (dark.luma() > light.luma()) {
  10609. const t = light;
  10610. light = dark;
  10611. dark = t;
  10612. }
  10613. if (typeof threshold === 'undefined') {
  10614. threshold = 0.43;
  10615. } else {
  10616. threshold = number$1(threshold);
  10617. }
  10618. if (color.luma() < threshold) {
  10619. return light;
  10620. } else {
  10621. return dark;
  10622. }
  10623. },
  10624. // Changes made in 2.7.0 - Reverted in 3.0.0
  10625. // contrast: function (color, color1, color2, threshold) {
  10626. // // Return which of `color1` and `color2` has the greatest contrast with `color`
  10627. // // according to the standard WCAG contrast ratio calculation.
  10628. // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  10629. // // The threshold param is no longer used, in line with SASS.
  10630. // // filter: contrast(3.2);
  10631. // // should be kept as is, so check for color
  10632. // if (!color.rgb) {
  10633. // return null;
  10634. // }
  10635. // if (typeof color1 === 'undefined') {
  10636. // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
  10637. // }
  10638. // if (typeof color2 === 'undefined') {
  10639. // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
  10640. // }
  10641. // var contrast1, contrast2;
  10642. // var luma = color.luma();
  10643. // var luma1 = color1.luma();
  10644. // var luma2 = color2.luma();
  10645. // // Calculate contrast ratios for each color
  10646. // if (luma > luma1) {
  10647. // contrast1 = (luma + 0.05) / (luma1 + 0.05);
  10648. // } else {
  10649. // contrast1 = (luma1 + 0.05) / (luma + 0.05);
  10650. // }
  10651. // if (luma > luma2) {
  10652. // contrast2 = (luma + 0.05) / (luma2 + 0.05);
  10653. // } else {
  10654. // contrast2 = (luma2 + 0.05) / (luma + 0.05);
  10655. // }
  10656. // if (contrast1 > contrast2) {
  10657. // return color1;
  10658. // } else {
  10659. // return color2;
  10660. // }
  10661. // },
  10662. argb: function (color) {
  10663. return new Anonymous(color.toARGB());
  10664. },
  10665. color: function(c) {
  10666. if ((c instanceof Quoted) &&
  10667. (/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value))) {
  10668. const val = c.value.slice(1);
  10669. return new Color(val, undefined, `#${val}`);
  10670. }
  10671. if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
  10672. c.value = undefined;
  10673. return c;
  10674. }
  10675. throw {
  10676. type: 'Argument',
  10677. message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
  10678. };
  10679. },
  10680. tint: function(color, amount) {
  10681. return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
  10682. },
  10683. shade: function(color, amount) {
  10684. return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
  10685. }
  10686. };
  10687. var color = colorFunctions;
  10688. // Color Blending
  10689. // ref: http://www.w3.org/TR/compositing-1
  10690. function colorBlend(mode, color1, color2) {
  10691. const ab = color1.alpha; // result
  10692. let // backdrop
  10693. cb;
  10694. const as = color2.alpha;
  10695. let // source
  10696. cs;
  10697. let ar;
  10698. let cr;
  10699. const r = [];
  10700. ar = as + ab * (1 - as);
  10701. for (let i = 0; i < 3; i++) {
  10702. cb = color1.rgb[i] / 255;
  10703. cs = color2.rgb[i] / 255;
  10704. cr = mode(cb, cs);
  10705. if (ar) {
  10706. cr = (as * cs + ab * (cb -
  10707. as * (cb + cs - cr))) / ar;
  10708. }
  10709. r[i] = cr * 255;
  10710. }
  10711. return new Color(r, ar);
  10712. }
  10713. const colorBlendModeFunctions = {
  10714. multiply: function(cb, cs) {
  10715. return cb * cs;
  10716. },
  10717. screen: function(cb, cs) {
  10718. return cb + cs - cb * cs;
  10719. },
  10720. overlay: function(cb, cs) {
  10721. cb *= 2;
  10722. return (cb <= 1) ?
  10723. colorBlendModeFunctions.multiply(cb, cs) :
  10724. colorBlendModeFunctions.screen(cb - 1, cs);
  10725. },
  10726. softlight: function(cb, cs) {
  10727. let d = 1;
  10728. let e = cb;
  10729. if (cs > 0.5) {
  10730. e = 1;
  10731. d = (cb > 0.25) ? Math.sqrt(cb)
  10732. : ((16 * cb - 12) * cb + 4) * cb;
  10733. }
  10734. return cb - (1 - 2 * cs) * e * (d - cb);
  10735. },
  10736. hardlight: function(cb, cs) {
  10737. return colorBlendModeFunctions.overlay(cs, cb);
  10738. },
  10739. difference: function(cb, cs) {
  10740. return Math.abs(cb - cs);
  10741. },
  10742. exclusion: function(cb, cs) {
  10743. return cb + cs - 2 * cb * cs;
  10744. },
  10745. // non-w3c functions:
  10746. average: function(cb, cs) {
  10747. return (cb + cs) / 2;
  10748. },
  10749. negation: function(cb, cs) {
  10750. return 1 - Math.abs(cb + cs - 1);
  10751. }
  10752. };
  10753. for (const f in colorBlendModeFunctions) {
  10754. // eslint-disable-next-line no-prototype-builtins
  10755. if (colorBlendModeFunctions.hasOwnProperty(f)) {
  10756. colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
  10757. }
  10758. }
  10759. var dataUri = environment => {
  10760. const fallback = (functionThis, node) => new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context);
  10761. return { 'data-uri': function(mimetypeNode, filePathNode) {
  10762. if (!filePathNode) {
  10763. filePathNode = mimetypeNode;
  10764. mimetypeNode = null;
  10765. }
  10766. let mimetype = mimetypeNode && mimetypeNode.value;
  10767. let filePath = filePathNode.value;
  10768. const currentFileInfo = this.currentFileInfo;
  10769. const currentDirectory = currentFileInfo.rewriteUrls ?
  10770. currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  10771. const fragmentStart = filePath.indexOf('#');
  10772. let fragment = '';
  10773. if (fragmentStart !== -1) {
  10774. fragment = filePath.slice(fragmentStart);
  10775. filePath = filePath.slice(0, fragmentStart);
  10776. }
  10777. const context = clone(this.context);
  10778. context.rawBuffer = true;
  10779. const fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
  10780. if (!fileManager) {
  10781. return fallback(this, filePathNode);
  10782. }
  10783. let useBase64 = false;
  10784. // detect the mimetype if not given
  10785. if (!mimetypeNode) {
  10786. mimetype = environment.mimeLookup(filePath);
  10787. if (mimetype === 'image/svg+xml') {
  10788. useBase64 = false;
  10789. } else {
  10790. // use base 64 unless it's an ASCII or UTF-8 format
  10791. const charset = environment.charsetLookup(mimetype);
  10792. useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
  10793. }
  10794. if (useBase64) { mimetype += ';base64'; }
  10795. }
  10796. else {
  10797. useBase64 = /;base64$/.test(mimetype);
  10798. }
  10799. const fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
  10800. if (!fileSync.contents) {
  10801. logger.warn(`Skipped data-uri embedding of ${filePath} because file not found`);
  10802. return fallback(this, filePathNode || mimetypeNode);
  10803. }
  10804. let buf = fileSync.contents;
  10805. if (useBase64 && !environment.encodeBase64) {
  10806. return fallback(this, filePathNode);
  10807. }
  10808. buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
  10809. const uri = `data:${mimetype},${buf}${fragment}`;
  10810. return new URL(new Quoted(`"${uri}"`, uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  10811. }};
  10812. };
  10813. const getItemsFromNode = node => {
  10814. // handle non-array values as an array of length 1
  10815. // return 'undefined' if index is invalid
  10816. const items = Array.isArray(node.value) ?
  10817. node.value : Array(node);
  10818. return items;
  10819. };
  10820. var list = {
  10821. _SELF: function(n) {
  10822. return n;
  10823. },
  10824. '~': function(...expr) {
  10825. if (expr.length === 1) {
  10826. return expr[0];
  10827. }
  10828. return new Value(expr);
  10829. },
  10830. extract: function(values, index) {
  10831. // (1-based index)
  10832. index = index.value - 1;
  10833. return getItemsFromNode(values)[index];
  10834. },
  10835. length: function(values) {
  10836. return new Dimension(getItemsFromNode(values).length);
  10837. },
  10838. /**
  10839. * Creates a Less list of incremental values.
  10840. * Modeled after Lodash's range function, also exists natively in PHP
  10841. *
  10842. * @param {Dimension} [start=1]
  10843. * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
  10844. * @param {Dimension} [step=1]
  10845. */
  10846. range: function(start, end, step) {
  10847. let from;
  10848. let to;
  10849. let stepValue = 1;
  10850. const list = [];
  10851. if (end) {
  10852. to = end;
  10853. from = start.value;
  10854. if (step) {
  10855. stepValue = step.value;
  10856. }
  10857. }
  10858. else {
  10859. from = 1;
  10860. to = start;
  10861. }
  10862. for (let i = from; i <= to.value; i += stepValue) {
  10863. list.push(new Dimension(i, to.unit));
  10864. }
  10865. return new Expression(list);
  10866. },
  10867. each: function(list, rs) {
  10868. const rules = [];
  10869. let newRules;
  10870. let iterator;
  10871. const tryEval = val => {
  10872. if (val instanceof Node) {
  10873. return val.eval(this.context);
  10874. }
  10875. return val;
  10876. };
  10877. if (list.value && !(list instanceof Quoted)) {
  10878. if (Array.isArray(list.value)) {
  10879. iterator = list.value.map(tryEval);
  10880. } else {
  10881. iterator = [tryEval(list.value)];
  10882. }
  10883. } else if (list.ruleset) {
  10884. iterator = tryEval(list.ruleset).rules;
  10885. } else if (list.rules) {
  10886. iterator = list.rules.map(tryEval);
  10887. } else if (Array.isArray(list)) {
  10888. iterator = list.map(tryEval);
  10889. } else {
  10890. iterator = [tryEval(list)];
  10891. }
  10892. let valueName = '@value';
  10893. let keyName = '@key';
  10894. let indexName = '@index';
  10895. if (rs.params) {
  10896. valueName = rs.params[0] && rs.params[0].name;
  10897. keyName = rs.params[1] && rs.params[1].name;
  10898. indexName = rs.params[2] && rs.params[2].name;
  10899. rs = rs.rules;
  10900. } else {
  10901. rs = rs.ruleset;
  10902. }
  10903. for (let i = 0; i < iterator.length; i++) {
  10904. let key;
  10905. let value;
  10906. const item = iterator[i];
  10907. if (item instanceof Declaration) {
  10908. key = typeof item.name === 'string' ? item.name : item.name[0].value;
  10909. value = item.value;
  10910. } else {
  10911. key = new Dimension(i + 1);
  10912. value = item;
  10913. }
  10914. if (item instanceof Comment) {
  10915. continue;
  10916. }
  10917. newRules = rs.rules.slice(0);
  10918. if (valueName) {
  10919. newRules.push(new Declaration(valueName,
  10920. value,
  10921. false, false, this.index, this.currentFileInfo));
  10922. }
  10923. if (indexName) {
  10924. newRules.push(new Declaration(indexName,
  10925. new Dimension(i + 1),
  10926. false, false, this.index, this.currentFileInfo));
  10927. }
  10928. if (keyName) {
  10929. newRules.push(new Declaration(keyName,
  10930. key,
  10931. false, false, this.index, this.currentFileInfo));
  10932. }
  10933. rules.push(new Ruleset([ new(Selector)([ new Element('', '&') ]) ],
  10934. newRules,
  10935. rs.strictImports,
  10936. rs.visibilityInfo()
  10937. ));
  10938. }
  10939. return new Ruleset([ new(Selector)([ new Element('', '&') ]) ],
  10940. rules,
  10941. rs.strictImports,
  10942. rs.visibilityInfo()
  10943. ).eval(this.context);
  10944. }
  10945. };
  10946. const MathHelper = (fn, unit, n) => {
  10947. if (!(n instanceof Dimension)) {
  10948. throw { type: 'Argument', message: 'argument must be a number' };
  10949. }
  10950. if (unit === null) {
  10951. unit = n.unit;
  10952. } else {
  10953. n = n.unify();
  10954. }
  10955. return new Dimension(fn(parseFloat(n.value)), unit);
  10956. };
  10957. const mathFunctions = {
  10958. // name, unit
  10959. ceil: null,
  10960. floor: null,
  10961. sqrt: null,
  10962. abs: null,
  10963. tan: '',
  10964. sin: '',
  10965. cos: '',
  10966. atan: 'rad',
  10967. asin: 'rad',
  10968. acos: 'rad'
  10969. };
  10970. for (const f in mathFunctions) {
  10971. // eslint-disable-next-line no-prototype-builtins
  10972. if (mathFunctions.hasOwnProperty(f)) {
  10973. mathFunctions[f] = MathHelper.bind(null, Math[f], mathFunctions[f]);
  10974. }
  10975. }
  10976. mathFunctions.round = (n, f) => {
  10977. const fraction = typeof f === 'undefined' ? 0 : f.value;
  10978. return MathHelper(num => num.toFixed(fraction), null, n);
  10979. };
  10980. const minMax = function (isMin, args) {
  10981. args = Array.prototype.slice.call(args);
  10982. switch (args.length) {
  10983. case 0: throw { type: 'Argument', message: 'one or more arguments required' };
  10984. }
  10985. let i; // key is the unit.toString() for unified Dimension values,
  10986. let j;
  10987. let current;
  10988. let currentUnified;
  10989. let referenceUnified;
  10990. let unit;
  10991. let unitStatic;
  10992. let unitClone;
  10993. const // elems only contains original argument values.
  10994. order = [];
  10995. const values = {};
  10996. // value is the index into the order array.
  10997. for (i = 0; i < args.length; i++) {
  10998. current = args[i];
  10999. if (!(current instanceof Dimension)) {
  11000. if (Array.isArray(args[i].value)) {
  11001. Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
  11002. continue;
  11003. } else {
  11004. throw { type: 'Argument', message: 'incompatible types' };
  11005. }
  11006. }
  11007. currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
  11008. unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
  11009. unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
  11010. unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
  11011. j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
  11012. if (j === undefined) {
  11013. if (unitStatic !== undefined && unit !== unitStatic) {
  11014. throw { type: 'Argument', message: 'incompatible types' };
  11015. }
  11016. values[unit] = order.length;
  11017. order.push(current);
  11018. continue;
  11019. }
  11020. referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
  11021. if ( isMin && currentUnified.value < referenceUnified.value ||
  11022. !isMin && currentUnified.value > referenceUnified.value) {
  11023. order[j] = current;
  11024. }
  11025. }
  11026. if (order.length == 1) {
  11027. return order[0];
  11028. }
  11029. args = order.map(a => { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
  11030. return new Anonymous(`${isMin ? 'min' : 'max'}(${args})`);
  11031. };
  11032. var number = {
  11033. min: function(...args) {
  11034. try {
  11035. return minMax.call(this, true, args);
  11036. } catch (e) {}
  11037. },
  11038. max: function(...args) {
  11039. try {
  11040. return minMax.call(this, false, args);
  11041. } catch (e) {}
  11042. },
  11043. convert: function (val, unit) {
  11044. return val.convertTo(unit.value);
  11045. },
  11046. pi: function () {
  11047. return new Dimension(Math.PI);
  11048. },
  11049. mod: function(a, b) {
  11050. return new Dimension(a.value % b.value, a.unit);
  11051. },
  11052. pow: function(x, y) {
  11053. if (typeof x === 'number' && typeof y === 'number') {
  11054. x = new Dimension(x);
  11055. y = new Dimension(y);
  11056. } else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
  11057. throw { type: 'Argument', message: 'arguments must be numbers' };
  11058. }
  11059. return new Dimension(Math.pow(x.value, y.value), x.unit);
  11060. },
  11061. percentage: function (n) {
  11062. const result = MathHelper(num => num * 100, '%', n);
  11063. return result;
  11064. }
  11065. };
  11066. var string = {
  11067. e: function (str) {
  11068. return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
  11069. },
  11070. escape: function (str) {
  11071. return new Anonymous(
  11072. encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
  11073. .replace(/\(/g, '%28').replace(/\)/g, '%29'));
  11074. },
  11075. replace: function (string, pattern, replacement, flags) {
  11076. let result = string.value;
  11077. replacement = (replacement.type === 'Quoted') ?
  11078. replacement.value : replacement.toCSS();
  11079. result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
  11080. return new Quoted(string.quote || '', result, string.escaped);
  11081. },
  11082. '%': function (string /* arg, arg, ... */) {
  11083. const args = Array.prototype.slice.call(arguments, 1);
  11084. let result = string.value;
  11085. for (let i = 0; i < args.length; i++) {
  11086. /* jshint loopfunc:true */
  11087. result = result.replace(/%[sda]/i, token => {
  11088. const value = ((args[i].type === 'Quoted') &&
  11089. token.match(/s/i)) ? args[i].value : args[i].toCSS();
  11090. return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
  11091. });
  11092. }
  11093. result = result.replace(/%%/g, '%');
  11094. return new Quoted(string.quote || '', result, string.escaped);
  11095. }
  11096. };
  11097. var svg = () => {
  11098. return { 'svg-gradient': function(direction) {
  11099. let stops;
  11100. let gradientDirectionSvg;
  11101. let gradientType = 'linear';
  11102. let rectangleDimension = 'x="0" y="0" width="1" height="1"';
  11103. const renderEnv = {compress: false};
  11104. let returner;
  11105. const directionValue = direction.toCSS(renderEnv);
  11106. let i;
  11107. let color;
  11108. let position;
  11109. let positionValue;
  11110. let alpha;
  11111. function throwArgumentDescriptor() {
  11112. throw { type: 'Argument',
  11113. message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
  11114. ' end_color [end_position] or direction, color list' };
  11115. }
  11116. if (arguments.length == 2) {
  11117. if (arguments[1].value.length < 2) {
  11118. throwArgumentDescriptor();
  11119. }
  11120. stops = arguments[1].value;
  11121. } else if (arguments.length < 3) {
  11122. throwArgumentDescriptor();
  11123. } else {
  11124. stops = Array.prototype.slice.call(arguments, 1);
  11125. }
  11126. switch (directionValue) {
  11127. case 'to bottom':
  11128. gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
  11129. break;
  11130. case 'to right':
  11131. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
  11132. break;
  11133. case 'to bottom right':
  11134. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
  11135. break;
  11136. case 'to top right':
  11137. gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
  11138. break;
  11139. case 'ellipse':
  11140. case 'ellipse at center':
  11141. gradientType = 'radial';
  11142. gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
  11143. rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
  11144. break;
  11145. default:
  11146. throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
  11147. ' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
  11148. }
  11149. returner = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><${gradientType}Gradient id="g" ${gradientDirectionSvg}>`;
  11150. for (i = 0; i < stops.length; i += 1) {
  11151. if (stops[i] instanceof Expression) {
  11152. color = stops[i].value[0];
  11153. position = stops[i].value[1];
  11154. } else {
  11155. color = stops[i];
  11156. position = undefined;
  11157. }
  11158. if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) {
  11159. throwArgumentDescriptor();
  11160. }
  11161. positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
  11162. alpha = color.alpha;
  11163. returner += `<stop offset="${positionValue}" stop-color="${color.toRGB()}"${alpha < 1 ? ` stop-opacity="${alpha}"` : ''}/>`;
  11164. }
  11165. returner += `</${gradientType}Gradient><rect ${rectangleDimension} fill="url(#g)" /></svg>`;
  11166. returner = encodeURIComponent(returner);
  11167. returner = `data:image/svg+xml,${returner}`;
  11168. return new URL(new Quoted(`'${returner}'`, returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  11169. }};
  11170. };
  11171. const isa = (n, Type) => (n instanceof Type) ? Keyword.True : Keyword.False;
  11172. const isunit = (n, unit) => {
  11173. if (unit === undefined) {
  11174. throw { type: 'Argument', message: 'missing the required second argument to isunit.' };
  11175. }
  11176. unit = typeof unit.value === 'string' ? unit.value : unit;
  11177. if (typeof unit !== 'string') {
  11178. throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' };
  11179. }
  11180. return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
  11181. };
  11182. var types = {
  11183. isruleset: function (n) {
  11184. return isa(n, DetachedRuleset);
  11185. },
  11186. iscolor: function (n) {
  11187. return isa(n, Color);
  11188. },
  11189. isnumber: function (n) {
  11190. return isa(n, Dimension);
  11191. },
  11192. isstring: function (n) {
  11193. return isa(n, Quoted);
  11194. },
  11195. iskeyword: function (n) {
  11196. return isa(n, Keyword);
  11197. },
  11198. isurl: function (n) {
  11199. return isa(n, URL);
  11200. },
  11201. ispixel: function (n) {
  11202. return isunit(n, 'px');
  11203. },
  11204. ispercentage: function (n) {
  11205. return isunit(n, '%');
  11206. },
  11207. isem: function (n) {
  11208. return isunit(n, 'em');
  11209. },
  11210. isunit,
  11211. unit: function (val, unit) {
  11212. if (!(val instanceof Dimension)) {
  11213. throw { type: 'Argument',
  11214. message: `the first argument to unit must be a number${val instanceof Operation ? '. Have you forgotten parenthesis?' : ''}` };
  11215. }
  11216. if (unit) {
  11217. if (unit instanceof Keyword) {
  11218. unit = unit.value;
  11219. } else {
  11220. unit = unit.toCSS();
  11221. }
  11222. } else {
  11223. unit = '';
  11224. }
  11225. return new Dimension(val.value, unit);
  11226. },
  11227. 'get-unit': function (n) {
  11228. return new Anonymous(n.unit);
  11229. }
  11230. };
  11231. /** @param {*[]} args */
  11232. const styleExpression = function (args) {
  11233. args = Array.prototype.slice.call(args);
  11234. if (args.length === 0) {
  11235. throw { type: 'Argument', message: 'one or more arguments required' };
  11236. }
  11237. const entityList = [new Variable(args[0].value, this.index, this.currentFileInfo).eval(this.context)];
  11238. const result = entityList.map(a => { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
  11239. return new Anonymous(`style(${result})`);
  11240. };
  11241. var style = {
  11242. /** @param {...*} args */
  11243. style: function(...args) {
  11244. try {
  11245. return styleExpression.call(this, args);
  11246. } catch (e) {
  11247. // When style() is used as a CSS function (e.g. @container style(--responsive: true)),
  11248. // arguments won't be valid Less variables. Return undefined to let the
  11249. // parser fall through and treat it as plain CSS.
  11250. }
  11251. },
  11252. };
  11253. var functions = environment => {
  11254. const functions = { functionRegistry, functionCaller };
  11255. // register functions
  11256. functionRegistry.addMultiple(boolean$1);
  11257. functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
  11258. functionRegistry.addMultiple(color);
  11259. functionRegistry.addMultiple(colorBlend);
  11260. functionRegistry.addMultiple(dataUri(environment));
  11261. functionRegistry.addMultiple(list);
  11262. functionRegistry.addMultiple(mathFunctions);
  11263. functionRegistry.addMultiple(number);
  11264. functionRegistry.addMultiple(string);
  11265. functionRegistry.addMultiple(svg());
  11266. functionRegistry.addMultiple(types);
  11267. functionRegistry.addMultiple(style);
  11268. return functions;
  11269. };
  11270. /**
  11271. * @param {import('./tree/node.js').default} root
  11272. * @param {{ variables?: Record<string, *>, compress?: boolean, pluginManager?: *, frames?: *[] }} options
  11273. * @returns {import('./tree/node.js').default}
  11274. */
  11275. function transformTree(root, options) {
  11276. options = options || {};
  11277. let evaldRoot;
  11278. let variables = options.variables;
  11279. const evalEnv = new contexts.Eval(options);
  11280. //
  11281. // Allows setting variables with a hash, so:
  11282. //
  11283. // `{ color: new tree.Color('#f01') }` will become:
  11284. //
  11285. // new tree.Declaration('@color',
  11286. // new tree.Value([
  11287. // new tree.Expression([
  11288. // new tree.Color('#f01')
  11289. // ])
  11290. // ])
  11291. // )
  11292. //
  11293. if (typeof variables === 'object' && !Array.isArray(variables)) {
  11294. variables = Object.keys(variables).map(function (k) {
  11295. let value = variables[k];
  11296. if (!(value instanceof tree.Value)) {
  11297. if (!(value instanceof tree.Expression)) {
  11298. value = new tree.Expression([value]);
  11299. }
  11300. value = new tree.Value([value]);
  11301. }
  11302. return new tree.Declaration(`@${k}`, value, false, null, 0);
  11303. });
  11304. evalEnv.frames = [new tree.Ruleset(null, variables)];
  11305. }
  11306. const visitors$1 = [
  11307. new visitors.JoinSelectorVisitor(),
  11308. new visitors.MarkVisibleSelectorsVisitor(true),
  11309. new visitors.ExtendVisitor(),
  11310. new visitors.ToCSSVisitor({compress: Boolean(options.compress)})
  11311. ];
  11312. const preEvalVisitors = [];
  11313. let v;
  11314. let visitorIterator;
  11315. /**
  11316. * first() / get() allows visitors to be added while visiting
  11317. *
  11318. * @todo Add scoping for visitors just like functions for @plugin; right now they're global
  11319. */
  11320. if (options.pluginManager) {
  11321. visitorIterator = options.pluginManager.visitor();
  11322. for (let i = 0; i < 2; i++) {
  11323. visitorIterator.first();
  11324. while ((v = visitorIterator.get())) {
  11325. if (v.isPreEvalVisitor) {
  11326. if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
  11327. preEvalVisitors.push(v);
  11328. v.run(root);
  11329. }
  11330. }
  11331. else {
  11332. if (i === 0 || visitors$1.indexOf(v) === -1) {
  11333. if (v.isPreVisitor) {
  11334. visitors$1.unshift(v);
  11335. }
  11336. else {
  11337. visitors$1.push(v);
  11338. }
  11339. }
  11340. }
  11341. }
  11342. }
  11343. }
  11344. evaldRoot = root.eval(evalEnv);
  11345. for (let i = 0; i < visitors$1.length; i++) {
  11346. visitors$1[i].run(evaldRoot);
  11347. }
  11348. // Run any remaining visitors added after eval pass
  11349. if (options.pluginManager) {
  11350. visitorIterator.first();
  11351. while ((v = visitorIterator.get())) {
  11352. if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
  11353. v.run(evaldRoot);
  11354. }
  11355. }
  11356. }
  11357. return evaldRoot;
  11358. }
  11359. /**
  11360. * Plugin Manager
  11361. */
  11362. class PluginManager {
  11363. constructor(less) {
  11364. this.less = less;
  11365. this.visitors = [];
  11366. this.preProcessors = [];
  11367. this.postProcessors = [];
  11368. this.installedPlugins = [];
  11369. this.fileManagers = [];
  11370. this.iterator = -1;
  11371. this.pluginCache = {};
  11372. this.Loader = new less.PluginLoader(less);
  11373. }
  11374. /**
  11375. * Adds all the plugins in the array
  11376. * @param {Array} plugins
  11377. */
  11378. addPlugins(plugins) {
  11379. if (plugins) {
  11380. for (let i = 0; i < plugins.length; i++) {
  11381. this.addPlugin(plugins[i]);
  11382. }
  11383. }
  11384. }
  11385. /**
  11386. *
  11387. * @param plugin
  11388. * @param {String} filename
  11389. */
  11390. addPlugin(plugin, filename, functionRegistry) {
  11391. this.installedPlugins.push(plugin);
  11392. if (filename) {
  11393. this.pluginCache[filename] = plugin;
  11394. }
  11395. if (plugin.install) {
  11396. plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
  11397. }
  11398. }
  11399. /**
  11400. *
  11401. * @param filename
  11402. */
  11403. get(filename) {
  11404. return this.pluginCache[filename];
  11405. }
  11406. /**
  11407. * Adds a visitor. The visitor object has options on itself to determine
  11408. * when it should run.
  11409. * @param visitor
  11410. */
  11411. addVisitor(visitor) {
  11412. this.visitors.push(visitor);
  11413. }
  11414. /**
  11415. * Adds a pre processor object
  11416. * @param {object} preProcessor
  11417. * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
  11418. */
  11419. addPreProcessor(preProcessor, priority) {
  11420. let indexToInsertAt;
  11421. for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
  11422. if (this.preProcessors[indexToInsertAt].priority >= priority) {
  11423. break;
  11424. }
  11425. }
  11426. this.preProcessors.splice(indexToInsertAt, 0, {preProcessor, priority});
  11427. }
  11428. /**
  11429. * Adds a post processor object
  11430. * @param {object} postProcessor
  11431. * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
  11432. */
  11433. addPostProcessor(postProcessor, priority) {
  11434. let indexToInsertAt;
  11435. for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
  11436. if (this.postProcessors[indexToInsertAt].priority >= priority) {
  11437. break;
  11438. }
  11439. }
  11440. this.postProcessors.splice(indexToInsertAt, 0, {postProcessor, priority});
  11441. }
  11442. /**
  11443. *
  11444. * @param manager
  11445. */
  11446. addFileManager(manager) {
  11447. this.fileManagers.push(manager);
  11448. }
  11449. /**
  11450. *
  11451. * @returns {Array}
  11452. * @private
  11453. */
  11454. getPreProcessors() {
  11455. const preProcessors = [];
  11456. for (let i = 0; i < this.preProcessors.length; i++) {
  11457. preProcessors.push(this.preProcessors[i].preProcessor);
  11458. }
  11459. return preProcessors;
  11460. }
  11461. /**
  11462. *
  11463. * @returns {Array}
  11464. * @private
  11465. */
  11466. getPostProcessors() {
  11467. const postProcessors = [];
  11468. for (let i = 0; i < this.postProcessors.length; i++) {
  11469. postProcessors.push(this.postProcessors[i].postProcessor);
  11470. }
  11471. return postProcessors;
  11472. }
  11473. /**
  11474. *
  11475. * @returns {Array}
  11476. * @private
  11477. */
  11478. getVisitors() {
  11479. return this.visitors;
  11480. }
  11481. visitor() {
  11482. const self = this;
  11483. return {
  11484. first: function() {
  11485. self.iterator = -1;
  11486. return self.visitors[self.iterator];
  11487. },
  11488. get: function() {
  11489. self.iterator += 1;
  11490. return self.visitors[self.iterator];
  11491. }
  11492. };
  11493. }
  11494. /**
  11495. *
  11496. * @returns {Array}
  11497. * @private
  11498. */
  11499. getFileManagers() {
  11500. return this.fileManagers;
  11501. }
  11502. }
  11503. let pm;
  11504. const PluginManagerFactory = function(less, newFactory) {
  11505. if (newFactory || !pm) {
  11506. pm = new PluginManager(less);
  11507. }
  11508. return pm;
  11509. };
  11510. function SourceMapOutput (environment) {
  11511. class SourceMapOutput {
  11512. constructor(options) {
  11513. this._css = [];
  11514. this._rootNode = options.rootNode;
  11515. this._contentsMap = options.contentsMap;
  11516. this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
  11517. if (options.sourceMapFilename) {
  11518. this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
  11519. }
  11520. this._outputFilename = options.outputFilename ? options.outputFilename.replace(/\\/g, '/') : options.outputFilename;
  11521. this.sourceMapURL = options.sourceMapURL;
  11522. if (options.sourceMapBasepath) {
  11523. this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
  11524. }
  11525. if (options.sourceMapRootpath) {
  11526. this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
  11527. if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
  11528. this._sourceMapRootpath += '/';
  11529. }
  11530. } else {
  11531. this._sourceMapRootpath = '';
  11532. }
  11533. this._outputSourceFiles = options.outputSourceFiles;
  11534. this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
  11535. this._lineNumber = 0;
  11536. this._column = 0;
  11537. }
  11538. removeBasepath(path) {
  11539. if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
  11540. path = path.substring(this._sourceMapBasepath.length);
  11541. if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
  11542. path = path.substring(1);
  11543. }
  11544. }
  11545. return path;
  11546. }
  11547. normalizeFilename(filename) {
  11548. filename = filename.replace(/\\/g, '/');
  11549. filename = this.removeBasepath(filename);
  11550. return (this._sourceMapRootpath || '') + filename;
  11551. }
  11552. add(chunk, fileInfo, index, mapLines) {
  11553. // ignore adding empty strings
  11554. if (!chunk) {
  11555. return;
  11556. }
  11557. let lines, sourceLines, columns, sourceColumns, i;
  11558. if (fileInfo && fileInfo.filename) {
  11559. let inputSource = this._contentsMap[fileInfo.filename];
  11560. // remove vars/banner added to the top of the file
  11561. if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
  11562. // adjust the index
  11563. index -= this._contentsIgnoredCharsMap[fileInfo.filename];
  11564. if (index < 0) { index = 0; }
  11565. // adjust the source
  11566. inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
  11567. }
  11568. /**
  11569. * ignore empty content, or failsafe
  11570. * if contents map is incorrect
  11571. */
  11572. if (inputSource === undefined) {
  11573. this._css.push(chunk);
  11574. return;
  11575. }
  11576. inputSource = inputSource.substring(0, index);
  11577. sourceLines = inputSource.split('\n');
  11578. sourceColumns = sourceLines[sourceLines.length - 1];
  11579. }
  11580. lines = chunk.split('\n');
  11581. columns = lines[lines.length - 1];
  11582. if (fileInfo && fileInfo.filename) {
  11583. if (!mapLines) {
  11584. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column},
  11585. original: { line: sourceLines.length, column: sourceColumns.length},
  11586. source: this.normalizeFilename(fileInfo.filename)});
  11587. } else {
  11588. for (i = 0; i < lines.length; i++) {
  11589. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0},
  11590. original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0},
  11591. source: this.normalizeFilename(fileInfo.filename)});
  11592. }
  11593. }
  11594. }
  11595. if (lines.length === 1) {
  11596. this._column += columns.length;
  11597. } else {
  11598. this._lineNumber += lines.length - 1;
  11599. this._column = columns.length;
  11600. }
  11601. this._css.push(chunk);
  11602. }
  11603. isEmpty() {
  11604. return this._css.length === 0;
  11605. }
  11606. toCSS(context) {
  11607. this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
  11608. if (this._outputSourceFiles) {
  11609. for (const filename in this._contentsMap) {
  11610. // eslint-disable-next-line no-prototype-builtins
  11611. if (this._contentsMap.hasOwnProperty(filename)) {
  11612. let source = this._contentsMap[filename];
  11613. if (this._contentsIgnoredCharsMap[filename]) {
  11614. source = source.slice(this._contentsIgnoredCharsMap[filename]);
  11615. }
  11616. this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
  11617. }
  11618. }
  11619. }
  11620. this._rootNode.genCSS(context, this);
  11621. if (this._css.length > 0) {
  11622. let sourceMapURL;
  11623. const sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
  11624. if (this.sourceMapURL) {
  11625. sourceMapURL = this.sourceMapURL;
  11626. } else if (this._sourceMapFilename) {
  11627. sourceMapURL = this._sourceMapFilename;
  11628. }
  11629. this.sourceMapURL = sourceMapURL;
  11630. this.sourceMap = sourceMapContent;
  11631. }
  11632. return this._css.join('');
  11633. }
  11634. }
  11635. return SourceMapOutput;
  11636. }
  11637. function SourceMapBuilder (SourceMapOutput, environment) {
  11638. class SourceMapBuilder {
  11639. constructor(options) {
  11640. this.options = options;
  11641. }
  11642. toCSS(rootNode, options, imports) {
  11643. const sourceMapOutput = new SourceMapOutput(
  11644. {
  11645. contentsIgnoredCharsMap: imports.contentsIgnoredChars,
  11646. rootNode,
  11647. contentsMap: imports.contents,
  11648. sourceMapFilename: this.options.sourceMapFilename,
  11649. sourceMapURL: this.options.sourceMapURL,
  11650. outputFilename: this.options.sourceMapOutputFilename,
  11651. sourceMapBasepath: this.options.sourceMapBasepath,
  11652. sourceMapRootpath: this.options.sourceMapRootpath,
  11653. outputSourceFiles: this.options.outputSourceFiles,
  11654. sourceMapGenerator: this.options.sourceMapGenerator,
  11655. sourceMapFileInline: this.options.sourceMapFileInline,
  11656. disableSourcemapAnnotation: this.options.disableSourcemapAnnotation
  11657. });
  11658. const css = sourceMapOutput.toCSS(options);
  11659. this.sourceMap = sourceMapOutput.sourceMap;
  11660. this.sourceMapURL = sourceMapOutput.sourceMapURL;
  11661. if (this.options.sourceMapInputFilename) {
  11662. this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
  11663. }
  11664. if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
  11665. this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
  11666. }
  11667. return css + this.getCSSAppendage();
  11668. }
  11669. getCSSAppendage() {
  11670. let sourceMapURL = this.sourceMapURL;
  11671. if (this.options.sourceMapFileInline) {
  11672. if (this.sourceMap === undefined) {
  11673. return '';
  11674. }
  11675. sourceMapURL = `data:application/json;base64,${environment.encodeBase64(this.sourceMap)}`;
  11676. }
  11677. if (this.options.disableSourcemapAnnotation) {
  11678. return '';
  11679. }
  11680. if (sourceMapURL) {
  11681. return `/*# sourceMappingURL=${sourceMapURL} */`;
  11682. }
  11683. return '';
  11684. }
  11685. getExternalSourceMap() {
  11686. return this.sourceMap;
  11687. }
  11688. setExternalSourceMap(sourceMap) {
  11689. this.sourceMap = sourceMap;
  11690. }
  11691. isInline() {
  11692. return this.options.sourceMapFileInline;
  11693. }
  11694. getSourceMapURL() {
  11695. return this.sourceMapURL;
  11696. }
  11697. getOutputFilename() {
  11698. return this.options.sourceMapOutputFilename;
  11699. }
  11700. getInputFilename() {
  11701. return this.sourceMapInputFilename;
  11702. }
  11703. }
  11704. return SourceMapBuilder;
  11705. }
  11706. function ParseTree(SourceMapBuilder) {
  11707. class ParseTree {
  11708. constructor(root, imports) {
  11709. this.root = root;
  11710. this.imports = imports;
  11711. }
  11712. toCSS(options) {
  11713. let evaldRoot;
  11714. const result = {};
  11715. let sourceMapBuilder;
  11716. try {
  11717. evaldRoot = transformTree(this.root, options);
  11718. } catch (e) {
  11719. throw new LessError(e, this.imports);
  11720. }
  11721. try {
  11722. const compress = Boolean(options.compress);
  11723. if (compress) {
  11724. logger.warn('The compress option has been deprecated. ' +
  11725. 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
  11726. }
  11727. const toCSSOptions = {
  11728. compress,
  11729. // @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead. All modes will be removed in a future version.
  11730. dumpLineNumbers: options.dumpLineNumbers,
  11731. strictUnits: Boolean(options.strictUnits),
  11732. numPrecision: 8};
  11733. if (options.sourceMap) {
  11734. // Normalize sourceMap option: if it's just true, convert to object
  11735. if (options.sourceMap === true) {
  11736. options.sourceMap = {};
  11737. }
  11738. const sourceMapOpts = options.sourceMap;
  11739. // Set sourceMapInputFilename if not set and filename is available
  11740. if (!sourceMapOpts.sourceMapInputFilename && options.filename) {
  11741. sourceMapOpts.sourceMapInputFilename = options.filename;
  11742. }
  11743. // Default sourceMapBasepath to the input file's directory if not set
  11744. // This matches the behavior documented and implemented in bin/lessc
  11745. if (sourceMapOpts.sourceMapBasepath === undefined && options.filename) {
  11746. // Get directory from filename using string manipulation (works cross-platform)
  11747. const lastSlash = Math.max(options.filename.lastIndexOf('/'), options.filename.lastIndexOf('\\'));
  11748. if (lastSlash >= 0) {
  11749. sourceMapOpts.sourceMapBasepath = options.filename.substring(0, lastSlash);
  11750. } else {
  11751. // No directory separator found, use current directory
  11752. sourceMapOpts.sourceMapBasepath = '.';
  11753. }
  11754. }
  11755. // Handle sourceMapFullFilename (CLI-specific: --source-map=filename)
  11756. // This is converted to sourceMapFilename and sourceMapOutputFilename
  11757. if (sourceMapOpts.sourceMapFullFilename && !sourceMapOpts.sourceMapFileInline) {
  11758. // This case is handled by lessc before calling render
  11759. // We just need to ensure sourceMapFilename is set if sourceMapFullFilename is provided
  11760. if (!sourceMapOpts.sourceMapFilename && !sourceMapOpts.sourceMapURL) {
  11761. // Extract just the basename for the sourceMappingURL comment
  11762. const mapBase = sourceMapOpts.sourceMapFullFilename.split(/[/\\]/).pop();
  11763. sourceMapOpts.sourceMapFilename = mapBase;
  11764. }
  11765. } else if (!sourceMapOpts.sourceMapFilename && !sourceMapOpts.sourceMapURL) {
  11766. // If sourceMapFilename is not set and sourceMapURL is not set,
  11767. // derive it from the output filename (if available) or input filename
  11768. if (sourceMapOpts.sourceMapOutputFilename) {
  11769. // Use output filename + .map
  11770. sourceMapOpts.sourceMapFilename = sourceMapOpts.sourceMapOutputFilename + '.map';
  11771. } else if (options.filename) {
  11772. // Fallback to input filename + .css.map (basename only)
  11773. const inputBasename = options.filename.split(/[/\\]/).pop().replace(/\.[^/.]+$/, '');
  11774. sourceMapOpts.sourceMapFilename = inputBasename + '.css.map';
  11775. }
  11776. }
  11777. // Default sourceMapOutputFilename if not set
  11778. if (!sourceMapOpts.sourceMapOutputFilename) {
  11779. if (options.filename) {
  11780. const inputBasename = options.filename.split(/[/\\]/).pop().replace(/\.[^/.]+$/, '');
  11781. sourceMapOpts.sourceMapOutputFilename = inputBasename + '.css';
  11782. } else {
  11783. sourceMapOpts.sourceMapOutputFilename = 'output.css';
  11784. }
  11785. }
  11786. sourceMapBuilder = new SourceMapBuilder(sourceMapOpts);
  11787. result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
  11788. } else {
  11789. result.css = evaldRoot.toCSS(toCSSOptions);
  11790. }
  11791. } catch (e) {
  11792. throw new LessError(e, this.imports);
  11793. }
  11794. if (options.pluginManager) {
  11795. const postProcessors = options.pluginManager.getPostProcessors();
  11796. for (let i = 0; i < postProcessors.length; i++) {
  11797. result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options, imports: this.imports });
  11798. }
  11799. }
  11800. if (options.sourceMap) {
  11801. result.map = sourceMapBuilder.getExternalSourceMap();
  11802. }
  11803. result.imports = [];
  11804. for (const file in this.imports.files) {
  11805. if (Object.prototype.hasOwnProperty.call(this.imports.files, file) && file !== this.imports.rootFilename) {
  11806. result.imports.push(file);
  11807. }
  11808. }
  11809. return result;
  11810. }
  11811. }
  11812. return ParseTree;
  11813. }
  11814. function ImportManager(environment) {
  11815. // FileInfo = {
  11816. // 'rewriteUrls' - option - whether to adjust URL's to be relative
  11817. // 'filename' - full resolved filename of current file
  11818. // 'rootpath' - path to append to normal URLs for this node
  11819. // 'currentDirectory' - path to the current file, absolute
  11820. // 'rootFilename' - filename of the base file
  11821. // 'entryPath' - absolute path to the entry file
  11822. // 'reference' - whether the file should not be output and only output parts that are referenced
  11823. class ImportManager {
  11824. constructor(less, context, rootFileInfo) {
  11825. this.less = less;
  11826. this.rootFilename = rootFileInfo.filename;
  11827. this.paths = context.paths || []; // Search paths, when importing
  11828. this.contents = {}; // map - filename to contents of all the files
  11829. this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
  11830. this.mime = context.mime;
  11831. this.error = null;
  11832. this.context = context;
  11833. // Deprecated? Unused outside of here, could be useful.
  11834. this.queue = []; // Files which haven't been imported yet
  11835. this.files = {}; // Holds the imported parse trees.
  11836. }
  11837. /**
  11838. * Add an import to be imported
  11839. * @param path - the raw path
  11840. * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
  11841. * @param currentFileInfo - the current file info (used for instance to work out relative paths)
  11842. * @param importOptions - import options
  11843. * @param callback - callback for when it is imported
  11844. */
  11845. push(path, tryAppendExtension, currentFileInfo, importOptions, callback) {
  11846. const importManager = this, pluginLoader = this.context.pluginManager.Loader;
  11847. this.queue.push(path);
  11848. const fileParsedFunc = function (e, root, fullPath) {
  11849. importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
  11850. const importedEqualsRoot = fullPath === importManager.rootFilename;
  11851. if (importOptions.optional && e) {
  11852. callback(null, {rules:[]}, false, null);
  11853. logger.info(`The file ${fullPath} was skipped because it was not found and the import was marked optional.`);
  11854. }
  11855. else {
  11856. // Inline imports aren't cached here.
  11857. // If we start to cache them, please make sure they won't conflict with non-inline imports of the
  11858. // same name as they used to do before this comment and the condition below have been added.
  11859. if (!importManager.files[fullPath] && !importOptions.inline) {
  11860. importManager.files[fullPath] = { root, options: importOptions };
  11861. }
  11862. if (e && !importManager.error) { importManager.error = e; }
  11863. callback(e, root, importedEqualsRoot, fullPath);
  11864. }
  11865. };
  11866. const newFileInfo = {
  11867. rewriteUrls: this.context.rewriteUrls,
  11868. entryPath: currentFileInfo.entryPath,
  11869. rootpath: currentFileInfo.rootpath,
  11870. rootFilename: currentFileInfo.rootFilename
  11871. };
  11872. const fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
  11873. if (!fileManager) {
  11874. fileParsedFunc({ message: `Could not find a file-manager for ${path}` });
  11875. return;
  11876. }
  11877. const loadFileCallback = function(loadedFile) {
  11878. let plugin;
  11879. const resolvedFilename = loadedFile.filename;
  11880. const contents = loadedFile.contents.replace(/^\uFEFF/, '');
  11881. // Pass on an updated rootpath if path of imported file is relative and file
  11882. // is in a (sub|sup) directory
  11883. //
  11884. // Examples:
  11885. // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
  11886. // then rootpath should become 'less/module/nav/'
  11887. // - If path of imported file is '../mixins.less' and rootpath is 'less/',
  11888. // then rootpath should become 'less/../'
  11889. newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
  11890. if (newFileInfo.rewriteUrls) {
  11891. newFileInfo.rootpath = fileManager.join(
  11892. (importManager.context.rootpath || ''),
  11893. fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
  11894. if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
  11895. newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
  11896. }
  11897. }
  11898. newFileInfo.filename = resolvedFilename;
  11899. const newEnv = new contexts.Parse(importManager.context);
  11900. newEnv.processImports = false;
  11901. importManager.contents[resolvedFilename] = contents;
  11902. if (currentFileInfo.reference || importOptions.reference) {
  11903. newFileInfo.reference = true;
  11904. }
  11905. if (importOptions.isPlugin) {
  11906. plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
  11907. if (plugin instanceof LessError) {
  11908. fileParsedFunc(plugin, null, resolvedFilename);
  11909. }
  11910. else {
  11911. fileParsedFunc(null, plugin, resolvedFilename);
  11912. }
  11913. } else if (importOptions.inline) {
  11914. fileParsedFunc(null, contents, resolvedFilename);
  11915. } else {
  11916. // import (multiple) parse trees apparently get altered and can't be cached.
  11917. // TODO: investigate why this is
  11918. if (importManager.files[resolvedFilename]
  11919. && !importManager.files[resolvedFilename].options.multiple
  11920. && !importOptions.multiple) {
  11921. fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
  11922. }
  11923. else {
  11924. new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
  11925. fileParsedFunc(e, root, resolvedFilename);
  11926. });
  11927. }
  11928. }
  11929. };
  11930. let loadedFile;
  11931. let promise;
  11932. const context = clone(this.context);
  11933. if (tryAppendExtension) {
  11934. context.ext = importOptions.isPlugin ? '.js' : '.less';
  11935. }
  11936. if (importOptions.isPlugin) {
  11937. context.mime = 'application/javascript';
  11938. if (context.syncImport) {
  11939. loadedFile = pluginLoader.loadPluginSync(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  11940. } else {
  11941. promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  11942. }
  11943. }
  11944. else {
  11945. if (context.syncImport) {
  11946. loadedFile = fileManager.loadFileSync(path, currentFileInfo.currentDirectory, context, environment);
  11947. } else {
  11948. promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment,
  11949. (err, loadedFile) => {
  11950. if (err) {
  11951. fileParsedFunc(err);
  11952. } else {
  11953. loadFileCallback(loadedFile);
  11954. }
  11955. });
  11956. }
  11957. }
  11958. if (loadedFile) {
  11959. if (!loadedFile.filename) {
  11960. fileParsedFunc(loadedFile);
  11961. } else {
  11962. loadFileCallback(loadedFile);
  11963. }
  11964. } else if (promise) {
  11965. promise.then(loadFileCallback, fileParsedFunc);
  11966. }
  11967. }
  11968. }
  11969. return ImportManager;
  11970. }
  11971. function Parse(environment, ParseTree, ImportManager) {
  11972. const parse = function (input, options, callback) {
  11973. if (typeof options === 'function') {
  11974. callback = options;
  11975. options = copyOptions(this.options, {});
  11976. }
  11977. else {
  11978. options = copyOptions(this.options, options || {});
  11979. }
  11980. if (!callback) {
  11981. const self = this;
  11982. return new Promise(function (resolve, reject) {
  11983. parse.call(self, input, options, function(err, output) {
  11984. if (err) {
  11985. reject(err);
  11986. } else {
  11987. resolve(output);
  11988. }
  11989. });
  11990. });
  11991. } else {
  11992. let context;
  11993. let rootFileInfo;
  11994. const pluginManager = new PluginManagerFactory(this, !options.reUsePluginManager);
  11995. options.pluginManager = pluginManager;
  11996. context = new contexts.Parse(options);
  11997. if (options.rootFileInfo) {
  11998. rootFileInfo = options.rootFileInfo;
  11999. } else {
  12000. const filename = options.filename || 'input';
  12001. const entryPath = filename.replace(/[^/\\]*$/, '');
  12002. rootFileInfo = {
  12003. filename,
  12004. rewriteUrls: context.rewriteUrls,
  12005. rootpath: context.rootpath || '',
  12006. currentDirectory: entryPath,
  12007. entryPath,
  12008. rootFilename: filename
  12009. };
  12010. // add in a missing trailing slash
  12011. if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
  12012. rootFileInfo.rootpath += '/';
  12013. }
  12014. }
  12015. const imports = new ImportManager(this, context, rootFileInfo);
  12016. this.importManager = imports;
  12017. // TODO: allow the plugins to be just a list of paths or names
  12018. // Do an async plugin queue like lessc
  12019. if (options.plugins) {
  12020. options.plugins.forEach(function(plugin) {
  12021. let evalResult, contents;
  12022. if (plugin.fileContent) {
  12023. contents = plugin.fileContent.replace(/^\uFEFF/, '');
  12024. evalResult = pluginManager.Loader.evalPlugin(contents, context, imports, plugin.options, plugin.filename);
  12025. if (evalResult instanceof LessError) {
  12026. return callback(evalResult);
  12027. }
  12028. }
  12029. else {
  12030. pluginManager.addPlugin(plugin);
  12031. }
  12032. });
  12033. }
  12034. new Parser(context, imports, rootFileInfo)
  12035. .parse(input, function (e, root) {
  12036. if (e) { return callback(e); }
  12037. callback(null, root, imports, options);
  12038. }, options);
  12039. }
  12040. };
  12041. return parse;
  12042. }
  12043. function Render(environment, ParseTree) {
  12044. const render = function (input, options, callback) {
  12045. if (typeof options === 'function') {
  12046. callback = options;
  12047. options = copyOptions(this.options, {});
  12048. }
  12049. else {
  12050. options = copyOptions(this.options, options || {});
  12051. }
  12052. if (!callback) {
  12053. const self = this;
  12054. return new Promise(function (resolve, reject) {
  12055. render.call(self, input, options, function(err, output) {
  12056. if (err) {
  12057. reject(err);
  12058. } else {
  12059. resolve(output);
  12060. }
  12061. });
  12062. });
  12063. } else {
  12064. this.parse(input, options, function(err, root, imports, options) {
  12065. if (err) { return callback(err); }
  12066. let result;
  12067. try {
  12068. const parseTree = new ParseTree(root, imports);
  12069. result = parseTree.toCSS(options);
  12070. }
  12071. catch (err) { return callback(err); }
  12072. callback(null, result);
  12073. });
  12074. }
  12075. };
  12076. return render;
  12077. }
  12078. function parseNodeVersion(version) {
  12079. 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
  12080. if (!match) {
  12081. throw new Error('Unable to parse: ' + version);
  12082. }
  12083. var res = {
  12084. major: parseInt(match[1], 10),
  12085. minor: parseInt(match[2], 10),
  12086. patch: parseInt(match[3], 10),
  12087. pre: match[4] || '',
  12088. build: match[5] || '',
  12089. };
  12090. return res;
  12091. }
  12092. var parseNodeVersion_1 = parseNodeVersion;
  12093. function createFromEnvironment(environment, fileManagers, version = '0.0.0') {
  12094. let sourceMapOutput, sourceMapBuilder, parseTree, importManager;
  12095. environment = new Environment(environment, fileManagers);
  12096. sourceMapOutput = SourceMapOutput(environment);
  12097. sourceMapBuilder = SourceMapBuilder(sourceMapOutput, environment);
  12098. parseTree = ParseTree(sourceMapBuilder);
  12099. importManager = ImportManager(environment);
  12100. const render = Render(environment, parseTree);
  12101. const parse = Parse(environment, parseTree, importManager);
  12102. const v = parseNodeVersion_1(`v${version}`);
  12103. const initial = {
  12104. version: [v.major, v.minor, v.patch],
  12105. data,
  12106. tree,
  12107. Environment,
  12108. AbstractFileManager,
  12109. AbstractPluginLoader,
  12110. environment,
  12111. visitors,
  12112. Parser,
  12113. functions: functions(environment),
  12114. contexts,
  12115. SourceMapOutput: sourceMapOutput,
  12116. SourceMapBuilder: sourceMapBuilder,
  12117. ParseTree: parseTree,
  12118. ImportManager: importManager,
  12119. render,
  12120. parse,
  12121. LessError,
  12122. transformTree,
  12123. utils,
  12124. PluginManager: PluginManagerFactory,
  12125. logger
  12126. };
  12127. // Create a public API
  12128. const ctor = function(t) {
  12129. return function(...args) {
  12130. return new t(...args);
  12131. };
  12132. };
  12133. let t;
  12134. const api = Object.create(initial);
  12135. for (const n in initial.tree) {
  12136. /* eslint guard-for-in: 0 */
  12137. t = initial.tree[n];
  12138. if (typeof t === 'function') {
  12139. api[n.toLowerCase()] = ctor(t);
  12140. }
  12141. else {
  12142. api[n] = Object.create(null);
  12143. for (const o in t) {
  12144. /* eslint guard-for-in: 0 */
  12145. api[n][o.toLowerCase()] = ctor(t[o]);
  12146. }
  12147. }
  12148. }
  12149. /**
  12150. * Some of the functions assume a `this` context of the API object,
  12151. * which causes it to fail when wrapped for ES6 imports.
  12152. *
  12153. * An assumed `this` should be removed in the future.
  12154. */
  12155. initial.parse = initial.parse.bind(api);
  12156. initial.render = initial.render.bind(api);
  12157. return api;
  12158. }
  12159. // lessc_helper.js
  12160. //
  12161. // helper functions for lessc
  12162. const lessc_helper = {
  12163. // Stylize a string
  12164. stylize : function(str, style) {
  12165. const styles = {
  12166. 'reset' : [0, 0],
  12167. 'bold' : [1, 22],
  12168. 'inverse' : [7, 27],
  12169. 'underline' : [4, 24],
  12170. 'yellow' : [33, 39],
  12171. 'green' : [32, 39],
  12172. 'red' : [31, 39],
  12173. 'grey' : [90, 39]
  12174. };
  12175. return `\x1b[${styles[style][0]}m${str}\x1b[${styles[style][1]}m`;
  12176. },
  12177. // Print command line options
  12178. printUsage: function() {
  12179. console.log('usage: lessc [option option=parameter ...] <source> [destination]');
  12180. console.log('');
  12181. console.log('If source is set to `-\' (dash or hyphen-minus), input is read from stdin.');
  12182. console.log('');
  12183. console.log('options:');
  12184. console.log(' -h, --help Prints help (this message) and exit.');
  12185. console.log(' --include-path=PATHS Sets include paths. Separated by `:\'. `;\' also supported on windows.');
  12186. console.log(' -M, --depends Outputs a makefile import dependency list to stdout.');
  12187. console.log(' --no-color Disables colorized output.');
  12188. console.log(' --ie-compat Enables IE8 compatibility checks.');
  12189. console.log(' --js Enables inline JavaScript in less files');
  12190. console.log(' -l, --lint Syntax check only (lint).');
  12191. console.log(' -s, --silent Suppresses output of error messages.');
  12192. console.log(' --quiet Suppresses output of warnings.');
  12193. console.log(' --strict-imports (DEPRECATED) Ignores .less imports inside selector blocks. Has confusing behavior.');
  12194. console.log(' --insecure Allows imports from insecure https hosts.');
  12195. console.log(' -v, --version Prints version number and exit.');
  12196. console.log(' --verbose Be verbose.');
  12197. console.log(' --source-map[=FILENAME] Outputs a v3 sourcemap to the filename (or output filename.map).');
  12198. console.log(' --source-map-rootpath=X Adds this path onto the sourcemap filename and less file paths.');
  12199. console.log(' --source-map-basepath=X Sets sourcemap base path, defaults to current working directory.');
  12200. console.log(' --source-map-include-source Puts the less files into the map instead of referencing them.');
  12201. console.log(' --source-map-inline Puts the map (and any less files) as a base64 data uri into the output css file.');
  12202. console.log(' --source-map-url=URL Sets a custom URL to map file, for sourceMappingURL comment');
  12203. console.log(' in generated CSS file.');
  12204. console.log(' --source-map-no-annotation Excludes the sourceMappingURL comment from the output css file.');
  12205. console.log(' -rp, --rootpath=URL Sets rootpath for url rewriting in relative imports and urls');
  12206. console.log(' Works with or without the relative-urls option.');
  12207. console.log(' -ru=, --rewrite-urls= Rewrites URLs to make them relative to the base less file.');
  12208. console.log(' all|local|off \'all\' rewrites all URLs, \'local\' just those starting with a \'.\'');
  12209. console.log('');
  12210. console.log(' -m=, --math=');
  12211. console.log(' always Less will eagerly perform math operations always.');
  12212. console.log(' parens-division Math performed except for division (/) operator');
  12213. console.log(' parens | strict Math only performed inside parentheses');
  12214. console.log(' strict-legacy Parens required in very strict terms (legacy --strict-math)');
  12215. console.log('');
  12216. console.log(' -su=on|off Allows mixed units, e.g. 1px+1em or 1px*1px which have units');
  12217. console.log(' --strict-units=on|off that cannot be represented.');
  12218. console.log(' --global-var=\'VAR=VALUE\' Defines a variable that can be referenced by the file.');
  12219. console.log(' --modify-var=\'VAR=VALUE\' Modifies a variable already declared in the file.');
  12220. console.log(' --url-args=\'QUERYSTRING\' Adds params into url tokens (e.g. 42, cb=42 or \'a=1&b=2\')');
  12221. console.log(' --plugin=PLUGIN=OPTIONS Loads a plugin. You can also omit the --plugin= if the plugin begins');
  12222. console.log(' less-plugin. E.g. the clean css plugin is called less-plugin-clean-css');
  12223. console.log(' once installed (npm install less-plugin-clean-css), use either with');
  12224. console.log(' --plugin=less-plugin-clean-css or just --clean-css');
  12225. console.log(' specify options afterwards e.g. --plugin=less-plugin-clean-css="advanced"');
  12226. console.log(' or --clean-css="advanced"');
  12227. console.log(' --disable-plugin-rule Disallow @plugin statements');
  12228. console.log('');
  12229. console.log(' --quiet-deprecations Suppress deprecation warnings only (keeps other warnings).');
  12230. console.log('');
  12231. console.log('-------------------------- Deprecated ----------------');
  12232. console.log(' -sm=on|off Legacy parens-only math. Use --math');
  12233. console.log(' --strict-math=on|off ');
  12234. console.log('');
  12235. console.log(' --line-numbers=TYPE (DEPRECATED) Outputs filename and line numbers.');
  12236. console.log(' TYPE can be either \'comments\', \'mediaquery\', or \'all\'.');
  12237. console.log(' The entire dumpLineNumbers option is deprecated.');
  12238. console.log(' Use sourcemaps (--source-map) instead.');
  12239. console.log(' All modes will be removed in a future version.');
  12240. console.log(' Note: \'mediaquery\' and \'all\' modes generate @media -sass-debug-info');
  12241. console.log(' which had short-lived usage and is no longer recommended.');
  12242. console.log(' -x, --compress Compresses output by removing some whitespaces.');
  12243. console.log(' We recommend you use a dedicated minifer like less-plugin-clean-css');
  12244. console.log('');
  12245. console.log('Report bugs to: http://github.com/less/less.js/issues');
  12246. console.log('Home page: <http://lesscss.org/>');
  12247. }
  12248. };
  12249. const require$2 = createRequire();
  12250. /**
  12251. * Node Plugin Loader
  12252. */
  12253. const PluginLoader = function(less) {
  12254. this.less = less;
  12255. this.require = prefix => {
  12256. prefix = path__default["default"].dirname(prefix);
  12257. return id => {
  12258. const str = id.slice(0, 2);
  12259. if (str === '..' || str === './') {
  12260. return require$2(path__default["default"].join(prefix, id));
  12261. }
  12262. else {
  12263. return require$2(id);
  12264. }
  12265. };
  12266. };
  12267. };
  12268. PluginLoader.prototype = Object.assign(new AbstractPluginLoader(), {
  12269. loadPlugin(filename, basePath, context, environment, fileManager) {
  12270. const prefix = filename.slice(0, 1);
  12271. const explicit = prefix === '.' || prefix === '/' || filename.slice(-3).toLowerCase() === '.js';
  12272. if (!explicit) {
  12273. context.prefixes = ['less-plugin-', ''];
  12274. }
  12275. if (context.syncImport) {
  12276. return fileManager.loadFileSync(filename, basePath, context, environment);
  12277. }
  12278. return new Promise((fulfill, reject) => {
  12279. fileManager.loadFile(filename, basePath, context, environment).then(
  12280. data => {
  12281. try {
  12282. fulfill(data);
  12283. }
  12284. catch (e) {
  12285. console.log(e);
  12286. reject(e);
  12287. }
  12288. }
  12289. ).catch(err => {
  12290. reject(err);
  12291. });
  12292. });
  12293. },
  12294. loadPluginSync(filename, basePath, context, environment, fileManager) {
  12295. context.syncImport = true;
  12296. return this.loadPlugin(filename, basePath, context, environment, fileManager);
  12297. }
  12298. });
  12299. // Export a new default each time
  12300. function defaultOptions() {
  12301. return {
  12302. /* Inline Javascript - @plugin still allowed */
  12303. javascriptEnabled: false,
  12304. /* Outputs a makefile import dependency list to stdout. */
  12305. depends: false,
  12306. /* (DEPRECATED) Compress using less built-in compression.
  12307. * This does an okay job but does not utilise all the tricks of
  12308. * dedicated css compression. */
  12309. compress: false,
  12310. /* Runs the less parser and just reports errors without any output. */
  12311. lint: false,
  12312. /* Sets available include paths.
  12313. * If the file in an @import rule does not exist at that exact location,
  12314. * less will look for it at the location(s) passed to this option.
  12315. * You might use this for instance to specify a path to a library which
  12316. * you want to be referenced simply and relatively in the less files. */
  12317. paths: [],
  12318. /* color output in the terminal */
  12319. color: true,
  12320. /**
  12321. * @deprecated This option has confusing behavior and may be removed in a future version.
  12322. *
  12323. * When true, prevents @import statements for .less files from being evaluated inside
  12324. * selector blocks (rulesets). The imports are silently ignored and not output.
  12325. *
  12326. * Behavior:
  12327. * - @import at root level: Always processed
  12328. * - @import inside @-rules (@media, @supports, etc.): Processed (these are not selector blocks)
  12329. * - @import inside selector blocks (.class, #id, etc.): NOT processed (silently ignored)
  12330. *
  12331. * When false (default): All @import statements are processed regardless of context.
  12332. *
  12333. * Note: Despite the name "strict", this option does NOT throw an error when imports
  12334. * are used in selector blocks - it silently ignores them. This is confusing
  12335. * behavior that may catch users off guard.
  12336. *
  12337. * Note: Only affects .less file imports. CSS imports (url(...) or .css files) are
  12338. * always output as CSS @import statements regardless of this setting.
  12339. *
  12340. * @see https://github.com/less/less.js/issues/656
  12341. */
  12342. strictImports: false,
  12343. /* Allow Imports from Insecure HTTPS Hosts */
  12344. insecure: false,
  12345. /* Allows you to add a path to every generated import and url in your css.
  12346. * This does not affect less import statements that are processed, just ones
  12347. * that are left in the output css. */
  12348. rootpath: '',
  12349. /* By default URLs are kept as-is, so if you import a file in a sub-directory
  12350. * that references an image, exactly the same URL will be output in the css.
  12351. * This option allows you to re-write URL's in imported files so that the
  12352. * URL is always relative to the base imported file */
  12353. rewriteUrls: false,
  12354. /* How to process math
  12355. * 0 always - eagerly try to solve all operations
  12356. * 1 parens-division - require parens for division "/"
  12357. * 2 parens | strict - require parens for all operations
  12358. * 3 strict-legacy - legacy strict behavior (super-strict)
  12359. */
  12360. math: 1,
  12361. /* Without this option, less attempts to guess at the output unit when it does maths. */
  12362. strictUnits: false,
  12363. /* Effectively the declaration is put at the top of your base Less file,
  12364. * meaning it can be used but it also can be overridden if this variable
  12365. * is defined in the file. */
  12366. globalVars: null,
  12367. /* As opposed to the global variable option, this puts the declaration at the
  12368. * end of your base file, meaning it will override anything defined in your Less file. */
  12369. modifyVars: null,
  12370. /* This option allows you to specify a argument to go on to every URL. */
  12371. urlArgs: ''
  12372. }
  12373. }
  12374. const require$1 = createRequire();
  12375. var imageSize = environment => {
  12376. function imageSize(functionContext, filePathNode) {
  12377. let filePath = filePathNode.value;
  12378. const currentFileInfo = functionContext.currentFileInfo;
  12379. const currentDirectory = currentFileInfo.rewriteUrls ?
  12380. currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  12381. const fragmentStart = filePath.indexOf('#');
  12382. if (fragmentStart !== -1) {
  12383. filePath = filePath.slice(0, fragmentStart);
  12384. }
  12385. const fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);
  12386. if (!fileManager) {
  12387. throw {
  12388. type: 'File',
  12389. message: `Can not set up FileManager for ${filePathNode}`
  12390. };
  12391. }
  12392. const fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);
  12393. if (fileSync.error) {
  12394. throw fileSync.error;
  12395. }
  12396. const sizeOf = require$1('image-size');
  12397. return sizeOf ? sizeOf(fileSync.filename) : {width: 0, height: 0};
  12398. }
  12399. const imageFunctions = {
  12400. 'image-size': function(filePathNode) {
  12401. const size = imageSize(this, filePathNode);
  12402. return new Expression([
  12403. new Dimension(size.width, 'px'),
  12404. new Dimension(size.height, 'px')
  12405. ]);
  12406. },
  12407. 'image-width': function(filePathNode) {
  12408. const size = imageSize(this, filePathNode);
  12409. return new Dimension(size.width, 'px');
  12410. },
  12411. 'image-height': function(filePathNode) {
  12412. const size = imageSize(this, filePathNode);
  12413. return new Dimension(size.height, 'px');
  12414. }
  12415. };
  12416. functionRegistry.addMultiple(imageFunctions);
  12417. };
  12418. createRequire();
  12419. const version = "4.6.4";
  12420. const less = createFromEnvironment(environment, [new FileManager(), new UrlFileManager()], version);
  12421. // allow people to create less with their own environment
  12422. less.createFromEnvironment = createFromEnvironment;
  12423. less.lesscHelper = lessc_helper;
  12424. less.PluginLoader = PluginLoader;
  12425. less.fs = fs$1;
  12426. less.FileManager = FileManager;
  12427. less.UrlFileManager = UrlFileManager;
  12428. // Set up options
  12429. less.options = defaultOptions();
  12430. // provide image-size functionality
  12431. imageSize(less.environment);
  12432. module.exports = less;