styled-components-primitives.esm.js 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247
  1. import reactPrimitives from 'react-primitives';
  2. import transformDeclPairs from 'css-to-react-native';
  3. import { isElement, isValidElementType } from 'react-is';
  4. import React, { useContext, useMemo, createElement, Component } from 'react';
  5. import 'shallowequal';
  6. import Stylis from '@emotion/stylis';
  7. import unitless from '@emotion/unitless';
  8. import supportsColor from 'supports-color';
  9. import hoist from 'hoist-non-react-statics';
  10. //
  11. /* eslint-disable no-bitwise */
  12. var AD_REPLACER_R = /(a)(d)/gi;
  13. /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised
  14. * counterparts */
  15. var charsLength = 52;
  16. /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */
  17. var getAlphabeticChar = function getAlphabeticChar(code) {
  18. return String.fromCharCode(code + (code > 25 ? 39 : 97));
  19. };
  20. /* input a number, usually a hash and convert it to base-52 */
  21. function generateAlphabeticName(code) {
  22. var name = '';
  23. var x;
  24. /* get a char and divide by alphabet-length */
  25. for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) {
  26. name = getAlphabeticChar(x % charsLength) + name;
  27. }
  28. return (getAlphabeticChar(x % charsLength) + name).replace(AD_REPLACER_R, '$1-$2');
  29. }
  30. //
  31. /* eslint-disable */
  32. var SEED = 5381; // When we have separate strings it's useful to run a progressive
  33. // version of djb2 where we pretend that we're still looping over
  34. // the same string
  35. var phash = function phash(h, x) {
  36. var i = x.length;
  37. while (i) {
  38. h = h * 33 ^ x.charCodeAt(--i);
  39. }
  40. return h;
  41. }; // This is a djb2 hashing function
  42. var hash = function hash(x) {
  43. return phash(SEED, x);
  44. };
  45. //
  46. var generateComponentId = (function (str) {
  47. return generateAlphabeticName(hash(str) >>> 0);
  48. });
  49. //
  50. function getComponentName(target) {
  51. return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe
  52. target.displayName || // $FlowFixMe
  53. target.name || 'Component';
  54. }
  55. //
  56. function isFunction(test) {
  57. return typeof test === 'function';
  58. }
  59. //
  60. function isStatelessFunction(test) {
  61. return typeof test === 'function' && !(test.prototype && test.prototype.isReactComponent);
  62. }
  63. //
  64. var isPlainObject = (function (x) {
  65. return typeof x === 'object' && x.constructor === Object;
  66. });
  67. //
  68. function isStyledComponent(target) {
  69. return target && typeof target.styledComponentId === 'string';
  70. }
  71. function _defineProperties(target, props) {
  72. for (var i = 0; i < props.length; i++) {
  73. var descriptor = props[i];
  74. descriptor.enumerable = descriptor.enumerable || false;
  75. descriptor.configurable = true;
  76. if ("value" in descriptor) descriptor.writable = true;
  77. Object.defineProperty(target, descriptor.key, descriptor);
  78. }
  79. }
  80. function _createClass(Constructor, protoProps, staticProps) {
  81. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  82. if (staticProps) _defineProperties(Constructor, staticProps);
  83. return Constructor;
  84. }
  85. function _extends() {
  86. _extends = Object.assign || function (target) {
  87. for (var i = 1; i < arguments.length; i++) {
  88. var source = arguments[i];
  89. for (var key in source) {
  90. if (Object.prototype.hasOwnProperty.call(source, key)) {
  91. target[key] = source[key];
  92. }
  93. }
  94. }
  95. return target;
  96. };
  97. return _extends.apply(this, arguments);
  98. }
  99. function _inheritsLoose(subClass, superClass) {
  100. subClass.prototype = Object.create(superClass.prototype);
  101. subClass.prototype.constructor = subClass;
  102. subClass.__proto__ = superClass;
  103. }
  104. function _objectWithoutPropertiesLoose(source, excluded) {
  105. if (source == null) return {};
  106. var target = {};
  107. var sourceKeys = Object.keys(source);
  108. var key, i;
  109. for (i = 0; i < sourceKeys.length; i++) {
  110. key = sourceKeys[i];
  111. if (excluded.indexOf(key) >= 0) continue;
  112. target[key] = source[key];
  113. }
  114. return target;
  115. }
  116. //
  117. var SC_ATTR = typeof process !== 'undefined' && (process.env.REACT_APP_SC_ATTR || process.env.SC_ATTR) || 'data-styled';
  118. var SC_ATTR_ACTIVE = 'active';
  119. var SC_ATTR_VERSION = 'data-styled-version';
  120. var SC_VERSION = "5.0.1";
  121. var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window;
  122. var DISABLE_SPEEDY = typeof SC_DISABLE_SPEEDY === 'boolean' && SC_DISABLE_SPEEDY || typeof process !== 'undefined' && (process.env.REACT_APP_SC_DISABLE_SPEEDY || process.env.SC_DISABLE_SPEEDY) || process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles
  123. //
  124. /* eslint-disable camelcase, no-undef */
  125. var getNonce = function getNonce() {
  126. return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null;
  127. };
  128. var errorMap = {
  129. "1": "Cannot create styled-component for component: %s.\n\n",
  130. "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",
  131. "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",
  132. "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",
  133. "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",
  134. "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",
  135. "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n",
  136. "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n",
  137. "9": "Missing document `<head>`\n\n",
  138. "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",
  139. "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n",
  140. "12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css\n\n",
  141. "13": "%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n\n",
  142. "14": "ThemeProvider: \"theme\" prop is required.\n\n",
  143. "15": "A stylis plugin has been supplied that is not named. We need a name for each plugin to be able to prevent styling collisions between different stylis configurations within the same app. Before you pass your plugin to `<StyleSheetManager stylisPlugins={[]}>`, please make sure each plugin is uniquely-named, e.g.\n\n```js\nObject.defineProperty(importedPlugin, 'name', { value: 'some-unique-name' });\n```\n\n",
  144. "16": "Reached the limit of how many styled components may be created at group %s.\nYou may only create up to 1,073,741,824 components. If you're creating components dynamically,\nas for instance in your render method then you may be running into this limitation.\n\n",
  145. "17": "CSSStyleSheet could not be found on HTMLStyleElement.\nHas styled-components' style tag been unmounted or altered by another script?\n"
  146. };
  147. //
  148. var ERRORS = process.env.NODE_ENV !== 'production' ? errorMap : {};
  149. /**
  150. * super basic version of sprintf
  151. */
  152. function format() {
  153. var a = arguments.length <= 0 ? undefined : arguments[0];
  154. var b = [];
  155. for (var c = 1, len = arguments.length; c < len; c += 1) {
  156. b.push(c < 0 || arguments.length <= c ? undefined : arguments[c]);
  157. }
  158. b.forEach(function (d) {
  159. a = a.replace(/%[a-z]/, d);
  160. });
  161. return a;
  162. }
  163. /**
  164. * Create an error file out of errors.md for development and a simple web link to the full errors
  165. * in production mode.
  166. */
  167. function throwStyledComponentsError(code) {
  168. for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  169. interpolations[_key - 1] = arguments[_key];
  170. }
  171. if (process.env.NODE_ENV === 'production') {
  172. throw new Error("An error occurred. See https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/utils/errors.md#" + code + " for more information." + (interpolations.length > 0 ? " Additional arguments: " + interpolations.join(', ') : ''));
  173. } else {
  174. throw new Error(format.apply(void 0, [ERRORS[code]].concat(interpolations)).trim());
  175. }
  176. }
  177. //
  178. var ELEMENT_TYPE = 1;
  179. /* Node.ELEMENT_TYPE */
  180. /** Find last style element if any inside target */
  181. var findLastStyleTag = function findLastStyleTag(target) {
  182. var childNodes = target.childNodes;
  183. for (var i = childNodes.length; i >= 0; i--) {
  184. var child = childNodes[i];
  185. if (child && child.nodeType === ELEMENT_TYPE && child.hasAttribute(SC_ATTR)) {
  186. return child;
  187. }
  188. }
  189. return undefined;
  190. };
  191. /** Create a style element inside `target` or <head> after the last */
  192. var makeStyleTag = function makeStyleTag(target) {
  193. var head = document.head;
  194. var parent = target || head;
  195. var style = document.createElement('style');
  196. var prevStyle = findLastStyleTag(parent);
  197. var nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null;
  198. style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE);
  199. style.setAttribute(SC_ATTR_VERSION, SC_VERSION);
  200. var nonce = getNonce();
  201. if (nonce) style.setAttribute('nonce', nonce);
  202. parent.insertBefore(style, nextSibling);
  203. return style;
  204. };
  205. /** Get the CSSStyleSheet instance for a given style element */
  206. var getSheet = function getSheet(tag) {
  207. if (tag.sheet) {
  208. return tag.sheet;
  209. } // Avoid Firefox quirk where the style element might not have a sheet property
  210. var _document = document,
  211. styleSheets = _document.styleSheets;
  212. for (var i = 0, l = styleSheets.length; i < l; i++) {
  213. var sheet = styleSheets[i];
  214. if (sheet.ownerNode === tag) {
  215. return sheet;
  216. }
  217. }
  218. throwStyledComponentsError(17);
  219. return undefined;
  220. };
  221. //
  222. /** Create a CSSStyleSheet-like tag depending on the environment */
  223. var makeTag = function makeTag(_ref) {
  224. var isServer = _ref.isServer,
  225. useCSSOMInjection = _ref.useCSSOMInjection,
  226. target = _ref.target;
  227. if (isServer) {
  228. return new VirtualTag(target);
  229. } else if (useCSSOMInjection) {
  230. return new CSSOMTag(target);
  231. } else {
  232. return new TextTag(target);
  233. }
  234. };
  235. var CSSOMTag =
  236. /*#__PURE__*/
  237. function () {
  238. function CSSOMTag(target) {
  239. var element = this.element = makeStyleTag(target); // Avoid Edge bug where empty style elements don't create sheets
  240. element.appendChild(document.createTextNode(''));
  241. this.sheet = getSheet(element);
  242. this.length = 0;
  243. }
  244. var _proto = CSSOMTag.prototype;
  245. _proto.insertRule = function insertRule(index, rule) {
  246. try {
  247. this.sheet.insertRule(rule, index);
  248. this.length++;
  249. return true;
  250. } catch (_error) {
  251. return false;
  252. }
  253. };
  254. _proto.deleteRule = function deleteRule(index) {
  255. this.sheet.deleteRule(index);
  256. this.length--;
  257. };
  258. _proto.getRule = function getRule(index) {
  259. var rule = this.sheet.cssRules[index]; // Avoid IE11 quirk where cssText is inaccessible on some invalid rules
  260. if (rule !== undefined && typeof rule.cssText === 'string') {
  261. return rule.cssText;
  262. } else {
  263. return '';
  264. }
  265. };
  266. return CSSOMTag;
  267. }();
  268. /** A Tag that emulates the CSSStyleSheet API but uses text nodes */
  269. var TextTag =
  270. /*#__PURE__*/
  271. function () {
  272. function TextTag(target) {
  273. var element = this.element = makeStyleTag(target);
  274. this.nodes = element.childNodes;
  275. this.length = 0;
  276. }
  277. var _proto2 = TextTag.prototype;
  278. _proto2.insertRule = function insertRule(index, rule) {
  279. if (index <= this.length && index >= 0) {
  280. var node = document.createTextNode(rule);
  281. var refNode = this.nodes[index];
  282. this.element.insertBefore(node, refNode || null);
  283. this.length++;
  284. return true;
  285. } else {
  286. return false;
  287. }
  288. };
  289. _proto2.deleteRule = function deleteRule(index) {
  290. this.element.removeChild(this.nodes[index]);
  291. this.length--;
  292. };
  293. _proto2.getRule = function getRule(index) {
  294. if (index < this.length) {
  295. return this.nodes[index].textContent;
  296. } else {
  297. return '';
  298. }
  299. };
  300. return TextTag;
  301. }();
  302. /** A completely virtual (server-side) Tag that doesn't manipulate the DOM */
  303. var VirtualTag =
  304. /*#__PURE__*/
  305. function () {
  306. function VirtualTag(_target) {
  307. this.rules = [];
  308. this.length = 0;
  309. }
  310. var _proto3 = VirtualTag.prototype;
  311. _proto3.insertRule = function insertRule(index, rule) {
  312. if (index <= this.length) {
  313. this.rules.splice(index, 0, rule);
  314. this.length++;
  315. return true;
  316. } else {
  317. return false;
  318. }
  319. };
  320. _proto3.deleteRule = function deleteRule(index) {
  321. this.rules.splice(index, 1);
  322. this.length--;
  323. };
  324. _proto3.getRule = function getRule(index) {
  325. if (index < this.length) {
  326. return this.rules[index];
  327. } else {
  328. return '';
  329. }
  330. };
  331. return VirtualTag;
  332. }();
  333. //
  334. /** Create a GroupedTag with an underlying Tag implementation */
  335. var makeGroupedTag = function makeGroupedTag(tag) {
  336. return new DefaultGroupedTag(tag);
  337. };
  338. var BASE_SIZE = 1 << 9;
  339. var DefaultGroupedTag =
  340. /*#__PURE__*/
  341. function () {
  342. function DefaultGroupedTag(tag) {
  343. this.groupSizes = new Uint32Array(BASE_SIZE);
  344. this.length = BASE_SIZE;
  345. this.tag = tag;
  346. }
  347. var _proto = DefaultGroupedTag.prototype;
  348. _proto.indexOfGroup = function indexOfGroup(group) {
  349. var index = 0;
  350. for (var i = 0; i < group; i++) {
  351. index += this.groupSizes[i];
  352. }
  353. return index;
  354. };
  355. _proto.insertRules = function insertRules(group, rules) {
  356. if (group >= this.groupSizes.length) {
  357. var oldBuffer = this.groupSizes;
  358. var oldSize = oldBuffer.length;
  359. var newSize = oldSize;
  360. while (group >= newSize) {
  361. newSize <<= 1;
  362. if (newSize < 0) {
  363. throwStyledComponentsError(16, "" + group);
  364. }
  365. }
  366. this.groupSizes = new Uint32Array(newSize);
  367. this.groupSizes.set(oldBuffer);
  368. this.length = newSize;
  369. for (var i = oldSize; i < newSize; i++) {
  370. this.groupSizes[i] = 0;
  371. }
  372. }
  373. var ruleIndex = this.indexOfGroup(group + 1);
  374. for (var _i = 0, l = rules.length; _i < l; _i++) {
  375. if (this.tag.insertRule(ruleIndex, rules[_i])) {
  376. this.groupSizes[group]++;
  377. ruleIndex++;
  378. }
  379. }
  380. };
  381. _proto.clearGroup = function clearGroup(group) {
  382. if (group < this.length) {
  383. var length = this.groupSizes[group];
  384. var startIndex = this.indexOfGroup(group);
  385. var endIndex = startIndex + length;
  386. this.groupSizes[group] = 0;
  387. for (var i = startIndex; i < endIndex; i++) {
  388. this.tag.deleteRule(startIndex);
  389. }
  390. }
  391. };
  392. _proto.getGroup = function getGroup(group) {
  393. var css = '';
  394. if (group >= this.length || this.groupSizes[group] === 0) {
  395. return css;
  396. }
  397. var length = this.groupSizes[group];
  398. var startIndex = this.indexOfGroup(group);
  399. var endIndex = startIndex + length;
  400. for (var i = startIndex; i < endIndex; i++) {
  401. css += this.tag.getRule(i) + "\n";
  402. }
  403. return css;
  404. };
  405. return DefaultGroupedTag;
  406. }();
  407. //
  408. var MAX_SMI = 1 << 31 - 1;
  409. var groupIDRegister = new Map();
  410. var reverseRegister = new Map();
  411. var nextFreeGroup = 1;
  412. var getGroupForId = function getGroupForId(id) {
  413. if (groupIDRegister.has(id)) {
  414. return groupIDRegister.get(id);
  415. }
  416. var group = nextFreeGroup++;
  417. if (process.env.NODE_ENV !== 'production' && ((group | 0) < 0 || group > MAX_SMI)) {
  418. throwStyledComponentsError(16, "" + group);
  419. }
  420. groupIDRegister.set(id, group);
  421. reverseRegister.set(group, id);
  422. return group;
  423. };
  424. var getIdForGroup = function getIdForGroup(group) {
  425. return reverseRegister.get(group);
  426. };
  427. var setGroupForId = function setGroupForId(id, group) {
  428. if (group >= nextFreeGroup) {
  429. nextFreeGroup = group + 1;
  430. }
  431. groupIDRegister.set(id, group);
  432. reverseRegister.set(group, id);
  433. };
  434. //
  435. var SELECTOR = "style[" + SC_ATTR + "][" + SC_ATTR_VERSION + "=\"" + SC_VERSION + "\"]";
  436. var RULE_RE = /(?:\s*)?(.*?){((?:{[^}]*}|(?!{).*?)*)}/g;
  437. var MARKER_RE = new RegExp("^" + SC_ATTR + "\\.g(\\d+)\\[id=\"([\\w\\d-]+)\"\\]");
  438. var outputSheet = function outputSheet(sheet) {
  439. var tag = sheet.getTag();
  440. var length = tag.length;
  441. var css = '';
  442. for (var group = 0; group < length; group++) {
  443. var id = getIdForGroup(group);
  444. if (id === undefined) continue;
  445. var names = sheet.names.get(id);
  446. var rules = tag.getGroup(group);
  447. if (names === undefined || rules.length === 0) continue;
  448. var selector = SC_ATTR + ".g" + group + "[id=\"" + id + "\"]";
  449. var content = '';
  450. if (names !== undefined) {
  451. names.forEach(function (name) {
  452. if (name.length > 0) {
  453. content += name + ",";
  454. }
  455. });
  456. } // NOTE: It's easier to collect rules and have the marker
  457. // after the actual rules to simplify the rehydration
  458. css += "" + rules + selector + "{content:\"" + content + "\"}\n";
  459. }
  460. return css;
  461. };
  462. var rehydrateNamesFromContent = function rehydrateNamesFromContent(sheet, id, content) {
  463. var names = content.split(',');
  464. var name;
  465. for (var i = 0, l = names.length; i < l; i++) {
  466. // eslint-disable-next-line
  467. if (name = names[i]) {
  468. sheet.registerName(id, name);
  469. }
  470. }
  471. };
  472. var rehydrateSheetFromTag = function rehydrateSheetFromTag(sheet, style) {
  473. var rawHTML = style.innerHTML;
  474. var rules = [];
  475. var parts; // parts = [match, selector, content]
  476. // eslint-disable-next-line no-cond-assign
  477. while (parts = RULE_RE.exec(rawHTML)) {
  478. var marker = parts[1].match(MARKER_RE);
  479. if (marker) {
  480. var group = parseInt(marker[1], 10) | 0;
  481. var id = marker[2];
  482. if (group !== 0) {
  483. // Rehydrate componentId to group index mapping
  484. setGroupForId(id, group); // Rehydrate names and rules
  485. // looks like: data-styled.g11[id="idA"]{content:"nameA,"}
  486. rehydrateNamesFromContent(sheet, id, parts[2].split('"')[1]);
  487. sheet.getTag().insertRules(group, rules);
  488. }
  489. rules.length = 0;
  490. } else {
  491. rules.push(parts[0].trim());
  492. }
  493. }
  494. };
  495. var rehydrateSheet = function rehydrateSheet(sheet) {
  496. var nodes = document.querySelectorAll(SELECTOR);
  497. for (var i = 0, l = nodes.length; i < l; i++) {
  498. var node = nodes[i];
  499. if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) {
  500. rehydrateSheetFromTag(sheet, node);
  501. if (node.parentNode) {
  502. node.parentNode.removeChild(node);
  503. }
  504. }
  505. }
  506. };
  507. var SHOULD_REHYDRATE = IS_BROWSER;
  508. var defaultOptions = {
  509. isServer: !IS_BROWSER,
  510. useCSSOMInjection: !DISABLE_SPEEDY
  511. };
  512. /** Contains the main stylesheet logic for stringification and caching */
  513. var StyleSheet =
  514. /*#__PURE__*/
  515. function () {
  516. /** Register a group ID to give it an index */
  517. StyleSheet.registerId = function registerId(id) {
  518. return getGroupForId(id);
  519. };
  520. function StyleSheet(options, globalStyles, names) {
  521. if (options === void 0) {
  522. options = defaultOptions;
  523. }
  524. if (globalStyles === void 0) {
  525. globalStyles = {};
  526. }
  527. this.options = _extends({}, defaultOptions, {}, options);
  528. this.gs = globalStyles;
  529. this.names = new Map(names); // We rehydrate only once and use the sheet that is created first
  530. if (!this.options.isServer && IS_BROWSER && SHOULD_REHYDRATE) {
  531. SHOULD_REHYDRATE = false;
  532. rehydrateSheet(this);
  533. }
  534. }
  535. var _proto = StyleSheet.prototype;
  536. _proto.reconstructWithOptions = function reconstructWithOptions(options) {
  537. return new StyleSheet(_extends({}, this.options, {}, options), this.gs, this.names);
  538. };
  539. _proto.allocateGSInstance = function allocateGSInstance(id) {
  540. return this.gs[id] = (this.gs[id] || 0) + 1;
  541. }
  542. /** Lazily initialises a GroupedTag for when it's actually needed */
  543. ;
  544. _proto.getTag = function getTag() {
  545. return this.tag || (this.tag = makeGroupedTag(makeTag(this.options)));
  546. }
  547. /** Check whether a name is known for caching */
  548. ;
  549. _proto.hasNameForId = function hasNameForId(id, name) {
  550. return this.names.has(id) && this.names.get(id).has(name);
  551. }
  552. /** Mark a group's name as known for caching */
  553. ;
  554. _proto.registerName = function registerName(id, name) {
  555. getGroupForId(id);
  556. if (!this.names.has(id)) {
  557. var groupNames = new Set();
  558. groupNames.add(name);
  559. this.names.set(id, groupNames);
  560. } else {
  561. this.names.get(id).add(name);
  562. }
  563. }
  564. /** Insert new rules which also marks the name as known */
  565. ;
  566. _proto.insertRules = function insertRules(id, name, rules) {
  567. this.registerName(id, name);
  568. this.getTag().insertRules(getGroupForId(id), rules);
  569. }
  570. /** Clears all cached names for a given group ID */
  571. ;
  572. _proto.clearNames = function clearNames(id) {
  573. if (this.names.has(id)) {
  574. this.names.get(id).clear();
  575. }
  576. }
  577. /** Clears all rules for a given group ID */
  578. ;
  579. _proto.clearRules = function clearRules(id) {
  580. this.getTag().clearGroup(getGroupForId(id));
  581. this.clearNames(id);
  582. }
  583. /** Clears the entire tag which deletes all rules but not its names */
  584. ;
  585. _proto.clearTag = function clearTag() {
  586. // NOTE: This does not clear the names, since it's only used during SSR
  587. // so that we can continuously output only new rules
  588. this.tag = undefined;
  589. }
  590. /** Outputs the current sheet as a CSS string with markers for SSR */
  591. ;
  592. _proto.toString = function toString() {
  593. return outputSheet(this);
  594. };
  595. return StyleSheet;
  596. }();
  597. //
  598. var EMPTY_ARRAY = Object.freeze([]);
  599. var EMPTY_OBJECT = Object.freeze({});
  600. /**
  601. * MIT License
  602. *
  603. * Copyright (c) 2016 Sultan Tarimo
  604. *
  605. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  606. * this software and associated documentation files (the "Software"),
  607. * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  608. * sell copies of the Software and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  609. *
  610. * The above copyright notice and this permission notice shall be included in all
  611. * copies or substantial portions of the Software.
  612. *
  613. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  614. * OR IMPLIED INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  615. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  616. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  617. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
  618. * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  619. */
  620. /* eslint-disable */
  621. function insertRulePlugin (insertRule) {
  622. var delimiter = '/*|*/';
  623. var needle = delimiter + "}";
  624. function toSheet(block) {
  625. if (block) {
  626. try {
  627. insertRule(block + "}");
  628. } catch (e) {}
  629. }
  630. }
  631. return function ruleSheet(context, content, selectors, parents, line, column, length, ns, depth, at) {
  632. switch (context) {
  633. // property
  634. case 1:
  635. // @import
  636. if (depth === 0 && content.charCodeAt(0) === 64) return insertRule(content + ";"), '';
  637. break;
  638. // selector
  639. case 2:
  640. if (ns === 0) return content + delimiter;
  641. break;
  642. // at-rule
  643. case 3:
  644. switch (ns) {
  645. // @font-face, @page
  646. case 102:
  647. case 112:
  648. return insertRule(selectors[0] + content), '';
  649. default:
  650. return content + (at === 0 ? delimiter : '');
  651. }
  652. case -2:
  653. content.split(needle).forEach(toSheet);
  654. }
  655. };
  656. }
  657. var COMMENT_REGEX = /^\s*\/\/.*$/gm;
  658. function createStylisInstance(_temp) {
  659. var _ref = _temp === void 0 ? EMPTY_OBJECT : _temp,
  660. _ref$options = _ref.options,
  661. options = _ref$options === void 0 ? EMPTY_OBJECT : _ref$options,
  662. _ref$plugins = _ref.plugins,
  663. plugins = _ref$plugins === void 0 ? EMPTY_ARRAY : _ref$plugins;
  664. var stylis = new Stylis(options); // Wrap `insertRulePlugin to build a list of rules,
  665. // and then make our own plugin to return the rules. This
  666. // makes it easier to hook into the existing SSR architecture
  667. var parsingRules = []; // eslint-disable-next-line consistent-return
  668. var returnRulesPlugin = function returnRulesPlugin(context) {
  669. if (context === -2) {
  670. var parsedRules = parsingRules;
  671. parsingRules = [];
  672. return parsedRules;
  673. }
  674. };
  675. var parseRulesPlugin = insertRulePlugin(function (rule) {
  676. parsingRules.push(rule);
  677. });
  678. var _componentId;
  679. var _selector;
  680. var _selectorRegexp;
  681. var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) {
  682. if ( // the first self-ref is always untouched
  683. offset > 0 && // there should be at least two self-refs to do a replacement (.b > .b)
  684. string.slice(0, offset).indexOf(_selector) !== -1 && // no consecutive self refs (.b.b); that is a precedence boost and treated differently
  685. string.slice(offset - _selector.length, offset) !== _selector) {
  686. return "." + _componentId;
  687. }
  688. return match;
  689. };
  690. /**
  691. * When writing a style like
  692. *
  693. * & + & {
  694. * color: red;
  695. * }
  696. *
  697. * The second ampersand should be a reference to the static component class. stylis
  698. * has no knowledge of static class so we have to intelligently replace the base selector.
  699. *
  700. * https://github.com/thysultan/stylis.js#plugins <- more info about the context phase values
  701. * "2" means this plugin is taking effect at the very end after all other processing is complete
  702. */
  703. var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) {
  704. if (context === 2 && selectors.length && selectors[0].lastIndexOf(_selector) > 0) {
  705. // eslint-disable-next-line no-param-reassign
  706. selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer);
  707. }
  708. };
  709. stylis.use([].concat(plugins, [selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]));
  710. function stringifyRules(css, selector, prefix, componentId) {
  711. if (componentId === void 0) {
  712. componentId = '&';
  713. }
  714. var flatCSS = css.replace(COMMENT_REGEX, '');
  715. var cssStr = selector && prefix ? prefix + " " + selector + " { " + flatCSS + " }" : flatCSS; // stylis has no concept of state to be passed to plugins
  716. // but since JS is single=threaded, we can rely on that to ensure
  717. // these properties stay in sync with the current stylis run
  718. _componentId = componentId;
  719. _selector = selector;
  720. _selectorRegexp = new RegExp("\\" + _selector + "\\b", 'g');
  721. return stylis(prefix || !selector ? '' : selector, cssStr);
  722. }
  723. stringifyRules.hash = plugins.length ? plugins.reduce(function (acc, plugin) {
  724. if (!plugin.name) {
  725. throwStyledComponentsError(15);
  726. }
  727. return phash(acc, plugin.name);
  728. }, SEED).toString() : '';
  729. return stringifyRules;
  730. }
  731. //
  732. var StyleSheetContext = React.createContext();
  733. var StyleSheetConsumer = StyleSheetContext.Consumer;
  734. var StylisContext = React.createContext();
  735. var StylisConsumer = StylisContext.Consumer;
  736. var masterSheet = new StyleSheet();
  737. var masterStylis = createStylisInstance();
  738. //
  739. var Keyframes =
  740. /*#__PURE__*/
  741. function () {
  742. function Keyframes(name, stringifyArgs) {
  743. var _this = this;
  744. this.inject = function (styleSheet) {
  745. if (!styleSheet.hasNameForId(_this.id, _this.name)) {
  746. styleSheet.insertRules(_this.id, _this.name, masterStylis.apply(void 0, _this.stringifyArgs));
  747. }
  748. };
  749. this.toString = function () {
  750. return throwStyledComponentsError(12, String(_this.name));
  751. };
  752. this.name = name;
  753. this.id = "sc-keyframes-" + name;
  754. this.stringifyArgs = stringifyArgs;
  755. }
  756. var _proto = Keyframes.prototype;
  757. _proto.getName = function getName() {
  758. return this.name;
  759. };
  760. return Keyframes;
  761. }();
  762. //
  763. /**
  764. * inlined version of
  765. * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js
  766. */
  767. var uppercasePattern = /([A-Z])/g;
  768. var msPattern = /^ms-/;
  769. /**
  770. * Hyphenates a camelcased CSS property name, for example:
  771. *
  772. * > hyphenateStyleName('backgroundColor')
  773. * < "background-color"
  774. * > hyphenateStyleName('MozTransition')
  775. * < "-moz-transition"
  776. * > hyphenateStyleName('msTransition')
  777. * < "-ms-transition"
  778. *
  779. * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
  780. * is converted to `-ms-`.
  781. *
  782. * @param {string} string
  783. * @return {string}
  784. */
  785. function hyphenateStyleName(string) {
  786. return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
  787. }
  788. //
  789. function addUnitIfNeeded(name, value) {
  790. // https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133
  791. // $FlowFixMe
  792. if (value == null || typeof value === 'boolean' || value === '') {
  793. return '';
  794. }
  795. if (typeof value === 'number' && value !== 0 && !(name in unitless)) {
  796. return value + "px"; // Presumes implicit 'px' suffix for unitless numbers
  797. }
  798. return String(value).trim();
  799. }
  800. //
  801. /**
  802. * It's falsish not falsy because 0 is allowed.
  803. */
  804. var isFalsish = function isFalsish(chunk) {
  805. return chunk === undefined || chunk === null || chunk === false || chunk === '';
  806. };
  807. var objToCssArray = function objToCssArray(obj, prevKey) {
  808. var rules = [];
  809. var keys = Object.keys(obj);
  810. keys.forEach(function (key) {
  811. if (!isFalsish(obj[key])) {
  812. if (isPlainObject(obj[key])) {
  813. rules.push.apply(rules, objToCssArray(obj[key], key));
  814. return rules;
  815. } else if (isFunction(obj[key])) {
  816. rules.push(hyphenateStyleName(key) + ":", obj[key], ';');
  817. return rules;
  818. }
  819. rules.push(hyphenateStyleName(key) + ": " + addUnitIfNeeded(key, obj[key]) + ";");
  820. }
  821. return rules;
  822. });
  823. return prevKey ? [prevKey + " {"].concat(rules, ['}']) : rules;
  824. };
  825. function flatten(chunk, executionContext, styleSheet) {
  826. if (Array.isArray(chunk)) {
  827. var ruleSet = [];
  828. for (var i = 0, len = chunk.length, result; i < len; i += 1) {
  829. result = flatten(chunk[i], executionContext, styleSheet);
  830. if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
  831. }
  832. return ruleSet;
  833. }
  834. if (isFalsish(chunk)) {
  835. return '';
  836. }
  837. /* Handle other components */
  838. if (isStyledComponent(chunk)) {
  839. return "." + chunk.styledComponentId;
  840. }
  841. /* Either execute or defer the function */
  842. if (isFunction(chunk)) {
  843. if (isStatelessFunction(chunk) && executionContext) {
  844. var _result = chunk(executionContext);
  845. if (process.env.NODE_ENV !== 'production' && isElement(_result)) {
  846. // eslint-disable-next-line no-console
  847. console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.");
  848. }
  849. return flatten(_result, executionContext, styleSheet);
  850. } else return chunk;
  851. }
  852. if (chunk instanceof Keyframes) {
  853. if (styleSheet) {
  854. chunk.inject(styleSheet);
  855. return chunk.getName();
  856. } else return chunk;
  857. }
  858. /* Handle objects */
  859. return isPlainObject(chunk) ? objToCssArray(chunk) : chunk.toString();
  860. }
  861. //
  862. var printed = {};
  863. function warnOnce(message) {
  864. if (printed[message]) return;
  865. printed[message] = true;
  866. if (typeof console !== 'undefined' && console.warn) console.warn(message);
  867. }
  868. //
  869. var SINGLE_QUOTE = "'".charCodeAt(0);
  870. var DOUBLE_QUOTE = '"'.charCodeAt(0);
  871. var BACKSLASH = '\\'.charCodeAt(0);
  872. var SLASH = '/'.charCodeAt(0);
  873. var NEWLINE = '\n'.charCodeAt(0);
  874. var SPACE = ' '.charCodeAt(0);
  875. var FEED = '\f'.charCodeAt(0);
  876. var TAB = '\t'.charCodeAt(0);
  877. var CR = '\r'.charCodeAt(0);
  878. var OPEN_SQUARE = '['.charCodeAt(0);
  879. var CLOSE_SQUARE = ']'.charCodeAt(0);
  880. var OPEN_PARENTHESES = '('.charCodeAt(0);
  881. var CLOSE_PARENTHESES = ')'.charCodeAt(0);
  882. var OPEN_CURLY = '{'.charCodeAt(0);
  883. var CLOSE_CURLY = '}'.charCodeAt(0);
  884. var SEMICOLON = ';'.charCodeAt(0);
  885. var ASTERISK = '*'.charCodeAt(0);
  886. var COLON = ':'.charCodeAt(0);
  887. var AT = '@'.charCodeAt(0);
  888. var RE_AT_END = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g;
  889. var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g;
  890. var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
  891. function tokenize(input, options) {
  892. if (options === void 0) {
  893. options = {};
  894. }
  895. var tokens = [];
  896. var css = input.css.valueOf();
  897. var ignore = options.ignoreErrors;
  898. var code, next, quote, lines, last, content, escape, nextLine, nextOffset, escaped, escapePos, prev, n;
  899. var length = css.length;
  900. var offset = -1;
  901. var line = 1;
  902. var pos = 0;
  903. function unclosed(what) {
  904. throw input.error("Unclosed " + what, line, pos - offset);
  905. }
  906. while (pos < length) {
  907. code = css.charCodeAt(pos);
  908. if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) {
  909. offset = pos;
  910. line += 1;
  911. }
  912. switch (code) {
  913. case NEWLINE:
  914. case SPACE:
  915. case TAB:
  916. case CR:
  917. case FEED:
  918. next = pos;
  919. do {
  920. next += 1;
  921. code = css.charCodeAt(next);
  922. if (code === NEWLINE) {
  923. offset = next;
  924. line += 1;
  925. }
  926. } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
  927. tokens.push(['space', css.slice(pos, next)]);
  928. pos = next - 1;
  929. break;
  930. case OPEN_SQUARE:
  931. tokens.push(['[', '[', line, pos - offset]);
  932. break;
  933. case CLOSE_SQUARE:
  934. tokens.push([']', ']', line, pos - offset]);
  935. break;
  936. case OPEN_CURLY:
  937. tokens.push(['{', '{', line, pos - offset]);
  938. break;
  939. case CLOSE_CURLY:
  940. tokens.push(['}', '}', line, pos - offset]);
  941. break;
  942. case COLON:
  943. tokens.push([':', ':', line, pos - offset]);
  944. break;
  945. case SEMICOLON:
  946. tokens.push([';', ';', line, pos - offset]);
  947. break;
  948. case OPEN_PARENTHESES:
  949. prev = tokens.length ? tokens[tokens.length - 1][1] : '';
  950. n = css.charCodeAt(pos + 1);
  951. if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) {
  952. next = pos;
  953. do {
  954. escaped = false;
  955. next = css.indexOf(')', next + 1);
  956. if (next === -1) {
  957. if (ignore) {
  958. next = pos;
  959. break;
  960. } else {
  961. unclosed('bracket');
  962. }
  963. }
  964. escapePos = next;
  965. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  966. escapePos -= 1;
  967. escaped = !escaped;
  968. }
  969. } while (escaped);
  970. tokens.push(['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
  971. pos = next;
  972. } else {
  973. next = css.indexOf(')', pos + 1);
  974. content = css.slice(pos, next + 1);
  975. if (next === -1 || RE_BAD_BRACKET.test(content)) {
  976. tokens.push(['(', '(', line, pos - offset]);
  977. } else {
  978. tokens.push(['brackets', content, line, pos - offset, line, next - offset]);
  979. pos = next;
  980. }
  981. }
  982. break;
  983. case CLOSE_PARENTHESES:
  984. tokens.push([')', ')', line, pos - offset]);
  985. break;
  986. case SINGLE_QUOTE:
  987. case DOUBLE_QUOTE:
  988. quote = code === SINGLE_QUOTE ? "'" : '"';
  989. next = pos;
  990. do {
  991. escaped = false;
  992. next = css.indexOf(quote, next + 1);
  993. if (next === -1) {
  994. if (ignore) {
  995. next = pos + 1;
  996. break;
  997. } else {
  998. unclosed('quote');
  999. }
  1000. }
  1001. escapePos = next;
  1002. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  1003. escapePos -= 1;
  1004. escaped = !escaped;
  1005. }
  1006. } while (escaped);
  1007. content = css.slice(pos, next + 1);
  1008. lines = content.split('\n');
  1009. last = lines.length - 1;
  1010. if (last > 0) {
  1011. nextLine = line + last;
  1012. nextOffset = next - lines[last].length;
  1013. } else {
  1014. nextLine = line;
  1015. nextOffset = offset;
  1016. }
  1017. tokens.push(['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset]);
  1018. offset = nextOffset;
  1019. line = nextLine;
  1020. pos = next;
  1021. break;
  1022. case AT:
  1023. RE_AT_END.lastIndex = pos + 1;
  1024. RE_AT_END.test(css);
  1025. if (RE_AT_END.lastIndex === 0) {
  1026. next = css.length - 1;
  1027. } else {
  1028. next = RE_AT_END.lastIndex - 2;
  1029. }
  1030. tokens.push(['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
  1031. pos = next;
  1032. break;
  1033. case BACKSLASH:
  1034. next = pos;
  1035. escape = true;
  1036. while (css.charCodeAt(next + 1) === BACKSLASH) {
  1037. next += 1;
  1038. escape = !escape;
  1039. }
  1040. code = css.charCodeAt(next + 1);
  1041. if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
  1042. next += 1;
  1043. }
  1044. tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
  1045. pos = next;
  1046. break;
  1047. default:
  1048. if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
  1049. next = css.indexOf('*/', pos + 2) + 1;
  1050. if (next === 0) {
  1051. if (ignore) {
  1052. next = css.length;
  1053. } else {
  1054. unclosed('comment');
  1055. }
  1056. }
  1057. content = css.slice(pos, next + 1);
  1058. lines = content.split('\n');
  1059. last = lines.length - 1;
  1060. if (last > 0) {
  1061. nextLine = line + last;
  1062. nextOffset = next - lines[last].length;
  1063. } else {
  1064. nextLine = line;
  1065. nextOffset = offset;
  1066. }
  1067. tokens.push(['comment', content, line, pos - offset, nextLine, next - nextOffset]);
  1068. offset = nextOffset;
  1069. line = nextLine;
  1070. pos = next;
  1071. } else {
  1072. RE_WORD_END.lastIndex = pos + 1;
  1073. RE_WORD_END.test(css);
  1074. if (RE_WORD_END.lastIndex === 0) {
  1075. next = css.length - 1;
  1076. } else {
  1077. next = RE_WORD_END.lastIndex - 2;
  1078. }
  1079. tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
  1080. pos = next;
  1081. }
  1082. break;
  1083. }
  1084. pos++;
  1085. }
  1086. return tokens;
  1087. }
  1088. //
  1089. var HIGHLIGHT_THEME = {
  1090. brackets: [36, 39],
  1091. // cyan
  1092. string: [31, 39],
  1093. // red
  1094. 'at-word': [31, 39],
  1095. // red
  1096. comment: [90, 39],
  1097. // gray
  1098. '{': [32, 39],
  1099. // green
  1100. '}': [32, 39],
  1101. // green
  1102. ':': [1, 22],
  1103. // bold
  1104. ';': [1, 22],
  1105. // bold
  1106. '(': [1, 22],
  1107. // bold
  1108. ')': [1, 22] // bold
  1109. };
  1110. function code(color) {
  1111. return "\x1B[" + color + "m";
  1112. }
  1113. function terminalHighlight(css) {
  1114. var tokens = tokenize(new Input(css), {
  1115. ignoreErrors: true
  1116. });
  1117. var result = [];
  1118. tokens.forEach(function (token) {
  1119. var color = HIGHLIGHT_THEME[token[0]];
  1120. if (color) {
  1121. result.push(token[1].split(/\r?\n/).map(function (i) {
  1122. return code(color[0]) + i + code(color[1]);
  1123. }).join('\n'));
  1124. } else {
  1125. result.push(token[1]);
  1126. }
  1127. });
  1128. return result.join('');
  1129. }
  1130. /**
  1131. * The CSS parser throws this error for broken CSS.
  1132. *
  1133. * Custom parsers can throw this error for broken custom syntax using
  1134. * the {@link Node#error} method.
  1135. *
  1136. * PostCSS will use the input source map to detect the original error location.
  1137. * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
  1138. * PostCSS will show the original position in the Sass file.
  1139. *
  1140. * If you need the position in the PostCSS input
  1141. * (e.g., to debug the previous compiler), use `error.input.file`.
  1142. *
  1143. * @example
  1144. * // Catching and checking syntax error
  1145. * try {
  1146. * postcss.parse('a{')
  1147. * } catch (error) {
  1148. * if ( error.name === 'CssSyntaxError' ) {
  1149. * error //=> CssSyntaxError
  1150. * }
  1151. * }
  1152. *
  1153. * @example
  1154. * // Raising error from plugin
  1155. * throw node.error('Unknown variable', { plugin: 'postcss-vars' });
  1156. */
  1157. var CssSyntaxError =
  1158. /*#__PURE__*/
  1159. function () {
  1160. /**
  1161. * @param {string} message - error message
  1162. * @param {number} [line] - source line of the error
  1163. * @param {number} [column] - source column of the error
  1164. * @param {string} [source] - source code of the broken file
  1165. * @param {string} [file] - absolute path to the broken file
  1166. * @param {string} [plugin] - PostCSS plugin name, if error came from plugin
  1167. */
  1168. function CssSyntaxError(message, line, column, source, file, plugin) {
  1169. /**
  1170. * @member {string} - Always equal to `'CssSyntaxError'`. You should
  1171. * always check error type
  1172. * by `error.name === 'CssSyntaxError'` instead of
  1173. * `error instanceof CssSyntaxError`, because
  1174. * npm could have several PostCSS versions.
  1175. *
  1176. * @example
  1177. * if ( error.name === 'CssSyntaxError' ) {
  1178. * error //=> CssSyntaxError
  1179. * }
  1180. */
  1181. this.name = 'CssSyntaxError';
  1182. /**
  1183. * @member {string} - Error message.
  1184. *
  1185. * @example
  1186. * error.message //=> 'Unclosed block'
  1187. */
  1188. this.reason = message;
  1189. if (file) {
  1190. /**
  1191. * @member {string} - Absolute path to the broken file.
  1192. *
  1193. * @example
  1194. * error.file //=> 'a.sass'
  1195. * error.input.file //=> 'a.css'
  1196. */
  1197. this.file = file;
  1198. }
  1199. if (source) {
  1200. /**
  1201. * @member {string} - Source code of the broken file.
  1202. *
  1203. * @example
  1204. * error.source //=> 'a { b {} }'
  1205. * error.input.column //=> 'a b { }'
  1206. */
  1207. this.source = source;
  1208. }
  1209. if (plugin) {
  1210. /**
  1211. * @member {string} - Plugin name, if error came from plugin.
  1212. *
  1213. * @example
  1214. * error.plugin //=> 'postcss-vars'
  1215. */
  1216. this.plugin = plugin;
  1217. }
  1218. if (typeof line !== 'undefined' && typeof column !== 'undefined') {
  1219. /**
  1220. * @member {number} - Source line of the error.
  1221. *
  1222. * @example
  1223. * error.line //=> 2
  1224. * error.input.line //=> 4
  1225. */
  1226. this.line = line;
  1227. /**
  1228. * @member {number} - Source column of the error.
  1229. *
  1230. * @example
  1231. * error.column //=> 1
  1232. * error.input.column //=> 4
  1233. */
  1234. this.column = column;
  1235. }
  1236. this.setMessage();
  1237. if (Error.captureStackTrace) {
  1238. Error.captureStackTrace(this, CssSyntaxError);
  1239. }
  1240. }
  1241. var _proto = CssSyntaxError.prototype;
  1242. _proto.setMessage = function setMessage() {
  1243. /**
  1244. * @member {string} - Full error text in the GNU error format
  1245. * with plugin, file, line and column.
  1246. *
  1247. * @example
  1248. * error.message //=> 'a.css:1:1: Unclosed block'
  1249. */
  1250. this.message = this.plugin ? this.plugin + ": " : '';
  1251. this.message += this.file ? this.file : '<css input>';
  1252. if (typeof this.line !== 'undefined') {
  1253. this.message += ":" + this.line + ":" + this.column;
  1254. }
  1255. this.message += ": " + this.reason;
  1256. }
  1257. /**
  1258. * Returns a few lines of CSS source that caused the error.
  1259. *
  1260. * If the CSS has an input source map without `sourceContent`,
  1261. * this method will return an empty string.
  1262. *
  1263. * @param {boolean} [color] whether arrow will be colored red by terminal
  1264. * color codes. By default, PostCSS will detect
  1265. * color support by `process.stdout.isTTY`
  1266. * and `process.env.NODE_DISABLE_COLORS`.
  1267. *
  1268. * @example
  1269. * error.showSourceCode() //=> " 4 | }
  1270. * // 5 | a {
  1271. * // > 6 | bad
  1272. * // | ^
  1273. * // 7 | }
  1274. * // 8 | b {"
  1275. *
  1276. * @return {string} few lines of CSS source that caused the error
  1277. */
  1278. ;
  1279. _proto.showSourceCode = function showSourceCode(color) {
  1280. var _this = this;
  1281. if (!this.source) return '';
  1282. var css = this.source;
  1283. if (typeof color === 'undefined') color = supportsColor;
  1284. if (color) css = terminalHighlight(css);
  1285. var lines = css.split(/\r?\n/);
  1286. var start = Math.max(this.line - 3, 0);
  1287. var end = Math.min(this.line + 2, lines.length);
  1288. var maxWidth = String(end).length;
  1289. return lines.slice(start, end).map(function (line, index) {
  1290. var number = start + 1 + index;
  1291. var padded = (" " + number).slice(-maxWidth);
  1292. var gutter = " " + padded + " | ";
  1293. if (number === _this.line) {
  1294. var spacing = gutter.replace(/\d/g, ' ') + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' ');
  1295. return ">" + gutter + line + "\n " + spacing + "^";
  1296. } else {
  1297. return " " + gutter + line;
  1298. }
  1299. }).join('\n');
  1300. }
  1301. /**
  1302. * Returns error position, message and source code of the broken part.
  1303. *
  1304. * @example
  1305. * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
  1306. * // > 1 | a {
  1307. * // | ^"
  1308. *
  1309. * @return {string} error position, message and source code
  1310. */
  1311. ;
  1312. _proto.toString = function toString() {
  1313. var code = this.showSourceCode();
  1314. if (code) {
  1315. code = "\n\n" + code + "\n";
  1316. }
  1317. return this.name + ": " + this.message + code;
  1318. };
  1319. _createClass(CssSyntaxError, [{
  1320. key: "generated",
  1321. get: function get() {
  1322. warnOnce('CssSyntaxError#generated is deprecated. Use input instead.');
  1323. return this.input;
  1324. }
  1325. /**
  1326. * @memberof CssSyntaxError#
  1327. * @member {Input} input - Input object with PostCSS internal information
  1328. * about input file. If input has source map
  1329. * from previous tool, PostCSS will use origin
  1330. * (for example, Sass) source. You can use this
  1331. * object to get PostCSS input source.
  1332. *
  1333. * @example
  1334. * error.input.file //=> 'a.css'
  1335. * error.file //=> 'a.sass'
  1336. */
  1337. }]);
  1338. return CssSyntaxError;
  1339. }();
  1340. //
  1341. /* eslint-disable valid-jsdoc */
  1342. var defaultRaw = {
  1343. colon: ': ',
  1344. indent: ' ',
  1345. beforeDecl: '\n',
  1346. beforeRule: '\n',
  1347. beforeOpen: ' ',
  1348. beforeClose: '\n',
  1349. beforeComment: '\n',
  1350. after: '\n',
  1351. emptyBody: '',
  1352. commentLeft: ' ',
  1353. commentRight: ' '
  1354. };
  1355. function capitalize(str) {
  1356. return str[0].toUpperCase() + str.slice(1);
  1357. }
  1358. var Stringifier =
  1359. /*#__PURE__*/
  1360. function () {
  1361. function Stringifier(builder) {
  1362. this.builder = builder;
  1363. }
  1364. var _proto = Stringifier.prototype;
  1365. _proto.stringify = function stringify(node, semicolon) {
  1366. this[node.type](node, semicolon);
  1367. };
  1368. _proto.root = function root(node) {
  1369. this.body(node);
  1370. if (node.raws.after) this.builder(node.raws.after);
  1371. };
  1372. _proto.comment = function comment(node) {
  1373. var left = this.raw(node, 'left', 'commentLeft');
  1374. var right = this.raw(node, 'right', 'commentRight');
  1375. this.builder("/*" + left + node.text + right + "*/", node);
  1376. };
  1377. _proto.decl = function decl(node, semicolon) {
  1378. var between = this.raw(node, 'between', 'colon');
  1379. var string = node.prop + between + this.rawValue(node, 'value');
  1380. if (node.important) {
  1381. string += node.raws.important || ' !important';
  1382. }
  1383. if (semicolon) string += ';';
  1384. this.builder(string, node);
  1385. };
  1386. _proto.rule = function rule(node) {
  1387. this.block(node, this.rawValue(node, 'selector'));
  1388. };
  1389. _proto.atrule = function atrule(node, semicolon) {
  1390. var name = "@" + node.name;
  1391. var params = node.params ? this.rawValue(node, 'params') : '';
  1392. if (typeof node.raws.afterName !== 'undefined') {
  1393. name += node.raws.afterName;
  1394. } else if (params) {
  1395. name += ' ';
  1396. }
  1397. if (node.nodes) {
  1398. this.block(node, name + params);
  1399. } else {
  1400. var end = (node.raws.between || '') + (semicolon ? ';' : '');
  1401. this.builder(name + params + end, node);
  1402. }
  1403. };
  1404. _proto.body = function body(node) {
  1405. var last = node.nodes.length - 1;
  1406. while (last > 0) {
  1407. if (node.nodes[last].type !== 'comment') break;
  1408. last -= 1;
  1409. }
  1410. var semicolon = this.raw(node, 'semicolon');
  1411. for (var i = 0; i < node.nodes.length; i++) {
  1412. var child = node.nodes[i];
  1413. var before = this.raw(child, 'before');
  1414. if (before) this.builder(before);
  1415. this.stringify(child, last !== i || semicolon);
  1416. }
  1417. };
  1418. _proto.block = function block(node, start) {
  1419. var between = this.raw(node, 'between', 'beforeOpen');
  1420. this.builder(start + between + "{", node, 'start');
  1421. var after;
  1422. if (node.nodes && node.nodes.length) {
  1423. this.body(node);
  1424. after = this.raw(node, 'after');
  1425. } else {
  1426. after = this.raw(node, 'after', 'emptyBody');
  1427. }
  1428. if (after) this.builder(after);
  1429. this.builder('}', node, 'end');
  1430. };
  1431. _proto.raw = function raw(node, own, detect) {
  1432. var value;
  1433. if (!detect) detect = own; // Already had
  1434. if (own) {
  1435. value = node.raws[own];
  1436. if (typeof value !== 'undefined') return value;
  1437. }
  1438. var parent = node.parent; // Hack for first rule in CSS
  1439. if (detect === 'before') {
  1440. if (!parent || parent.type === 'root' && parent.first === node) {
  1441. return '';
  1442. }
  1443. } // Floating child without parent
  1444. if (!parent) return defaultRaw[detect]; // Detect style by other nodes
  1445. var root = node.root();
  1446. if (!root.rawCache) root.rawCache = {};
  1447. if (typeof root.rawCache[detect] !== 'undefined') {
  1448. return root.rawCache[detect];
  1449. }
  1450. if (detect === 'before' || detect === 'after') {
  1451. return this.beforeAfter(node, detect);
  1452. } else {
  1453. var method = "raw" + capitalize(detect);
  1454. if (this[method]) {
  1455. value = this[method](root, node);
  1456. } else {
  1457. root.walk(function (i) {
  1458. value = i.raws[own];
  1459. if (typeof value !== 'undefined') return false;
  1460. });
  1461. }
  1462. }
  1463. if (typeof value === 'undefined') value = defaultRaw[detect];
  1464. root.rawCache[detect] = value;
  1465. return value;
  1466. };
  1467. _proto.rawSemicolon = function rawSemicolon(root) {
  1468. var value;
  1469. root.walk(function (i) {
  1470. if (i.nodes && i.nodes.length && i.last.type === 'decl') {
  1471. value = i.raws.semicolon;
  1472. if (typeof value !== 'undefined') return false;
  1473. }
  1474. });
  1475. return value;
  1476. };
  1477. _proto.rawEmptyBody = function rawEmptyBody(root) {
  1478. var value;
  1479. root.walk(function (i) {
  1480. if (i.nodes && i.nodes.length === 0) {
  1481. value = i.raws.after;
  1482. if (typeof value !== 'undefined') return false;
  1483. }
  1484. });
  1485. return value;
  1486. };
  1487. _proto.rawIndent = function rawIndent(root) {
  1488. if (root.raws.indent) return root.raws.indent;
  1489. var value;
  1490. root.walk(function (i) {
  1491. var p = i.parent;
  1492. if (p && p !== root && p.parent && p.parent === root) {
  1493. if (typeof i.raws.before !== 'undefined') {
  1494. var parts = i.raws.before.split('\n');
  1495. value = parts[parts.length - 1];
  1496. value = value.replace(/[^\s]/g, '');
  1497. return false;
  1498. }
  1499. }
  1500. });
  1501. return value;
  1502. };
  1503. _proto.rawBeforeComment = function rawBeforeComment(root, node) {
  1504. var value;
  1505. root.walkComments(function (i) {
  1506. if (typeof i.raws.before !== 'undefined') {
  1507. value = i.raws.before;
  1508. if (value.indexOf('\n') !== -1) {
  1509. value = value.replace(/[^\n]+$/, '');
  1510. }
  1511. return false;
  1512. }
  1513. });
  1514. if (typeof value === 'undefined') {
  1515. value = this.raw(node, null, 'beforeDecl');
  1516. }
  1517. return value;
  1518. };
  1519. _proto.rawBeforeDecl = function rawBeforeDecl(root, node) {
  1520. var value;
  1521. root.walkDecls(function (i) {
  1522. if (typeof i.raws.before !== 'undefined') {
  1523. value = i.raws.before;
  1524. if (value.indexOf('\n') !== -1) {
  1525. value = value.replace(/[^\n]+$/, '');
  1526. }
  1527. return false;
  1528. }
  1529. });
  1530. if (typeof value === 'undefined') {
  1531. value = this.raw(node, null, 'beforeRule');
  1532. }
  1533. return value;
  1534. };
  1535. _proto.rawBeforeRule = function rawBeforeRule(root) {
  1536. var value;
  1537. root.walk(function (i) {
  1538. if (i.nodes && (i.parent !== root || root.first !== i)) {
  1539. if (typeof i.raws.before !== 'undefined') {
  1540. value = i.raws.before;
  1541. if (value.indexOf('\n') !== -1) {
  1542. value = value.replace(/[^\n]+$/, '');
  1543. }
  1544. return false;
  1545. }
  1546. }
  1547. });
  1548. return value;
  1549. };
  1550. _proto.rawBeforeClose = function rawBeforeClose(root) {
  1551. var value;
  1552. root.walk(function (i) {
  1553. if (i.nodes && i.nodes.length > 0) {
  1554. if (typeof i.raws.after !== 'undefined') {
  1555. value = i.raws.after;
  1556. if (value.indexOf('\n') !== -1) {
  1557. value = value.replace(/[^\n]+$/, '');
  1558. }
  1559. return false;
  1560. }
  1561. }
  1562. });
  1563. return value;
  1564. };
  1565. _proto.rawBeforeOpen = function rawBeforeOpen(root) {
  1566. var value;
  1567. root.walk(function (i) {
  1568. if (i.type !== 'decl') {
  1569. value = i.raws.between;
  1570. if (typeof value !== 'undefined') return false;
  1571. }
  1572. });
  1573. return value;
  1574. };
  1575. _proto.rawColon = function rawColon(root) {
  1576. var value;
  1577. root.walkDecls(function (i) {
  1578. if (typeof i.raws.between !== 'undefined') {
  1579. value = i.raws.between.replace(/[^\s:]/g, '');
  1580. return false;
  1581. }
  1582. });
  1583. return value;
  1584. };
  1585. _proto.beforeAfter = function beforeAfter(node, detect) {
  1586. var value;
  1587. if (node.type === 'decl') {
  1588. value = this.raw(node, null, 'beforeDecl');
  1589. } else if (node.type === 'comment') {
  1590. value = this.raw(node, null, 'beforeComment');
  1591. } else if (detect === 'before') {
  1592. value = this.raw(node, null, 'beforeRule');
  1593. } else {
  1594. value = this.raw(node, null, 'beforeClose');
  1595. }
  1596. var buf = node.parent;
  1597. var depth = 0;
  1598. while (buf && buf.type !== 'root') {
  1599. depth += 1;
  1600. buf = buf.parent;
  1601. }
  1602. if (value.indexOf('\n') !== -1) {
  1603. var indent = this.raw(node, null, 'indent');
  1604. if (indent.length) {
  1605. for (var step = 0; step < depth; step++) {
  1606. value += indent;
  1607. }
  1608. }
  1609. }
  1610. return value;
  1611. };
  1612. _proto.rawValue = function rawValue(node, prop) {
  1613. var value = node[prop];
  1614. var raw = node.raws[prop];
  1615. if (raw && raw.value === value) {
  1616. return raw.raw;
  1617. } else {
  1618. return value;
  1619. }
  1620. };
  1621. return Stringifier;
  1622. }();
  1623. //
  1624. function stringify(node, builder) {
  1625. var str = new Stringifier(builder);
  1626. str.stringify(node);
  1627. }
  1628. /**
  1629. * @typedef {object} position
  1630. * @property {number} line - source line in file
  1631. * @property {number} column - source column in file
  1632. */
  1633. /**
  1634. * @typedef {object} source
  1635. * @property {Input} input - {@link Input} with input file
  1636. * @property {position} start - The starting position of the node’s source
  1637. * @property {position} end - The ending position of the node’s source
  1638. */
  1639. var cloneNode = function cloneNode(obj, parent) {
  1640. var cloned = new obj.constructor();
  1641. for (var i in obj) {
  1642. if (!obj.hasOwnProperty(i)) continue;
  1643. var value = obj[i];
  1644. var type = typeof value;
  1645. if (i === 'parent' && type === 'object') {
  1646. if (parent) cloned[i] = parent;
  1647. } else if (i === 'source') {
  1648. cloned[i] = value;
  1649. } else if (value instanceof Array) {
  1650. cloned[i] = value.map(function (j) {
  1651. return cloneNode(j, cloned);
  1652. });
  1653. } else if (i !== 'before' && i !== 'after' && i !== 'between' && i !== 'semicolon') {
  1654. if (type === 'object' && value !== null) value = cloneNode(value);
  1655. cloned[i] = value;
  1656. }
  1657. }
  1658. return cloned;
  1659. };
  1660. /**
  1661. * All node classes inherit the following common methods.
  1662. *
  1663. * @abstract
  1664. */
  1665. var Node =
  1666. /*#__PURE__*/
  1667. function () {
  1668. /**
  1669. * @param {object} [defaults] - value for node properties
  1670. */
  1671. function Node(defaults) {
  1672. if (defaults === void 0) {
  1673. defaults = {};
  1674. }
  1675. this.raws = {};
  1676. for (var name in defaults) {
  1677. this[name] = defaults[name];
  1678. }
  1679. }
  1680. /**
  1681. * Returns a CssSyntaxError instance containing the original position
  1682. * of the node in the source, showing line and column numbers and also
  1683. * a small excerpt to facilitate debugging.
  1684. *
  1685. * If present, an input source map will be used to get the original position
  1686. * of the source, even from a previous compilation step
  1687. * (e.g., from Sass compilation).
  1688. *
  1689. * This method produces very useful error messages.
  1690. *
  1691. * @param {string} message - error description
  1692. * @param {object} [opts] - options
  1693. * @param {string} opts.plugin - plugin name that created this error.
  1694. * PostCSS will set it automatically.
  1695. * @param {string} opts.word - a word inside a node’s string that should
  1696. * be highlighted as the source of the error
  1697. * @param {number} opts.index - an index inside a node’s string that should
  1698. * be highlighted as the source of the error
  1699. *
  1700. * @return {CssSyntaxError} error object to throw it
  1701. *
  1702. * @example
  1703. * if ( !variables[name] ) {
  1704. * throw decl.error('Unknown variable ' + name, { word: name });
  1705. * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  1706. * // color: $black
  1707. * // a
  1708. * // ^
  1709. * // background: white
  1710. * }
  1711. */
  1712. var _proto = Node.prototype;
  1713. _proto.error = function error(message, opts) {
  1714. if (opts === void 0) {
  1715. opts = {};
  1716. }
  1717. if (this.source) {
  1718. var pos = this.positionBy(opts);
  1719. return this.source.input.error(message, pos.line, pos.column, opts);
  1720. } else {
  1721. return new CssSyntaxError(message);
  1722. }
  1723. }
  1724. /**
  1725. * This method is provided as a convenience wrapper for {@link Result#warn}.
  1726. *
  1727. * @param {Result} result - the {@link Result} instance
  1728. * that will receive the warning
  1729. * @param {string} text - warning message
  1730. * @param {object} [opts] - options
  1731. * @param {string} opts.plugin - plugin name that created this warning.
  1732. * PostCSS will set it automatically.
  1733. * @param {string} opts.word - a word inside a node’s string that should
  1734. * be highlighted as the source of the warning
  1735. * @param {number} opts.index - an index inside a node’s string that should
  1736. * be highlighted as the source of the warning
  1737. *
  1738. * @return {Warning} created warning object
  1739. *
  1740. * @example
  1741. * const plugin = postcss.plugin('postcss-deprecated', () => {
  1742. * return (root, result) => {
  1743. * root.walkDecls('bad', decl => {
  1744. * decl.warn(result, 'Deprecated property bad');
  1745. * });
  1746. * };
  1747. * });
  1748. */
  1749. ;
  1750. _proto.warn = function warn(result, text, opts) {
  1751. var data = {
  1752. node: this
  1753. };
  1754. for (var i in opts) {
  1755. data[i] = opts[i];
  1756. }
  1757. return result.warn(text, data);
  1758. }
  1759. /**
  1760. * Removes the node from its parent and cleans the parent properties
  1761. * from the node and its children.
  1762. *
  1763. * @example
  1764. * if ( decl.prop.match(/^-webkit-/) ) {
  1765. * decl.remove();
  1766. * }
  1767. *
  1768. * @return {Node} node to make calls chain
  1769. */
  1770. ;
  1771. _proto.remove = function remove() {
  1772. if (this.parent) {
  1773. this.parent.removeChild(this);
  1774. }
  1775. this.parent = undefined;
  1776. return this;
  1777. }
  1778. /**
  1779. * Returns a CSS string representing the node.
  1780. *
  1781. * @param {stringifier|syntax} [stringifier] - a syntax to use
  1782. * in string generation
  1783. *
  1784. * @return {string} CSS string of this node
  1785. *
  1786. * @example
  1787. * postcss.rule({ selector: 'a' }).toString() //=> "a {}"
  1788. */
  1789. ;
  1790. _proto.toString = function toString(stringifier) {
  1791. if (stringifier === void 0) {
  1792. stringifier = stringify;
  1793. }
  1794. if (stringifier.stringify) stringifier = stringifier.stringify;
  1795. var result = '';
  1796. stringifier(this, function (i) {
  1797. result += i;
  1798. });
  1799. return result;
  1800. }
  1801. /**
  1802. * Returns a clone of the node.
  1803. *
  1804. * The resulting cloned node and its (cloned) children will have
  1805. * a clean parent and code style properties.
  1806. *
  1807. * @param {object} [overrides] - new properties to override in the clone.
  1808. *
  1809. * @example
  1810. * const cloned = decl.clone({ prop: '-moz-' + decl.prop });
  1811. * cloned.raws.before //=> undefined
  1812. * cloned.parent //=> undefined
  1813. * cloned.toString() //=> -moz-transform: scale(0)
  1814. *
  1815. * @return {Node} clone of the node
  1816. */
  1817. ;
  1818. _proto.clone = function clone(overrides) {
  1819. if (overrides === void 0) {
  1820. overrides = {};
  1821. }
  1822. var cloned = cloneNode(this);
  1823. for (var name in overrides) {
  1824. cloned[name] = overrides[name];
  1825. }
  1826. return cloned;
  1827. }
  1828. /**
  1829. * Shortcut to clone the node and insert the resulting cloned node
  1830. * before the current node.
  1831. *
  1832. * @param {object} [overrides] - new properties to override in the clone.
  1833. *
  1834. * @example
  1835. * decl.cloneBefore({ prop: '-moz-' + decl.prop });
  1836. *
  1837. * @return {Node} - new node
  1838. */
  1839. ;
  1840. _proto.cloneBefore = function cloneBefore(overrides) {
  1841. if (overrides === void 0) {
  1842. overrides = {};
  1843. }
  1844. var cloned = this.clone(overrides);
  1845. this.parent.insertBefore(this, cloned);
  1846. return cloned;
  1847. }
  1848. /**
  1849. * Shortcut to clone the node and insert the resulting cloned node
  1850. * after the current node.
  1851. *
  1852. * @param {object} [overrides] - new properties to override in the clone.
  1853. *
  1854. * @return {Node} - new node
  1855. */
  1856. ;
  1857. _proto.cloneAfter = function cloneAfter(overrides) {
  1858. if (overrides === void 0) {
  1859. overrides = {};
  1860. }
  1861. var cloned = this.clone(overrides);
  1862. this.parent.insertAfter(this, cloned);
  1863. return cloned;
  1864. }
  1865. /**
  1866. * Inserts node(s) before the current node and removes the current node.
  1867. *
  1868. * @param {...Node} nodes - node(s) to replace current one
  1869. *
  1870. * @example
  1871. * if ( atrule.name == 'mixin' ) {
  1872. * atrule.replaceWith(mixinRules[atrule.params]);
  1873. * }
  1874. *
  1875. * @return {Node} current node to methods chain
  1876. */
  1877. ;
  1878. _proto.replaceWith = function replaceWith() {
  1879. var _this = this;
  1880. if (this.parent) {
  1881. for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) {
  1882. nodes[_key] = arguments[_key];
  1883. }
  1884. nodes.forEach(function (node) {
  1885. _this.parent.insertBefore(_this, node);
  1886. });
  1887. this.remove();
  1888. }
  1889. return this;
  1890. }
  1891. /**
  1892. * Removes the node from its current parent and inserts it
  1893. * at the end of `newParent`.
  1894. *
  1895. * This will clean the `before` and `after` code {@link Node#raws} data
  1896. * from the node and replace them with the indentation style of `newParent`.
  1897. * It will also clean the `between` property
  1898. * if `newParent` is in another {@link Root}.
  1899. *
  1900. * @param {Container} newParent - container node where the current node
  1901. * will be moved
  1902. *
  1903. * @example
  1904. * atrule.moveTo(atrule.root());
  1905. *
  1906. * @return {Node} current node to methods chain
  1907. */
  1908. ;
  1909. _proto.moveTo = function moveTo(newParent) {
  1910. this.cleanRaws(this.root() === newParent.root());
  1911. this.remove();
  1912. newParent.append(this);
  1913. return this;
  1914. }
  1915. /**
  1916. * Removes the node from its current parent and inserts it into
  1917. * a new parent before `otherNode`.
  1918. *
  1919. * This will also clean the node’s code style properties just as it would
  1920. * in {@link Node#moveTo}.
  1921. *
  1922. * @param {Node} otherNode - node that will be before current node
  1923. *
  1924. * @return {Node} current node to methods chain
  1925. */
  1926. ;
  1927. _proto.moveBefore = function moveBefore(otherNode) {
  1928. this.cleanRaws(this.root() === otherNode.root());
  1929. this.remove();
  1930. otherNode.parent.insertBefore(otherNode, this);
  1931. return this;
  1932. }
  1933. /**
  1934. * Removes the node from its current parent and inserts it into
  1935. * a new parent after `otherNode`.
  1936. *
  1937. * This will also clean the node’s code style properties just as it would
  1938. * in {@link Node#moveTo}.
  1939. *
  1940. * @param {Node} otherNode - node that will be after current node
  1941. *
  1942. * @return {Node} current node to methods chain
  1943. */
  1944. ;
  1945. _proto.moveAfter = function moveAfter(otherNode) {
  1946. this.cleanRaws(this.root() === otherNode.root());
  1947. this.remove();
  1948. otherNode.parent.insertAfter(otherNode, this);
  1949. return this;
  1950. }
  1951. /**
  1952. * Returns the next child of the node’s parent.
  1953. * Returns `undefined` if the current node is the last child.
  1954. *
  1955. * @return {Node|undefined} next node
  1956. *
  1957. * @example
  1958. * if ( comment.text === 'delete next' ) {
  1959. * const next = comment.next();
  1960. * if ( next ) {
  1961. * next.remove();
  1962. * }
  1963. * }
  1964. */
  1965. ;
  1966. _proto.next = function next() {
  1967. var index = this.parent.index(this);
  1968. return this.parent.nodes[index + 1];
  1969. }
  1970. /**
  1971. * Returns the previous child of the node’s parent.
  1972. * Returns `undefined` if the current node is the first child.
  1973. *
  1974. * @return {Node|undefined} previous node
  1975. *
  1976. * @example
  1977. * const annotation = decl.prev();
  1978. * if ( annotation.type == 'comment' ) {
  1979. * readAnnotation(annotation.text);
  1980. * }
  1981. */
  1982. ;
  1983. _proto.prev = function prev() {
  1984. var index = this.parent.index(this);
  1985. return this.parent.nodes[index - 1];
  1986. };
  1987. _proto.toJSON = function toJSON() {
  1988. var fixed = {};
  1989. for (var name in this) {
  1990. if (!this.hasOwnProperty(name)) continue;
  1991. if (name === 'parent') continue;
  1992. var value = this[name];
  1993. if (value instanceof Array) {
  1994. fixed[name] = value.map(function (i) {
  1995. if (typeof i === 'object' && i.toJSON) {
  1996. return i.toJSON();
  1997. } else {
  1998. return i;
  1999. }
  2000. });
  2001. } else if (typeof value === 'object' && value.toJSON) {
  2002. fixed[name] = value.toJSON();
  2003. } else {
  2004. fixed[name] = value;
  2005. }
  2006. }
  2007. return fixed;
  2008. }
  2009. /**
  2010. * Returns a {@link Node#raws} value. If the node is missing
  2011. * the code style property (because the node was manually built or cloned),
  2012. * PostCSS will try to autodetect the code style property by looking
  2013. * at other nodes in the tree.
  2014. *
  2015. * @param {string} prop - name of code style property
  2016. * @param {string} [defaultType] - name of default value, it can be missed
  2017. * if the value is the same as prop
  2018. *
  2019. * @example
  2020. * const root = postcss.parse('a { background: white }');
  2021. * root.nodes[0].append({ prop: 'color', value: 'black' });
  2022. * root.nodes[0].nodes[1].raws.before //=> undefined
  2023. * root.nodes[0].nodes[1].raw('before') //=> ' '
  2024. *
  2025. * @return {string} code style value
  2026. */
  2027. ;
  2028. _proto.raw = function raw(prop, defaultType) {
  2029. var str = new Stringifier();
  2030. return str.raw(this, prop, defaultType);
  2031. }
  2032. /**
  2033. * Finds the Root instance of the node’s tree.
  2034. *
  2035. * @example
  2036. * root.nodes[0].nodes[0].root() === root
  2037. *
  2038. * @return {Root} root parent
  2039. */
  2040. ;
  2041. _proto.root = function root() {
  2042. var result = this;
  2043. while (result.parent) {
  2044. result = result.parent;
  2045. }
  2046. return result;
  2047. };
  2048. _proto.cleanRaws = function cleanRaws(keepBetween) {
  2049. delete this.raws.before;
  2050. delete this.raws.after;
  2051. if (!keepBetween) delete this.raws.between;
  2052. };
  2053. _proto.positionInside = function positionInside(index) {
  2054. var string = this.toString();
  2055. var column = this.source.start.column;
  2056. var line = this.source.start.line;
  2057. for (var i = 0; i < index; i++) {
  2058. if (string[i] === '\n') {
  2059. column = 1;
  2060. line += 1;
  2061. } else {
  2062. column += 1;
  2063. }
  2064. }
  2065. return {
  2066. line: line,
  2067. column: column
  2068. };
  2069. };
  2070. _proto.positionBy = function positionBy(opts) {
  2071. var pos = this.source.start;
  2072. if (opts.index) {
  2073. pos = this.positionInside(opts.index);
  2074. } else if (opts.word) {
  2075. var index = this.toString().indexOf(opts.word);
  2076. if (index !== -1) pos = this.positionInside(index);
  2077. }
  2078. return pos;
  2079. };
  2080. _proto.removeSelf = function removeSelf() {
  2081. warnOnce('Node#removeSelf is deprecated. Use Node#remove.');
  2082. return this.remove();
  2083. };
  2084. _proto.replace = function replace(nodes) {
  2085. warnOnce('Node#replace is deprecated. Use Node#replaceWith');
  2086. return this.replaceWith(nodes);
  2087. };
  2088. _proto.style = function style(own, detect) {
  2089. warnOnce('Node#style() is deprecated. Use Node#raw()');
  2090. return this.raw(own, detect);
  2091. };
  2092. _proto.cleanStyles = function cleanStyles(keepBetween) {
  2093. warnOnce('Node#cleanStyles() is deprecated. Use Node#cleanRaws()');
  2094. return this.cleanRaws(keepBetween);
  2095. };
  2096. _createClass(Node, [{
  2097. key: "before",
  2098. get: function get() {
  2099. warnOnce('Node#before is deprecated. Use Node#raws.before');
  2100. return this.raws.before;
  2101. },
  2102. set: function set(val) {
  2103. warnOnce('Node#before is deprecated. Use Node#raws.before');
  2104. this.raws.before = val;
  2105. }
  2106. }, {
  2107. key: "between",
  2108. get: function get() {
  2109. warnOnce('Node#between is deprecated. Use Node#raws.between');
  2110. return this.raws.between;
  2111. },
  2112. set: function set(val) {
  2113. warnOnce('Node#between is deprecated. Use Node#raws.between');
  2114. this.raws.between = val;
  2115. }
  2116. /**
  2117. * @memberof Node#
  2118. * @member {string} type - String representing the node’s type.
  2119. * Possible values are `root`, `atrule`, `rule`,
  2120. * `decl`, or `comment`.
  2121. *
  2122. * @example
  2123. * postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl'
  2124. */
  2125. /**
  2126. * @memberof Node#
  2127. * @member {Container} parent - the node’s parent node.
  2128. *
  2129. * @example
  2130. * root.nodes[0].parent == root;
  2131. */
  2132. /**
  2133. * @memberof Node#
  2134. * @member {source} source - the input source of the node
  2135. *
  2136. * The property is used in source map generation.
  2137. *
  2138. * If you create a node manually (e.g., with `postcss.decl()`),
  2139. * that node will not have a `source` property and will be absent
  2140. * from the source map. For this reason, the plugin developer should
  2141. * consider cloning nodes to create new ones (in which case the new node’s
  2142. * source will reference the original, cloned node) or setting
  2143. * the `source` property manually.
  2144. *
  2145. * ```js
  2146. * // Bad
  2147. * const prefixed = postcss.decl({
  2148. * prop: '-moz-' + decl.prop,
  2149. * value: decl.value
  2150. * });
  2151. *
  2152. * // Good
  2153. * const prefixed = decl.clone({ prop: '-moz-' + decl.prop });
  2154. * ```
  2155. *
  2156. * ```js
  2157. * if ( atrule.name == 'add-link' ) {
  2158. * const rule = postcss.rule({ selector: 'a', source: atrule.source });
  2159. * atrule.parent.insertBefore(atrule, rule);
  2160. * }
  2161. * ```
  2162. *
  2163. * @example
  2164. * decl.source.input.from //=> '/home/ai/a.sass'
  2165. * decl.source.start //=> { line: 10, column: 2 }
  2166. * decl.source.end //=> { line: 10, column: 12 }
  2167. */
  2168. /**
  2169. * @memberof Node#
  2170. * @member {object} raws - Information to generate byte-to-byte equal
  2171. * node string as it was in the origin input.
  2172. *
  2173. * Every parser saves its own properties,
  2174. * but the default CSS parser uses:
  2175. *
  2176. * * `before`: the space symbols before the node. It also stores `*`
  2177. * and `_` symbols before the declaration (IE hack).
  2178. * * `after`: the space symbols after the last child of the node
  2179. * to the end of the node.
  2180. * * `between`: the symbols between the property and value
  2181. * for declarations, selector and `{` for rules, or last parameter
  2182. * and `{` for at-rules.
  2183. * * `semicolon`: contains true if the last child has
  2184. * an (optional) semicolon.
  2185. * * `afterName`: the space between the at-rule name and its parameters.
  2186. * * `left`: the space symbols between `/*` and the comment’s text.
  2187. * * `right`: the space symbols between the comment’s text
  2188. * and <code>*&#47;</code>.
  2189. * * `important`: the content of the important statement,
  2190. * if it is not just `!important`.
  2191. *
  2192. * PostCSS cleans selectors, declaration values and at-rule parameters
  2193. * from comments and extra spaces, but it stores origin content in raws
  2194. * properties. As such, if you don’t change a declaration’s value,
  2195. * PostCSS will use the raw value with comments.
  2196. *
  2197. * @example
  2198. * const root = postcss.parse('a {\n color:black\n}')
  2199. * root.first.first.raws //=> { before: '\n ', between: ':' }
  2200. */
  2201. }]);
  2202. return Node;
  2203. }();
  2204. /**
  2205. * Represents a CSS declaration.
  2206. *
  2207. * @extends Node
  2208. *
  2209. * @example
  2210. * const root = postcss.parse('a { color: black }');
  2211. * const decl = root.first.first;
  2212. * decl.type //=> 'decl'
  2213. * decl.toString() //=> ' color: black'
  2214. */
  2215. var Declaration =
  2216. /*#__PURE__*/
  2217. function (_Node) {
  2218. _inheritsLoose(Declaration, _Node);
  2219. function Declaration(defaults) {
  2220. var _this;
  2221. _this = _Node.call(this, defaults) || this;
  2222. _this.type = 'decl';
  2223. return _this;
  2224. }
  2225. _createClass(Declaration, [{
  2226. key: "_value",
  2227. get: function get() {
  2228. warnOnce('Node#_value was deprecated. Use Node#raws.value');
  2229. return this.raws.value;
  2230. },
  2231. set: function set(val) {
  2232. warnOnce('Node#_value was deprecated. Use Node#raws.value');
  2233. this.raws.value = val;
  2234. }
  2235. }, {
  2236. key: "_important",
  2237. get: function get() {
  2238. warnOnce('Node#_important was deprecated. Use Node#raws.important');
  2239. return this.raws.important;
  2240. },
  2241. set: function set(val) {
  2242. warnOnce('Node#_important was deprecated. Use Node#raws.important');
  2243. this.raws.important = val;
  2244. }
  2245. /**
  2246. * @memberof Declaration#
  2247. * @member {string} prop - the declaration’s property name
  2248. *
  2249. * @example
  2250. * const root = postcss.parse('a { color: black }');
  2251. * const decl = root.first.first;
  2252. * decl.prop //=> 'color'
  2253. */
  2254. /**
  2255. * @memberof Declaration#
  2256. * @member {string} value - the declaration’s value
  2257. *
  2258. * @example
  2259. * const root = postcss.parse('a { color: black }');
  2260. * const decl = root.first.first;
  2261. * decl.value //=> 'black'
  2262. */
  2263. /**
  2264. * @memberof Declaration#
  2265. * @member {boolean} important - `true` if the declaration
  2266. * has an !important annotation.
  2267. *
  2268. * @example
  2269. * const root = postcss.parse('a { color: black !important; color: red }');
  2270. * root.first.first.important //=> true
  2271. * root.first.last.important //=> undefined
  2272. */
  2273. /**
  2274. * @memberof Declaration#
  2275. * @member {object} raws - Information to generate byte-to-byte equal
  2276. * node string as it was in the origin input.
  2277. *
  2278. * Every parser saves its own properties,
  2279. * but the default CSS parser uses:
  2280. *
  2281. * * `before`: the space symbols before the node. It also stores `*`
  2282. * and `_` symbols before the declaration (IE hack).
  2283. * * `between`: the symbols between the property and value
  2284. * for declarations, selector and `{` for rules, or last parameter
  2285. * and `{` for at-rules.
  2286. * * `important`: the content of the important statement,
  2287. * if it is not just `!important`.
  2288. *
  2289. * PostCSS cleans declaration from comments and extra spaces,
  2290. * but it stores origin content in raws properties.
  2291. * As such, if you don’t change a declaration’s value,
  2292. * PostCSS will use the raw value with comments.
  2293. *
  2294. * @example
  2295. * const root = postcss.parse('a {\n color:black\n}')
  2296. * root.first.first.raws //=> { before: '\n ', between: ':' }
  2297. */
  2298. }]);
  2299. return Declaration;
  2300. }(Node);
  2301. /**
  2302. * Represents a comment between declarations or statements (rule and at-rules).
  2303. *
  2304. * Comments inside selectors, at-rule parameters, or declaration values
  2305. * will be stored in the `raws` properties explained above.
  2306. *
  2307. * @extends Node
  2308. */
  2309. var Comment =
  2310. /*#__PURE__*/
  2311. function (_Node) {
  2312. _inheritsLoose(Comment, _Node);
  2313. function Comment(defaults) {
  2314. var _this;
  2315. _this = _Node.call(this, defaults) || this;
  2316. _this.type = 'comment';
  2317. return _this;
  2318. }
  2319. _createClass(Comment, [{
  2320. key: "left",
  2321. get: function get() {
  2322. warnOnce('Comment#left was deprecated. Use Comment#raws.left');
  2323. return this.raws.left;
  2324. },
  2325. set: function set(val) {
  2326. warnOnce('Comment#left was deprecated. Use Comment#raws.left');
  2327. this.raws.left = val;
  2328. }
  2329. }, {
  2330. key: "right",
  2331. get: function get() {
  2332. warnOnce('Comment#right was deprecated. Use Comment#raws.right');
  2333. return this.raws.right;
  2334. },
  2335. set: function set(val) {
  2336. warnOnce('Comment#right was deprecated. Use Comment#raws.right');
  2337. this.raws.right = val;
  2338. }
  2339. /**
  2340. * @memberof Comment#
  2341. * @member {string} text - the comment’s text
  2342. */
  2343. /**
  2344. * @memberof Comment#
  2345. * @member {object} raws - Information to generate byte-to-byte equal
  2346. * node string as it was in the origin input.
  2347. *
  2348. * Every parser saves its own properties,
  2349. * but the default CSS parser uses:
  2350. *
  2351. * * `before`: the space symbols before the node.
  2352. * * `left`: the space symbols between `/*` and the comment’s text.
  2353. * * `right`: the space symbols between the comment’s text.
  2354. */
  2355. }]);
  2356. return Comment;
  2357. }(Node);
  2358. //
  2359. var Parser =
  2360. /*#__PURE__*/
  2361. function () {
  2362. function Parser(input) {
  2363. this.input = input;
  2364. this.pos = 0;
  2365. this.root = new Root();
  2366. this.current = this.root;
  2367. this.spaces = '';
  2368. this.semicolon = false;
  2369. this.root.source = {
  2370. input: input,
  2371. start: {
  2372. line: 1,
  2373. column: 1
  2374. }
  2375. };
  2376. }
  2377. var _proto = Parser.prototype;
  2378. _proto.tokenize = function tokenize$1() {
  2379. this.tokens = tokenize(this.input);
  2380. };
  2381. _proto.loop = function loop() {
  2382. var token;
  2383. while (this.pos < this.tokens.length) {
  2384. token = this.tokens[this.pos];
  2385. switch (token[0]) {
  2386. case 'space':
  2387. case ';':
  2388. this.spaces += token[1];
  2389. break;
  2390. case '}':
  2391. this.end(token);
  2392. break;
  2393. case 'comment':
  2394. this.comment(token);
  2395. break;
  2396. case 'at-word':
  2397. this.atrule(token);
  2398. break;
  2399. case '{':
  2400. this.emptyRule(token);
  2401. break;
  2402. default:
  2403. this.other();
  2404. break;
  2405. }
  2406. this.pos += 1;
  2407. }
  2408. this.endFile();
  2409. };
  2410. _proto.comment = function comment(token) {
  2411. var node = new Comment();
  2412. this.init(node, token[2], token[3]);
  2413. node.source.end = {
  2414. line: token[4],
  2415. column: token[5]
  2416. };
  2417. var text = token[1].slice(2, -2);
  2418. if (/^\s*$/.test(text)) {
  2419. node.text = '';
  2420. node.raws.left = text;
  2421. node.raws.right = '';
  2422. } else {
  2423. var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
  2424. node.text = match[2];
  2425. node.raws.left = match[1];
  2426. node.raws.right = match[3];
  2427. }
  2428. };
  2429. _proto.emptyRule = function emptyRule(token) {
  2430. var node = new Rule();
  2431. this.init(node, token[2], token[3]);
  2432. node.selector = '';
  2433. node.raws.between = '';
  2434. this.current = node;
  2435. };
  2436. _proto.other = function other() {
  2437. var token;
  2438. var end = false;
  2439. var type = null;
  2440. var colon = false;
  2441. var bracket = null;
  2442. var brackets = [];
  2443. var start = this.pos;
  2444. while (this.pos < this.tokens.length) {
  2445. token = this.tokens[this.pos];
  2446. type = token[0];
  2447. if (type === '(' || type === '[') {
  2448. if (!bracket) bracket = token;
  2449. brackets.push(type === '(' ? ')' : ']');
  2450. } else if (brackets.length === 0) {
  2451. if (type === ';') {
  2452. if (colon) {
  2453. this.decl(this.tokens.slice(start, this.pos + 1));
  2454. return;
  2455. } else {
  2456. break;
  2457. }
  2458. } else if (type === '{') {
  2459. this.rule(this.tokens.slice(start, this.pos + 1));
  2460. return;
  2461. } else if (type === '}') {
  2462. this.pos -= 1;
  2463. end = true;
  2464. break;
  2465. } else if (type === ':') {
  2466. colon = true;
  2467. }
  2468. } else if (type === brackets[brackets.length - 1]) {
  2469. brackets.pop();
  2470. if (brackets.length === 0) bracket = null;
  2471. }
  2472. this.pos += 1;
  2473. }
  2474. if (this.pos === this.tokens.length) {
  2475. this.pos -= 1;
  2476. end = true;
  2477. }
  2478. if (brackets.length > 0) this.unclosedBracket(bracket);
  2479. if (end && colon) {
  2480. while (this.pos > start) {
  2481. token = this.tokens[this.pos][0];
  2482. if (token !== 'space' && token !== 'comment') break;
  2483. this.pos -= 1;
  2484. }
  2485. this.decl(this.tokens.slice(start, this.pos + 1));
  2486. return;
  2487. }
  2488. this.unknownWord(start);
  2489. };
  2490. _proto.rule = function rule(tokens) {
  2491. tokens.pop();
  2492. var node = new Rule();
  2493. this.init(node, tokens[0][2], tokens[0][3]);
  2494. node.raws.between = this.spacesFromEnd(tokens);
  2495. this.raw(node, 'selector', tokens);
  2496. this.current = node;
  2497. };
  2498. _proto.decl = function decl(tokens) {
  2499. var node = new Declaration();
  2500. this.init(node);
  2501. var last = tokens[tokens.length - 1];
  2502. if (last[0] === ';') {
  2503. this.semicolon = true;
  2504. tokens.pop();
  2505. }
  2506. if (last[4]) {
  2507. node.source.end = {
  2508. line: last[4],
  2509. column: last[5]
  2510. };
  2511. } else {
  2512. node.source.end = {
  2513. line: last[2],
  2514. column: last[3]
  2515. };
  2516. }
  2517. while (tokens[0][0] !== 'word') {
  2518. node.raws.before += tokens.shift()[1];
  2519. }
  2520. node.source.start = {
  2521. line: tokens[0][2],
  2522. column: tokens[0][3]
  2523. };
  2524. node.prop = '';
  2525. while (tokens.length) {
  2526. var type = tokens[0][0];
  2527. if (type === ':' || type === 'space' || type === 'comment') {
  2528. break;
  2529. }
  2530. node.prop += tokens.shift()[1];
  2531. }
  2532. node.raws.between = '';
  2533. var token;
  2534. while (tokens.length) {
  2535. token = tokens.shift();
  2536. if (token[0] === ':') {
  2537. node.raws.between += token[1];
  2538. break;
  2539. } else {
  2540. node.raws.between += token[1];
  2541. }
  2542. }
  2543. if (node.prop[0] === '_' || node.prop[0] === '*') {
  2544. node.raws.before += node.prop[0];
  2545. node.prop = node.prop.slice(1);
  2546. }
  2547. node.raws.between += this.spacesFromStart(tokens);
  2548. this.precheckMissedSemicolon(tokens);
  2549. for (var i = tokens.length - 1; i > 0; i--) {
  2550. token = tokens[i];
  2551. if (token[1] === '!important') {
  2552. node.important = true;
  2553. var string = this.stringFrom(tokens, i);
  2554. string = this.spacesFromEnd(tokens) + string;
  2555. if (string !== ' !important') node.raws.important = string;
  2556. break;
  2557. } else if (token[1] === 'important') {
  2558. var cache = tokens.slice(0);
  2559. var str = '';
  2560. for (var j = i; j > 0; j--) {
  2561. var _type = cache[j][0];
  2562. if (str.trim().indexOf('!') === 0 && _type !== 'space') {
  2563. break;
  2564. }
  2565. str = cache.pop()[1] + str;
  2566. }
  2567. if (str.trim().indexOf('!') === 0) {
  2568. node.important = true;
  2569. node.raws.important = str;
  2570. tokens = cache;
  2571. }
  2572. }
  2573. if (token[0] !== 'space' && token[0] !== 'comment') {
  2574. break;
  2575. }
  2576. }
  2577. this.raw(node, 'value', tokens);
  2578. if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens);
  2579. };
  2580. _proto.atrule = function atrule(token) {
  2581. var node = new AtRule();
  2582. node.name = token[1].slice(1);
  2583. if (node.name === '') {
  2584. this.unnamedAtrule(node, token);
  2585. }
  2586. this.init(node, token[2], token[3]);
  2587. var last = false;
  2588. var open = false;
  2589. var params = [];
  2590. this.pos += 1;
  2591. while (this.pos < this.tokens.length) {
  2592. token = this.tokens[this.pos];
  2593. if (token[0] === ';') {
  2594. node.source.end = {
  2595. line: token[2],
  2596. column: token[3]
  2597. };
  2598. this.semicolon = true;
  2599. break;
  2600. } else if (token[0] === '{') {
  2601. open = true;
  2602. break;
  2603. } else if (token[0] === '}') {
  2604. this.end(token);
  2605. break;
  2606. } else {
  2607. params.push(token);
  2608. }
  2609. this.pos += 1;
  2610. }
  2611. if (this.pos === this.tokens.length) {
  2612. last = true;
  2613. }
  2614. node.raws.between = this.spacesFromEnd(params);
  2615. if (params.length) {
  2616. node.raws.afterName = this.spacesFromStart(params);
  2617. this.raw(node, 'params', params);
  2618. if (last) {
  2619. token = params[params.length - 1];
  2620. node.source.end = {
  2621. line: token[4],
  2622. column: token[5]
  2623. };
  2624. this.spaces = node.raws.between;
  2625. node.raws.between = '';
  2626. }
  2627. } else {
  2628. node.raws.afterName = '';
  2629. node.params = '';
  2630. }
  2631. if (open) {
  2632. node.nodes = [];
  2633. this.current = node;
  2634. }
  2635. };
  2636. _proto.end = function end(token) {
  2637. if (this.current.nodes && this.current.nodes.length) {
  2638. this.current.raws.semicolon = this.semicolon;
  2639. }
  2640. this.semicolon = false;
  2641. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  2642. this.spaces = '';
  2643. if (this.current.parent) {
  2644. this.current.source.end = {
  2645. line: token[2],
  2646. column: token[3]
  2647. };
  2648. this.current = this.current.parent;
  2649. } else {
  2650. this.unexpectedClose(token);
  2651. }
  2652. };
  2653. _proto.endFile = function endFile() {
  2654. if (this.current.parent) this.unclosedBlock();
  2655. if (this.current.nodes && this.current.nodes.length) {
  2656. this.current.raws.semicolon = this.semicolon;
  2657. }
  2658. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  2659. } // Helpers
  2660. ;
  2661. _proto.init = function init(node, line, column) {
  2662. this.current.push(node);
  2663. node.source = {
  2664. start: {
  2665. line: line,
  2666. column: column
  2667. },
  2668. input: this.input
  2669. };
  2670. node.raws.before = this.spaces;
  2671. this.spaces = '';
  2672. if (node.type !== 'comment') this.semicolon = false;
  2673. };
  2674. _proto.raw = function raw(node, prop, tokens) {
  2675. var token, type;
  2676. var length = tokens.length;
  2677. var value = '';
  2678. var clean = true;
  2679. for (var i = 0; i < length; i += 1) {
  2680. token = tokens[i];
  2681. type = token[0];
  2682. if (type === 'comment' || type === 'space' && i === length - 1) {
  2683. clean = false;
  2684. } else {
  2685. value += token[1];
  2686. }
  2687. }
  2688. if (!clean) {
  2689. var raw = tokens.reduce(function (all, i) {
  2690. return all + i[1];
  2691. }, '');
  2692. node.raws[prop] = {
  2693. value: value,
  2694. raw: raw
  2695. };
  2696. }
  2697. node[prop] = value;
  2698. };
  2699. _proto.spacesFromEnd = function spacesFromEnd(tokens) {
  2700. var lastTokenType;
  2701. var spaces = '';
  2702. while (tokens.length) {
  2703. lastTokenType = tokens[tokens.length - 1][0];
  2704. if (lastTokenType !== 'space' && lastTokenType !== 'comment') break;
  2705. spaces = tokens.pop()[1] + spaces;
  2706. }
  2707. return spaces;
  2708. };
  2709. _proto.spacesFromStart = function spacesFromStart(tokens) {
  2710. var next;
  2711. var spaces = '';
  2712. while (tokens.length) {
  2713. next = tokens[0][0];
  2714. if (next !== 'space' && next !== 'comment') break;
  2715. spaces += tokens.shift()[1];
  2716. }
  2717. return spaces;
  2718. };
  2719. _proto.stringFrom = function stringFrom(tokens, from) {
  2720. var result = '';
  2721. for (var i = from; i < tokens.length; i++) {
  2722. result += tokens[i][1];
  2723. }
  2724. tokens.splice(from, tokens.length - from);
  2725. return result;
  2726. };
  2727. _proto.colon = function colon(tokens) {
  2728. var brackets = 0;
  2729. var token, type, prev;
  2730. for (var i = 0; i < tokens.length; i++) {
  2731. token = tokens[i];
  2732. type = token[0];
  2733. if (type === '(') {
  2734. brackets += 1;
  2735. } else if (type === ')') {
  2736. brackets -= 1;
  2737. } else if (brackets === 0 && type === ':') {
  2738. if (!prev) {
  2739. this.doubleColon(token);
  2740. } else if (prev[0] === 'word' && prev[1] === 'progid') {
  2741. continue;
  2742. } else {
  2743. return i;
  2744. }
  2745. }
  2746. prev = token;
  2747. }
  2748. return false;
  2749. } // Errors
  2750. ;
  2751. _proto.unclosedBracket = function unclosedBracket(bracket) {
  2752. throw this.input.error('Unclosed bracket', bracket[2], bracket[3]);
  2753. };
  2754. _proto.unknownWord = function unknownWord(start) {
  2755. var token = this.tokens[start];
  2756. throw this.input.error('Unknown word', token[2], token[3]);
  2757. };
  2758. _proto.unexpectedClose = function unexpectedClose(token) {
  2759. throw this.input.error('Unexpected }', token[2], token[3]);
  2760. };
  2761. _proto.unclosedBlock = function unclosedBlock() {
  2762. var pos = this.current.source.start;
  2763. throw this.input.error('Unclosed block', pos.line, pos.column);
  2764. };
  2765. _proto.doubleColon = function doubleColon(token) {
  2766. throw this.input.error('Double colon', token[2], token[3]);
  2767. };
  2768. _proto.unnamedAtrule = function unnamedAtrule(node, token) {
  2769. throw this.input.error('At-rule without name', token[2], token[3]);
  2770. };
  2771. _proto.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
  2772. };
  2773. _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
  2774. var colon = this.colon(tokens);
  2775. if (colon === false) return;
  2776. var founded = 0;
  2777. var token;
  2778. for (var j = colon - 1; j >= 0; j--) {
  2779. token = tokens[j];
  2780. if (token[0] !== 'space') {
  2781. founded += 1;
  2782. if (founded === 2) break;
  2783. }
  2784. }
  2785. throw this.input.error('Missed semicolon', token[2], token[3]);
  2786. };
  2787. return Parser;
  2788. }();
  2789. //
  2790. function parse(css, opts) {
  2791. if (opts && opts.safe) {
  2792. throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
  2793. }
  2794. var input = new Input(css, opts);
  2795. var parser = new Parser(input);
  2796. try {
  2797. parser.tokenize();
  2798. parser.loop();
  2799. } catch (e) {
  2800. if (e.name === 'CssSyntaxError' && opts && opts.from) {
  2801. if (/\.scss$/i.test(opts.from)) {
  2802. e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
  2803. } else if (/\.less$/i.test(opts.from)) {
  2804. e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
  2805. }
  2806. }
  2807. throw e;
  2808. }
  2809. return parser.root;
  2810. }
  2811. function cleanSource(nodes) {
  2812. return nodes.map(function (i) {
  2813. if (i.nodes) i.nodes = cleanSource(i.nodes);
  2814. delete i.source;
  2815. return i;
  2816. });
  2817. }
  2818. /**
  2819. * @callback childCondition
  2820. * @param {Node} node - container child
  2821. * @param {number} index - child index
  2822. * @param {Node[]} nodes - all container children
  2823. * @return {boolean}
  2824. */
  2825. /**
  2826. * @callback childIterator
  2827. * @param {Node} node - container child
  2828. * @param {number} index - child index
  2829. * @return {false|undefined} returning `false` will break iteration
  2830. */
  2831. /**
  2832. * The {@link Root}, {@link AtRule}, and {@link Rule} container nodes
  2833. * inherit some common methods to help work with their children.
  2834. *
  2835. * Note that all containers can store any content. If you write a rule inside
  2836. * a rule, PostCSS will parse it.
  2837. *
  2838. * @extends Node
  2839. * @abstract
  2840. */
  2841. var Container =
  2842. /*#__PURE__*/
  2843. function (_Node) {
  2844. _inheritsLoose(Container, _Node);
  2845. function Container() {
  2846. return _Node.apply(this, arguments) || this;
  2847. }
  2848. var _proto = Container.prototype;
  2849. _proto.push = function push(child) {
  2850. child.parent = this;
  2851. this.nodes.push(child);
  2852. return this;
  2853. }
  2854. /**
  2855. * Iterates through the container’s immediate children,
  2856. * calling `callback` for each child.
  2857. *
  2858. * Returning `false` in the callback will break iteration.
  2859. *
  2860. * This method only iterates through the container’s immediate children.
  2861. * If you need to recursively iterate through all the container’s descendant
  2862. * nodes, use {@link Container#walk}.
  2863. *
  2864. * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
  2865. * if you are mutating the array of child nodes during iteration.
  2866. * PostCSS will adjust the current index to match the mutations.
  2867. *
  2868. * @param {childIterator} callback - iterator receives each node and index
  2869. *
  2870. * @return {false|undefined} returns `false` if iteration was broke
  2871. *
  2872. * @example
  2873. * const root = postcss.parse('a { color: black; z-index: 1 }');
  2874. * const rule = root.first;
  2875. *
  2876. * for ( let decl of rule.nodes ) {
  2877. * decl.cloneBefore({ prop: '-webkit-' + decl.prop });
  2878. * // Cycle will be infinite, because cloneBefore moves the current node
  2879. * // to the next index
  2880. * }
  2881. *
  2882. * rule.each(decl => {
  2883. * decl.cloneBefore({ prop: '-webkit-' + decl.prop });
  2884. * // Will be executed only for color and z-index
  2885. * });
  2886. */
  2887. ;
  2888. _proto.each = function each(callback) {
  2889. if (!this.lastEach) this.lastEach = 0;
  2890. if (!this.indexes) this.indexes = {};
  2891. this.lastEach += 1;
  2892. var id = this.lastEach;
  2893. this.indexes[id] = 0;
  2894. if (!this.nodes) return undefined;
  2895. var index, result;
  2896. while (this.indexes[id] < this.nodes.length) {
  2897. index = this.indexes[id];
  2898. result = callback(this.nodes[index], index);
  2899. if (result === false) break;
  2900. this.indexes[id] += 1;
  2901. }
  2902. delete this.indexes[id];
  2903. return result;
  2904. }
  2905. /**
  2906. * Traverses the container’s descendant nodes, calling callback
  2907. * for each node.
  2908. *
  2909. * Like container.each(), this method is safe to use
  2910. * if you are mutating arrays during iteration.
  2911. *
  2912. * If you only need to iterate through the container’s immediate children,
  2913. * use {@link Container#each}.
  2914. *
  2915. * @param {childIterator} callback - iterator receives each node and index
  2916. *
  2917. * @return {false|undefined} returns `false` if iteration was broke
  2918. *
  2919. * @example
  2920. * root.walk(node => {
  2921. * // Traverses all descendant nodes.
  2922. * });
  2923. */
  2924. ;
  2925. _proto.walk = function walk(callback) {
  2926. return this.each(function (child, i) {
  2927. var result = callback(child, i);
  2928. if (result !== false && child.walk) {
  2929. result = child.walk(callback);
  2930. }
  2931. return result;
  2932. });
  2933. }
  2934. /**
  2935. * Traverses the container’s descendant nodes, calling callback
  2936. * for each declaration node.
  2937. *
  2938. * If you pass a filter, iteration will only happen over declarations
  2939. * with matching properties.
  2940. *
  2941. * Like {@link Container#each}, this method is safe
  2942. * to use if you are mutating arrays during iteration.
  2943. *
  2944. * @param {string|RegExp} [prop] - string or regular expression
  2945. * to filter declarations by property name
  2946. * @param {childIterator} callback - iterator receives each node and index
  2947. *
  2948. * @return {false|undefined} returns `false` if iteration was broke
  2949. *
  2950. * @example
  2951. * root.walkDecls(decl => {
  2952. * checkPropertySupport(decl.prop);
  2953. * });
  2954. *
  2955. * root.walkDecls('border-radius', decl => {
  2956. * decl.remove();
  2957. * });
  2958. *
  2959. * root.walkDecls(/^background/, decl => {
  2960. * decl.value = takeFirstColorFromGradient(decl.value);
  2961. * });
  2962. */
  2963. ;
  2964. _proto.walkDecls = function walkDecls(prop, callback) {
  2965. if (!callback) {
  2966. callback = prop;
  2967. return this.walk(function (child, i) {
  2968. if (child.type === 'decl') {
  2969. return callback(child, i);
  2970. }
  2971. });
  2972. } else if (prop instanceof RegExp) {
  2973. return this.walk(function (child, i) {
  2974. if (child.type === 'decl' && prop.test(child.prop)) {
  2975. return callback(child, i);
  2976. }
  2977. });
  2978. } else {
  2979. return this.walk(function (child, i) {
  2980. if (child.type === 'decl' && child.prop === prop) {
  2981. return callback(child, i);
  2982. }
  2983. });
  2984. }
  2985. }
  2986. /**
  2987. * Traverses the container’s descendant nodes, calling callback
  2988. * for each rule node.
  2989. *
  2990. * If you pass a filter, iteration will only happen over rules
  2991. * with matching selectors.
  2992. *
  2993. * Like {@link Container#each}, this method is safe
  2994. * to use if you are mutating arrays during iteration.
  2995. *
  2996. * @param {string|RegExp} [selector] - string or regular expression
  2997. * to filter rules by selector
  2998. * @param {childIterator} callback - iterator receives each node and index
  2999. *
  3000. * @return {false|undefined} returns `false` if iteration was broke
  3001. *
  3002. * @example
  3003. * const selectors = [];
  3004. * root.walkRules(rule => {
  3005. * selectors.push(rule.selector);
  3006. * });
  3007. * console.log(`Your CSS uses ${selectors.length} selectors`);
  3008. */
  3009. ;
  3010. _proto.walkRules = function walkRules(selector, callback) {
  3011. if (!callback) {
  3012. callback = selector;
  3013. return this.walk(function (child, i) {
  3014. if (child.type === 'rule') {
  3015. return callback(child, i);
  3016. }
  3017. });
  3018. } else if (selector instanceof RegExp) {
  3019. return this.walk(function (child, i) {
  3020. if (child.type === 'rule' && selector.test(child.selector)) {
  3021. return callback(child, i);
  3022. }
  3023. });
  3024. } else {
  3025. return this.walk(function (child, i) {
  3026. if (child.type === 'rule' && child.selector === selector) {
  3027. return callback(child, i);
  3028. }
  3029. });
  3030. }
  3031. }
  3032. /**
  3033. * Traverses the container’s descendant nodes, calling callback
  3034. * for each at-rule node.
  3035. *
  3036. * If you pass a filter, iteration will only happen over at-rules
  3037. * that have matching names.
  3038. *
  3039. * Like {@link Container#each}, this method is safe
  3040. * to use if you are mutating arrays during iteration.
  3041. *
  3042. * @param {string|RegExp} [name] - string or regular expression
  3043. * to filter at-rules by name
  3044. * @param {childIterator} callback - iterator receives each node and index
  3045. *
  3046. * @return {false|undefined} returns `false` if iteration was broke
  3047. *
  3048. * @example
  3049. * root.walkAtRules(rule => {
  3050. * if ( isOld(rule.name) ) rule.remove();
  3051. * });
  3052. *
  3053. * let first = false;
  3054. * root.walkAtRules('charset', rule => {
  3055. * if ( !first ) {
  3056. * first = true;
  3057. * } else {
  3058. * rule.remove();
  3059. * }
  3060. * });
  3061. */
  3062. ;
  3063. _proto.walkAtRules = function walkAtRules(name, callback) {
  3064. if (!callback) {
  3065. callback = name;
  3066. return this.walk(function (child, i) {
  3067. if (child.type === 'atrule') {
  3068. return callback(child, i);
  3069. }
  3070. });
  3071. } else if (name instanceof RegExp) {
  3072. return this.walk(function (child, i) {
  3073. if (child.type === 'atrule' && name.test(child.name)) {
  3074. return callback(child, i);
  3075. }
  3076. });
  3077. } else {
  3078. return this.walk(function (child, i) {
  3079. if (child.type === 'atrule' && child.name === name) {
  3080. return callback(child, i);
  3081. }
  3082. });
  3083. }
  3084. }
  3085. /**
  3086. * Traverses the container’s descendant nodes, calling callback
  3087. * for each comment node.
  3088. *
  3089. * Like {@link Container#each}, this method is safe
  3090. * to use if you are mutating arrays during iteration.
  3091. *
  3092. * @param {childIterator} callback - iterator receives each node and index
  3093. *
  3094. * @return {false|undefined} returns `false` if iteration was broke
  3095. *
  3096. * @example
  3097. * root.walkComments(comment => {
  3098. * comment.remove();
  3099. * });
  3100. */
  3101. ;
  3102. _proto.walkComments = function walkComments(callback) {
  3103. return this.walk(function (child, i) {
  3104. if (child.type === 'comment') {
  3105. return callback(child, i);
  3106. }
  3107. });
  3108. }
  3109. /**
  3110. * Inserts new nodes to the start of the container.
  3111. *
  3112. * @param {...(Node|object|string|Node[])} children - new nodes
  3113. *
  3114. * @return {Node} this node for methods chain
  3115. *
  3116. * @example
  3117. * const decl1 = postcss.decl({ prop: 'color', value: 'black' });
  3118. * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
  3119. * rule.append(decl1, decl2);
  3120. *
  3121. * root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
  3122. * root.append({ selector: 'a' }); // rule
  3123. * rule.append({ prop: 'color', value: 'black' }); // declaration
  3124. * rule.append({ text: 'Comment' }) // comment
  3125. *
  3126. * root.append('a {}');
  3127. * root.first.append('color: black; z-index: 1');
  3128. */
  3129. ;
  3130. _proto.append = function append() {
  3131. var _this = this;
  3132. for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) {
  3133. children[_key] = arguments[_key];
  3134. }
  3135. children.forEach(function (child) {
  3136. var nodes = _this.normalize(child, _this.last);
  3137. nodes.forEach(function (node) {
  3138. return _this.nodes.push(node);
  3139. });
  3140. });
  3141. return this;
  3142. }
  3143. /**
  3144. * Inserts new nodes to the end of the container.
  3145. *
  3146. * @param {...(Node|object|string|Node[])} children - new nodes
  3147. *
  3148. * @return {Node} this node for methods chain
  3149. *
  3150. * @example
  3151. * const decl1 = postcss.decl({ prop: 'color', value: 'black' });
  3152. * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
  3153. * rule.prepend(decl1, decl2);
  3154. *
  3155. * root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
  3156. * root.append({ selector: 'a' }); // rule
  3157. * rule.append({ prop: 'color', value: 'black' }); // declaration
  3158. * rule.append({ text: 'Comment' }) // comment
  3159. *
  3160. * root.append('a {}');
  3161. * root.first.append('color: black; z-index: 1');
  3162. */
  3163. ;
  3164. _proto.prepend = function prepend() {
  3165. var _this2 = this;
  3166. for (var _len2 = arguments.length, children = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  3167. children[_key2] = arguments[_key2];
  3168. }
  3169. children = children.reverse();
  3170. children.forEach(function (child) {
  3171. var nodes = _this2.normalize(child, _this2.first, 'prepend').reverse();
  3172. nodes.forEach(function (node) {
  3173. return _this2.nodes.unshift(node);
  3174. });
  3175. for (var id in _this2.indexes) {
  3176. _this2.indexes[id] = _this2.indexes[id] + nodes.length;
  3177. }
  3178. });
  3179. return this;
  3180. };
  3181. _proto.cleanRaws = function cleanRaws(keepBetween) {
  3182. _Node.prototype.cleanRaws.call(this, keepBetween);
  3183. if (this.nodes) {
  3184. this.nodes.forEach(function (node) {
  3185. return node.cleanRaws(keepBetween);
  3186. });
  3187. }
  3188. }
  3189. /**
  3190. * Insert new node before old node within the container.
  3191. *
  3192. * @param {Node|number} exist - child or child’s index.
  3193. * @param {Node|object|string|Node[]} add - new node
  3194. *
  3195. * @return {Node} this node for methods chain
  3196. *
  3197. * @example
  3198. * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }));
  3199. */
  3200. ;
  3201. _proto.insertBefore = function insertBefore(exist, add) {
  3202. var _this3 = this;
  3203. exist = this.index(exist);
  3204. var type = exist === 0 ? 'prepend' : false;
  3205. var nodes = this.normalize(add, this.nodes[exist], type).reverse();
  3206. nodes.forEach(function (node) {
  3207. return _this3.nodes.splice(exist, 0, node);
  3208. });
  3209. var index;
  3210. for (var id in this.indexes) {
  3211. index = this.indexes[id];
  3212. if (exist <= index) {
  3213. this.indexes[id] = index + nodes.length;
  3214. }
  3215. }
  3216. return this;
  3217. }
  3218. /**
  3219. * Insert new node after old node within the container.
  3220. *
  3221. * @param {Node|number} exist - child or child’s index
  3222. * @param {Node|object|string|Node[]} add - new node
  3223. *
  3224. * @return {Node} this node for methods chain
  3225. */
  3226. ;
  3227. _proto.insertAfter = function insertAfter(exist, add) {
  3228. var _this4 = this;
  3229. exist = this.index(exist);
  3230. var nodes = this.normalize(add, this.nodes[exist]).reverse();
  3231. nodes.forEach(function (node) {
  3232. return _this4.nodes.splice(exist + 1, 0, node);
  3233. });
  3234. var index;
  3235. for (var id in this.indexes) {
  3236. index = this.indexes[id];
  3237. if (exist < index) {
  3238. this.indexes[id] = index + nodes.length;
  3239. }
  3240. }
  3241. return this;
  3242. };
  3243. _proto.remove = function remove(child) {
  3244. if (typeof child !== 'undefined') {
  3245. warnOnce('Container#remove is deprecated. ' + 'Use Container#removeChild');
  3246. this.removeChild(child);
  3247. } else {
  3248. _Node.prototype.remove.call(this);
  3249. }
  3250. return this;
  3251. }
  3252. /**
  3253. * Removes node from the container and cleans the parent properties
  3254. * from the node and its children.
  3255. *
  3256. * @param {Node|number} child - child or child’s index
  3257. *
  3258. * @return {Node} this node for methods chain
  3259. *
  3260. * @example
  3261. * rule.nodes.length //=> 5
  3262. * rule.removeChild(decl);
  3263. * rule.nodes.length //=> 4
  3264. * decl.parent //=> undefined
  3265. */
  3266. ;
  3267. _proto.removeChild = function removeChild(child) {
  3268. child = this.index(child);
  3269. this.nodes[child].parent = undefined;
  3270. this.nodes.splice(child, 1);
  3271. var index;
  3272. for (var id in this.indexes) {
  3273. index = this.indexes[id];
  3274. if (index >= child) {
  3275. this.indexes[id] = index - 1;
  3276. }
  3277. }
  3278. return this;
  3279. }
  3280. /**
  3281. * Removes all children from the container
  3282. * and cleans their parent properties.
  3283. *
  3284. * @return {Node} this node for methods chain
  3285. *
  3286. * @example
  3287. * rule.removeAll();
  3288. * rule.nodes.length //=> 0
  3289. */
  3290. ;
  3291. _proto.removeAll = function removeAll() {
  3292. this.nodes.forEach(function (node) {
  3293. return node.parent = undefined;
  3294. });
  3295. this.nodes = [];
  3296. return this;
  3297. }
  3298. /**
  3299. * Passes all declaration values within the container that match pattern
  3300. * through callback, replacing those values with the returned result
  3301. * of callback.
  3302. *
  3303. * This method is useful if you are using a custom unit or function
  3304. * and need to iterate through all values.
  3305. *
  3306. * @param {string|RegExp} pattern - replace pattern
  3307. * @param {object} opts - options to speed up the search
  3308. * @param {string|string[]} opts.props - an array of property names
  3309. * @param {string} opts.fast - string that’s used
  3310. * to narrow down values and speed up
  3311. the regexp search
  3312. * @param {function|string} callback - string to replace pattern
  3313. * or callback that returns a new
  3314. * value.
  3315. * The callback will receive
  3316. * the same arguments as those
  3317. * passed to a function parameter
  3318. * of `String#replace`.
  3319. *
  3320. * @return {Node} this node for methods chain
  3321. *
  3322. * @example
  3323. * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
  3324. * return 15 * parseInt(string) + 'px';
  3325. * });
  3326. */
  3327. ;
  3328. _proto.replaceValues = function replaceValues(pattern, opts, callback) {
  3329. if (!callback) {
  3330. callback = opts;
  3331. opts = {};
  3332. }
  3333. this.walkDecls(function (decl) {
  3334. if (opts.props && opts.props.indexOf(decl.prop) === -1) return;
  3335. if (opts.fast && decl.value.indexOf(opts.fast) === -1) return;
  3336. decl.value = decl.value.replace(pattern, callback);
  3337. });
  3338. return this;
  3339. }
  3340. /**
  3341. * Returns `true` if callback returns `true`
  3342. * for all of the container’s children.
  3343. *
  3344. * @param {childCondition} condition - iterator returns true or false.
  3345. *
  3346. * @return {boolean} is every child pass condition
  3347. *
  3348. * @example
  3349. * const noPrefixes = rule.every(i => i.prop[0] !== '-');
  3350. */
  3351. ;
  3352. _proto.every = function every(condition) {
  3353. return this.nodes.every(condition);
  3354. }
  3355. /**
  3356. * Returns `true` if callback returns `true` for (at least) one
  3357. * of the container’s children.
  3358. *
  3359. * @param {childCondition} condition - iterator returns true or false.
  3360. *
  3361. * @return {boolean} is some child pass condition
  3362. *
  3363. * @example
  3364. * const hasPrefix = rule.some(i => i.prop[0] === '-');
  3365. */
  3366. ;
  3367. _proto.some = function some(condition) {
  3368. return this.nodes.some(condition);
  3369. }
  3370. /**
  3371. * Returns a `child`’s index within the {@link Container#nodes} array.
  3372. *
  3373. * @param {Node} child - child of the current container.
  3374. *
  3375. * @return {number} child index
  3376. *
  3377. * @example
  3378. * rule.index( rule.nodes[2] ) //=> 2
  3379. */
  3380. ;
  3381. _proto.index = function index(child) {
  3382. if (typeof child === 'number') {
  3383. return child;
  3384. } else {
  3385. return this.nodes.indexOf(child);
  3386. }
  3387. }
  3388. /**
  3389. * The container’s first child.
  3390. *
  3391. * @type {Node}
  3392. *
  3393. * @example
  3394. * rule.first == rules.nodes[0];
  3395. */
  3396. ;
  3397. _proto.normalize = function normalize(nodes, sample) {
  3398. var _this5 = this;
  3399. if (typeof nodes === 'string') {
  3400. nodes = cleanSource(parse(nodes).nodes);
  3401. } else if (!Array.isArray(nodes)) {
  3402. if (nodes.type === 'root') {
  3403. nodes = nodes.nodes;
  3404. } else if (nodes.type) {
  3405. nodes = [nodes];
  3406. } else if (nodes.prop) {
  3407. if (typeof nodes.value === 'undefined') {
  3408. throw new Error('Value field is missed in node creation');
  3409. } else if (typeof nodes.value !== 'string') {
  3410. nodes.value = String(nodes.value);
  3411. }
  3412. nodes = [new Declaration(nodes)];
  3413. } else if (nodes.selector) {
  3414. nodes = [new Rule(nodes)];
  3415. } else if (nodes.name) {
  3416. nodes = [new AtRule(nodes)];
  3417. } else if (nodes.text) {
  3418. nodes = [new Comment(nodes)];
  3419. } else {
  3420. throw new Error('Unknown node type in node creation');
  3421. }
  3422. }
  3423. var processed = nodes.map(function (i) {
  3424. if (typeof i.raws === 'undefined') i = _this5.rebuild(i);
  3425. if (i.parent) i = i.clone();
  3426. if (typeof i.raws.before === 'undefined') {
  3427. if (sample && typeof sample.raws.before !== 'undefined') {
  3428. i.raws.before = sample.raws.before.replace(/[^\s]/g, '');
  3429. }
  3430. }
  3431. i.parent = _this5;
  3432. return i;
  3433. });
  3434. return processed;
  3435. };
  3436. _proto.rebuild = function rebuild(node, parent) {
  3437. var _this6 = this;
  3438. var fix;
  3439. if (node.type === 'root') {
  3440. fix = new Root();
  3441. } else if (node.type === 'atrule') {
  3442. fix = new AtRule();
  3443. } else if (node.type === 'rule') {
  3444. fix = new Rule();
  3445. } else if (node.type === 'decl') {
  3446. fix = new Declaration();
  3447. } else if (node.type === 'comment') {
  3448. fix = new Comment();
  3449. }
  3450. for (var i in node) {
  3451. if (i === 'nodes') {
  3452. fix.nodes = node.nodes.map(function (j) {
  3453. return _this6.rebuild(j, fix);
  3454. });
  3455. } else if (i === 'parent' && parent) {
  3456. fix.parent = parent;
  3457. } else if (node.hasOwnProperty(i)) {
  3458. fix[i] = node[i];
  3459. }
  3460. }
  3461. return fix;
  3462. };
  3463. _proto.eachInside = function eachInside(callback) {
  3464. warnOnce('Container#eachInside is deprecated. ' + 'Use Container#walk instead.');
  3465. return this.walk(callback);
  3466. };
  3467. _proto.eachDecl = function eachDecl(prop, callback) {
  3468. warnOnce('Container#eachDecl is deprecated. ' + 'Use Container#walkDecls instead.');
  3469. return this.walkDecls(prop, callback);
  3470. };
  3471. _proto.eachRule = function eachRule(selector, callback) {
  3472. warnOnce('Container#eachRule is deprecated. ' + 'Use Container#walkRules instead.');
  3473. return this.walkRules(selector, callback);
  3474. };
  3475. _proto.eachAtRule = function eachAtRule(name, callback) {
  3476. warnOnce('Container#eachAtRule is deprecated. ' + 'Use Container#walkAtRules instead.');
  3477. return this.walkAtRules(name, callback);
  3478. };
  3479. _proto.eachComment = function eachComment(callback) {
  3480. warnOnce('Container#eachComment is deprecated. ' + 'Use Container#walkComments instead.');
  3481. return this.walkComments(callback);
  3482. };
  3483. _createClass(Container, [{
  3484. key: "first",
  3485. get: function get() {
  3486. if (!this.nodes) return undefined;
  3487. return this.nodes[0];
  3488. }
  3489. /**
  3490. * The container’s last child.
  3491. *
  3492. * @type {Node}
  3493. *
  3494. * @example
  3495. * rule.last == rule.nodes[rule.nodes.length - 1];
  3496. */
  3497. }, {
  3498. key: "last",
  3499. get: function get() {
  3500. if (!this.nodes) return undefined;
  3501. return this.nodes[this.nodes.length - 1];
  3502. }
  3503. }, {
  3504. key: "semicolon",
  3505. get: function get() {
  3506. warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
  3507. return this.raws.semicolon;
  3508. },
  3509. set: function set(val) {
  3510. warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
  3511. this.raws.semicolon = val;
  3512. }
  3513. }, {
  3514. key: "after",
  3515. get: function get() {
  3516. warnOnce('Node#after is deprecated. Use Node#raws.after');
  3517. return this.raws.after;
  3518. },
  3519. set: function set(val) {
  3520. warnOnce('Node#after is deprecated. Use Node#raws.after');
  3521. this.raws.after = val;
  3522. }
  3523. /**
  3524. * @memberof Container#
  3525. * @member {Node[]} nodes - an array containing the container’s children
  3526. *
  3527. * @example
  3528. * const root = postcss.parse('a { color: black }');
  3529. * root.nodes.length //=> 1
  3530. * root.nodes[0].selector //=> 'a'
  3531. * root.nodes[0].nodes[0].prop //=> 'color'
  3532. */
  3533. }]);
  3534. return Container;
  3535. }(Node);
  3536. /**
  3537. * Represents an at-rule.
  3538. *
  3539. * If it’s followed in the CSS by a {} block, this node will have
  3540. * a nodes property representing its children.
  3541. *
  3542. * @extends Container
  3543. *
  3544. * @example
  3545. * const root = postcss.parse('@charset "UTF-8"; @media print {}');
  3546. *
  3547. * const charset = root.first;
  3548. * charset.type //=> 'atrule'
  3549. * charset.nodes //=> undefined
  3550. *
  3551. * const media = root.last;
  3552. * media.nodes //=> []
  3553. */
  3554. var AtRule =
  3555. /*#__PURE__*/
  3556. function (_Container) {
  3557. _inheritsLoose(AtRule, _Container);
  3558. function AtRule(defaults) {
  3559. var _this;
  3560. _this = _Container.call(this, defaults) || this;
  3561. _this.type = 'atrule';
  3562. return _this;
  3563. }
  3564. var _proto = AtRule.prototype;
  3565. _proto.append = function append() {
  3566. var _Container$prototype$;
  3567. if (!this.nodes) this.nodes = [];
  3568. for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) {
  3569. children[_key] = arguments[_key];
  3570. }
  3571. return (_Container$prototype$ = _Container.prototype.append).call.apply(_Container$prototype$, [this].concat(children));
  3572. };
  3573. _proto.prepend = function prepend() {
  3574. var _Container$prototype$2;
  3575. if (!this.nodes) this.nodes = [];
  3576. for (var _len2 = arguments.length, children = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  3577. children[_key2] = arguments[_key2];
  3578. }
  3579. return (_Container$prototype$2 = _Container.prototype.prepend).call.apply(_Container$prototype$2, [this].concat(children));
  3580. };
  3581. _createClass(AtRule, [{
  3582. key: "afterName",
  3583. get: function get() {
  3584. warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
  3585. return this.raws.afterName;
  3586. },
  3587. set: function set(val) {
  3588. warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
  3589. this.raws.afterName = val;
  3590. }
  3591. }, {
  3592. key: "_params",
  3593. get: function get() {
  3594. warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
  3595. return this.raws.params;
  3596. },
  3597. set: function set(val) {
  3598. warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
  3599. this.raws.params = val;
  3600. }
  3601. /**
  3602. * @memberof AtRule#
  3603. * @member {string} name - the at-rule’s name immediately follows the `@`
  3604. *
  3605. * @example
  3606. * const root = postcss.parse('@media print {}');
  3607. * media.name //=> 'media'
  3608. * const media = root.first;
  3609. */
  3610. /**
  3611. * @memberof AtRule#
  3612. * @member {string} params - the at-rule’s parameters, the values
  3613. * that follow the at-rule’s name but precede
  3614. * any {} block
  3615. *
  3616. * @example
  3617. * const root = postcss.parse('@media print, screen {}');
  3618. * const media = root.first;
  3619. * media.params //=> 'print, screen'
  3620. */
  3621. /**
  3622. * @memberof AtRule#
  3623. * @member {object} raws - Information to generate byte-to-byte equal
  3624. * node string as it was in the origin input.
  3625. *
  3626. * Every parser saves its own properties,
  3627. * but the default CSS parser uses:
  3628. *
  3629. * * `before`: the space symbols before the node. It also stores `*`
  3630. * and `_` symbols before the declaration (IE hack).
  3631. * * `after`: the space symbols after the last child of the node
  3632. * to the end of the node.
  3633. * * `between`: the symbols between the property and value
  3634. * for declarations, selector and `{` for rules, or last parameter
  3635. * and `{` for at-rules.
  3636. * * `semicolon`: contains true if the last child has
  3637. * an (optional) semicolon.
  3638. * * `afterName`: the space between the at-rule name and its parameters.
  3639. *
  3640. * PostCSS cleans at-rule parameters from comments and extra spaces,
  3641. * but it stores origin content in raws properties.
  3642. * As such, if you don’t change a declaration’s value,
  3643. * PostCSS will use the raw value with comments.
  3644. *
  3645. * @example
  3646. * const root = postcss.parse(' @media\nprint {\n}')
  3647. * root.first.first.raws //=> { before: ' ',
  3648. * // between: ' ',
  3649. * // afterName: '\n',
  3650. * // after: '\n' }
  3651. */
  3652. }]);
  3653. return AtRule;
  3654. }(Container);
  3655. //
  3656. /**
  3657. * Contains helpers for safely splitting lists of CSS values,
  3658. * preserving parentheses and quotes.
  3659. *
  3660. * @example
  3661. * const list = postcss.list;
  3662. *
  3663. * @namespace list
  3664. */
  3665. var list = {
  3666. split: function split(string, separators, last) {
  3667. var array = [];
  3668. var current = '';
  3669. var split = false;
  3670. var func = 0;
  3671. var quote = false;
  3672. var escape = false;
  3673. for (var i = 0; i < string.length; i++) {
  3674. var letter = string[i];
  3675. if (quote) {
  3676. if (escape) {
  3677. escape = false;
  3678. } else if (letter === '\\') {
  3679. escape = true;
  3680. } else if (letter === quote) {
  3681. quote = false;
  3682. }
  3683. } else if (letter === '"' || letter === "'") {
  3684. quote = letter;
  3685. } else if (letter === '(') {
  3686. func += 1;
  3687. } else if (letter === ')') {
  3688. if (func > 0) func -= 1;
  3689. } else if (func === 0) {
  3690. if (separators.indexOf(letter) !== -1) split = true;
  3691. }
  3692. if (split) {
  3693. if (current !== '') array.push(current.trim());
  3694. current = '';
  3695. split = false;
  3696. } else {
  3697. current += letter;
  3698. }
  3699. }
  3700. if (last || current !== '') array.push(current.trim());
  3701. return array;
  3702. },
  3703. /**
  3704. * Safely splits space-separated values (such as those for `background`,
  3705. * `border-radius`, and other shorthand properties).
  3706. *
  3707. * @param {string} string - space-separated values
  3708. *
  3709. * @return {string[]} splitted values
  3710. *
  3711. * @example
  3712. * postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
  3713. */
  3714. space: function space(string) {
  3715. var spaces = [' ', '\n', '\t'];
  3716. return list.split(string, spaces);
  3717. },
  3718. /**
  3719. * Safely splits comma-separated values (such as those for `transition-*`
  3720. * and `background` properties).
  3721. *
  3722. * @param {string} string - comma-separated values
  3723. *
  3724. * @return {string[]} splitted values
  3725. *
  3726. * @example
  3727. * postcss.list.comma('black, linear-gradient(white, black)')
  3728. * //=> ['black', 'linear-gradient(white, black)']
  3729. */
  3730. comma: function comma(string) {
  3731. var comma = ',';
  3732. return list.split(string, [comma], true);
  3733. }
  3734. };
  3735. /**
  3736. * Represents a CSS rule: a selector followed by a declaration block.
  3737. *
  3738. * @extends Container
  3739. *
  3740. * @example
  3741. * const root = postcss.parse('a{}');
  3742. * const rule = root.first;
  3743. * rule.type //=> 'rule'
  3744. * rule.toString() //=> 'a{}'
  3745. */
  3746. var Rule =
  3747. /*#__PURE__*/
  3748. function (_Container) {
  3749. _inheritsLoose(Rule, _Container);
  3750. function Rule(defaults) {
  3751. var _this;
  3752. _this = _Container.call(this, defaults) || this;
  3753. _this.type = 'rule';
  3754. if (!_this.nodes) _this.nodes = [];
  3755. return _this;
  3756. }
  3757. /**
  3758. * An array containing the rule’s individual selectors.
  3759. * Groups of selectors are split at commas.
  3760. *
  3761. * @type {string[]}
  3762. *
  3763. * @example
  3764. * const root = postcss.parse('a, b { }');
  3765. * const rule = root.first;
  3766. *
  3767. * rule.selector //=> 'a, b'
  3768. * rule.selectors //=> ['a', 'b']
  3769. *
  3770. * rule.selectors = ['a', 'strong'];
  3771. * rule.selector //=> 'a, strong'
  3772. */
  3773. _createClass(Rule, [{
  3774. key: "selectors",
  3775. get: function get() {
  3776. return list.comma(this.selector);
  3777. },
  3778. set: function set(values) {
  3779. var match = this.selector ? this.selector.match(/,\s*/) : null;
  3780. var sep = match ? match[0] : "," + this.raw('between', 'beforeOpen');
  3781. this.selector = values.join(sep);
  3782. }
  3783. }, {
  3784. key: "_selector",
  3785. get: function get() {
  3786. warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
  3787. return this.raws.selector;
  3788. },
  3789. set: function set(val) {
  3790. warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
  3791. this.raws.selector = val;
  3792. }
  3793. /**
  3794. * @memberof Rule#
  3795. * @member {string} selector - the rule’s full selector represented
  3796. * as a string
  3797. *
  3798. * @example
  3799. * const root = postcss.parse('a, b { }');
  3800. * const rule = root.first;
  3801. * rule.selector //=> 'a, b'
  3802. */
  3803. /**
  3804. * @memberof Rule#
  3805. * @member {object} raws - Information to generate byte-to-byte equal
  3806. * node string as it was in the origin input.
  3807. *
  3808. * Every parser saves its own properties,
  3809. * but the default CSS parser uses:
  3810. *
  3811. * * `before`: the space symbols before the node. It also stores `*`
  3812. * and `_` symbols before the declaration (IE hack).
  3813. * * `after`: the space symbols after the last child of the node
  3814. * to the end of the node.
  3815. * * `between`: the symbols between the property and value
  3816. * for declarations, selector and `{` for rules, or last parameter
  3817. * and `{` for at-rules.
  3818. * * `semicolon`: contains true if the last child has
  3819. * an (optional) semicolon.
  3820. *
  3821. * PostCSS cleans selectors from comments and extra spaces,
  3822. * but it stores origin content in raws properties.
  3823. * As such, if you don’t change a declaration’s value,
  3824. * PostCSS will use the raw value with comments.
  3825. *
  3826. * @example
  3827. * const root = postcss.parse('a {\n color:black\n}')
  3828. * root.first.first.raws //=> { before: '', between: ' ', after: '\n' }
  3829. */
  3830. }]);
  3831. return Rule;
  3832. }(Container);
  3833. //
  3834. /**
  3835. * Represents a plugin’s warning. It can be created using {@link Node#warn}.
  3836. *
  3837. * @example
  3838. * if ( decl.important ) {
  3839. * decl.warn(result, 'Avoid !important', { word: '!important' });
  3840. * }
  3841. */
  3842. var Warning =
  3843. /*#__PURE__*/
  3844. function () {
  3845. /**
  3846. * @param {string} text - warning message
  3847. * @param {Object} [opts] - warning options
  3848. * @param {Node} opts.node - CSS node that caused the warning
  3849. * @param {string} opts.word - word in CSS source that caused the warning
  3850. * @param {number} opts.index - index in CSS node string that caused
  3851. * the warning
  3852. * @param {string} opts.plugin - name of the plugin that created
  3853. * this warning. {@link Result#warn} fills
  3854. * this property automatically.
  3855. */
  3856. function Warning(text, opts) {
  3857. if (opts === void 0) {
  3858. opts = {};
  3859. }
  3860. /**
  3861. * @member {string} - Type to filter warnings from
  3862. * {@link Result#messages}. Always equal
  3863. * to `"warning"`.
  3864. *
  3865. * @example
  3866. * const nonWarning = result.messages.filter(i => i.type !== 'warning')
  3867. */
  3868. this.type = 'warning';
  3869. /**
  3870. * @member {string} - The warning message.
  3871. *
  3872. * @example
  3873. * warning.text //=> 'Try to avoid !important'
  3874. */
  3875. this.text = text;
  3876. if (opts.node && opts.node.source) {
  3877. var pos = opts.node.positionBy(opts);
  3878. /**
  3879. * @member {number} - Line in the input file
  3880. * with this warning’s source
  3881. *
  3882. * @example
  3883. * warning.line //=> 5
  3884. */
  3885. this.line = pos.line;
  3886. /**
  3887. * @member {number} - Column in the input file
  3888. * with this warning’s source.
  3889. *
  3890. * @example
  3891. * warning.column //=> 6
  3892. */
  3893. this.column = pos.column;
  3894. }
  3895. for (var opt in opts) {
  3896. this[opt] = opts[opt];
  3897. }
  3898. }
  3899. /**
  3900. * Returns a warning position and message.
  3901. *
  3902. * @example
  3903. * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
  3904. *
  3905. * @return {string} warning position and message
  3906. */
  3907. var _proto = Warning.prototype;
  3908. _proto.toString = function toString() {
  3909. if (this.node) {
  3910. return this.node.error(this.text, {
  3911. plugin: this.plugin,
  3912. index: this.index,
  3913. word: this.word
  3914. }).message;
  3915. } else if (this.plugin) {
  3916. return this.plugin + ": " + this.text;
  3917. } else {
  3918. return this.text;
  3919. }
  3920. }
  3921. /**
  3922. * @memberof Warning#
  3923. * @member {string} plugin - The name of the plugin that created
  3924. * it will fill this property automatically.
  3925. * this warning. When you call {@link Node#warn}
  3926. *
  3927. * @example
  3928. * warning.plugin //=> 'postcss-important'
  3929. */
  3930. /**
  3931. * @memberof Warning#
  3932. * @member {Node} node - Contains the CSS node that caused the warning.
  3933. *
  3934. * @example
  3935. * warning.node.toString() //=> 'color: white !important'
  3936. */
  3937. ;
  3938. return Warning;
  3939. }();
  3940. /**
  3941. * @typedef {object} Message
  3942. * @property {string} type - message type
  3943. * @property {string} plugin - source PostCSS plugin name
  3944. */
  3945. /**
  3946. * Provides the result of the PostCSS transformations.
  3947. *
  3948. * A Result instance is returned by {@link LazyResult#then}
  3949. * or {@link Root#toResult} methods.
  3950. *
  3951. * @example
  3952. * postcss([cssnext]).process(css).then(function (result) {
  3953. * console.log(result.css);
  3954. * });
  3955. *
  3956. * @example
  3957. * var result2 = postcss.parse(css).toResult();
  3958. */
  3959. var Result =
  3960. /*#__PURE__*/
  3961. function () {
  3962. /**
  3963. * @param {Processor} processor - processor used for this transformation.
  3964. * @param {Root} root - Root node after all transformations.
  3965. * @param {processOptions} opts - options from the {@link Processor#process}
  3966. * or {@link Root#toResult}
  3967. */
  3968. function Result(processor, root, opts) {
  3969. /**
  3970. * @member {Processor} - The Processor instance used
  3971. * for this transformation.
  3972. *
  3973. * @example
  3974. * for ( let plugin of result.processor.plugins) {
  3975. * if ( plugin.postcssPlugin === 'postcss-bad' ) {
  3976. * throw 'postcss-good is incompatible with postcss-bad';
  3977. * }
  3978. * });
  3979. */
  3980. this.processor = processor;
  3981. /**
  3982. * @member {Message[]} - Contains messages from plugins
  3983. * (e.g., warnings or custom messages).
  3984. * Each message should have type
  3985. * and plugin properties.
  3986. *
  3987. * @example
  3988. * postcss.plugin('postcss-min-browser', () => {
  3989. * return (root, result) => {
  3990. * var browsers = detectMinBrowsersByCanIUse(root);
  3991. * result.messages.push({
  3992. * type: 'min-browser',
  3993. * plugin: 'postcss-min-browser',
  3994. * browsers: browsers
  3995. * });
  3996. * };
  3997. * });
  3998. */
  3999. this.messages = [];
  4000. /**
  4001. * @member {Root} - Root node after all transformations.
  4002. *
  4003. * @example
  4004. * root.toResult().root == root;
  4005. */
  4006. this.root = root;
  4007. /**
  4008. * @member {processOptions} - Options from the {@link Processor#process}
  4009. * or {@link Root#toResult} call
  4010. * that produced this Result instance.
  4011. *
  4012. * @example
  4013. * root.toResult(opts).opts == opts;
  4014. */
  4015. this.opts = opts;
  4016. /**
  4017. * @member {string} - A CSS string representing of {@link Result#root}.
  4018. *
  4019. * @example
  4020. * postcss.parse('a{}').toResult().css //=> "a{}"
  4021. */
  4022. this.css = undefined;
  4023. /**
  4024. * @member {SourceMapGenerator} - An instance of `SourceMapGenerator`
  4025. * class from the `source-map` library,
  4026. * representing changes
  4027. * to the {@link Result#root} instance.
  4028. *
  4029. * @example
  4030. * result.map.toJSON() //=> { version: 3, file: 'a.css', … }
  4031. *
  4032. * @example
  4033. * if ( result.map ) {
  4034. * fs.writeFileSync(result.opts.to + '.map', result.map.toString());
  4035. * }
  4036. */
  4037. this.map = undefined;
  4038. }
  4039. /**
  4040. * Returns for @{link Result#css} content.
  4041. *
  4042. * @example
  4043. * result + '' === result.css
  4044. *
  4045. * @return {string} string representing of {@link Result#root}
  4046. */
  4047. var _proto = Result.prototype;
  4048. _proto.toString = function toString() {
  4049. return this.css;
  4050. }
  4051. /**
  4052. * Creates an instance of {@link Warning} and adds it
  4053. * to {@link Result#messages}.
  4054. *
  4055. * @param {string} text - warning message
  4056. * @param {Object} [opts] - warning options
  4057. * @param {Node} opts.node - CSS node that caused the warning
  4058. * @param {string} opts.word - word in CSS source that caused the warning
  4059. * @param {number} opts.index - index in CSS node string that caused
  4060. * the warning
  4061. * @param {string} opts.plugin - name of the plugin that created
  4062. * this warning. {@link Result#warn} fills
  4063. * this property automatically.
  4064. *
  4065. * @return {Warning} created warning
  4066. */
  4067. ;
  4068. _proto.warn = function warn(text, opts) {
  4069. if (opts === void 0) {
  4070. opts = {};
  4071. }
  4072. if (!opts.plugin) {
  4073. if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
  4074. opts.plugin = this.lastPlugin.postcssPlugin;
  4075. }
  4076. }
  4077. var warning = new Warning(text, opts);
  4078. this.messages.push(warning);
  4079. return warning;
  4080. }
  4081. /**
  4082. * Returns warnings from plugins. Filters {@link Warning} instances
  4083. * from {@link Result#messages}.
  4084. *
  4085. * @example
  4086. * result.warnings().forEach(warn => {
  4087. * console.warn(warn.toString());
  4088. * });
  4089. *
  4090. * @return {Warning[]} warnings from plugins
  4091. */
  4092. ;
  4093. _proto.warnings = function warnings() {
  4094. return this.messages.filter(function (i) {
  4095. return i.type === 'warning';
  4096. });
  4097. }
  4098. /**
  4099. * An alias for the {@link Result#css} property.
  4100. * Use it with syntaxes that generate non-CSS output.
  4101. * @type {string}
  4102. *
  4103. * @example
  4104. * result.css === result.content;
  4105. */
  4106. ;
  4107. _createClass(Result, [{
  4108. key: "content",
  4109. get: function get() {
  4110. return this.css;
  4111. }
  4112. }]);
  4113. return Result;
  4114. }();
  4115. function isPromise(obj) {
  4116. return typeof obj === 'object' && typeof obj.then === 'function';
  4117. }
  4118. /**
  4119. * @callback onFulfilled
  4120. * @param {Result} result
  4121. */
  4122. /**
  4123. * @callback onRejected
  4124. * @param {Error} error
  4125. */
  4126. /**
  4127. * A Promise proxy for the result of PostCSS transformations.
  4128. *
  4129. * A `LazyResult` instance is returned by {@link Processor#process}.
  4130. *
  4131. * @example
  4132. * const lazy = postcss([cssnext]).process(css);
  4133. */
  4134. var LazyResult =
  4135. /*#__PURE__*/
  4136. function () {
  4137. function LazyResult(processor, css, opts) {
  4138. this.stringified = false;
  4139. this.processed = false;
  4140. var root;
  4141. if (typeof css === 'object' && css.type === 'root') {
  4142. root = css;
  4143. } else if (css instanceof LazyResult || css instanceof Result) {
  4144. root = css.root;
  4145. if (css.map) {
  4146. if (typeof opts.map === 'undefined') opts.map = {};
  4147. if (!opts.map.inline) opts.map.inline = false;
  4148. opts.map.prev = css.map;
  4149. }
  4150. } else {
  4151. var parser = parse;
  4152. if (opts.syntax) parser = opts.syntax.parse;
  4153. if (opts.parser) parser = opts.parser;
  4154. if (parser.parse) parser = parser.parse;
  4155. try {
  4156. root = parser(css, opts);
  4157. } catch (error) {
  4158. this.error = error;
  4159. }
  4160. }
  4161. this.result = new Result(processor, root, opts);
  4162. }
  4163. /**
  4164. * Returns a {@link Processor} instance, which will be used
  4165. * for CSS transformations.
  4166. * @type {Processor}
  4167. */
  4168. var _proto = LazyResult.prototype;
  4169. /**
  4170. * Processes input CSS through synchronous plugins
  4171. * and calls {@link Result#warnings()}.
  4172. *
  4173. * @return {Warning[]} warnings from plugins
  4174. */
  4175. _proto.warnings = function warnings() {
  4176. return this.sync().warnings();
  4177. }
  4178. /**
  4179. * Alias for the {@link LazyResult#css} property.
  4180. *
  4181. * @example
  4182. * lazy + '' === lazy.css;
  4183. *
  4184. * @return {string} output CSS
  4185. */
  4186. ;
  4187. _proto.toString = function toString() {
  4188. return this.css;
  4189. }
  4190. /**
  4191. * Processes input CSS through synchronous and asynchronous plugins
  4192. * and calls `onFulfilled` with a Result instance. If a plugin throws
  4193. * an error, the `onRejected` callback will be executed.
  4194. *
  4195. * It implements standard Promise API.
  4196. *
  4197. * @param {onFulfilled} onFulfilled - callback will be executed
  4198. * when all plugins will finish work
  4199. * @param {onRejected} onRejected - callback will be execited on any error
  4200. *
  4201. * @return {Promise} Promise API to make queue
  4202. *
  4203. * @example
  4204. * postcss([cssnext]).process(css).then(result => {
  4205. * console.log(result.css);
  4206. * });
  4207. */
  4208. ;
  4209. _proto.then = function then(onFulfilled, onRejected) {
  4210. return this.async().then(onFulfilled, onRejected);
  4211. }
  4212. /**
  4213. * Processes input CSS through synchronous and asynchronous plugins
  4214. * and calls onRejected for each error thrown in any plugin.
  4215. *
  4216. * It implements standard Promise API.
  4217. *
  4218. * @param {onRejected} onRejected - callback will be execited on any error
  4219. *
  4220. * @return {Promise} Promise API to make queue
  4221. *
  4222. * @example
  4223. * postcss([cssnext]).process(css).then(result => {
  4224. * console.log(result.css);
  4225. * }).catch(error => {
  4226. * console.error(error);
  4227. * });
  4228. */
  4229. ;
  4230. _proto["catch"] = function _catch(onRejected) {
  4231. return this.async()["catch"](onRejected);
  4232. };
  4233. _proto.handleError = function handleError(error, plugin) {
  4234. try {
  4235. this.error = error;
  4236. if (error.name === 'CssSyntaxError' && !error.plugin) {
  4237. error.plugin = plugin.postcssPlugin;
  4238. error.setMessage();
  4239. } else if (plugin.postcssVersion) {
  4240. var pluginName = plugin.postcssPlugin;
  4241. var pluginVer = plugin.postcssVersion;
  4242. var runtimeVer = this.result.processor.version;
  4243. var a = pluginVer.split('.');
  4244. var b = runtimeVer.split('.');
  4245. if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
  4246. warnOnce("" + ('Your current PostCSS version ' + 'is ') + runtimeVer + ", but " + pluginName + " " + ("uses " + pluginVer + ". Perhaps this is ") + "the source of the error below.");
  4247. }
  4248. }
  4249. } catch (err) {
  4250. if (console && console.error) console.error(err);
  4251. }
  4252. };
  4253. _proto.asyncTick = function asyncTick(resolve, reject) {
  4254. var _this = this;
  4255. if (this.plugin >= this.processor.plugins.length) {
  4256. this.processed = true;
  4257. return resolve();
  4258. }
  4259. try {
  4260. var plugin = this.processor.plugins[this.plugin];
  4261. var promise = this.run(plugin);
  4262. this.plugin += 1;
  4263. if (isPromise(promise)) {
  4264. promise.then(function () {
  4265. _this.asyncTick(resolve, reject);
  4266. })["catch"](function (error) {
  4267. _this.handleError(error, plugin);
  4268. _this.processed = true;
  4269. reject(error);
  4270. });
  4271. } else {
  4272. this.asyncTick(resolve, reject);
  4273. }
  4274. } catch (error) {
  4275. this.processed = true;
  4276. reject(error);
  4277. }
  4278. };
  4279. _proto.async = function async() {
  4280. var _this2 = this;
  4281. if (this.processed) {
  4282. return new Promise(function (resolve, reject) {
  4283. if (_this2.error) {
  4284. reject(_this2.error);
  4285. } else {
  4286. resolve(_this2.stringify());
  4287. }
  4288. });
  4289. }
  4290. if (this.processing) {
  4291. return this.processing;
  4292. }
  4293. this.processing = new Promise(function (resolve, reject) {
  4294. if (_this2.error) return reject(_this2.error);
  4295. _this2.plugin = 0;
  4296. _this2.asyncTick(resolve, reject);
  4297. }).then(function () {
  4298. _this2.processed = true;
  4299. return _this2.stringify();
  4300. });
  4301. return this.processing;
  4302. };
  4303. _proto.sync = function sync() {
  4304. var _this3 = this;
  4305. if (this.processed) return this.result;
  4306. this.processed = true;
  4307. if (this.processing) {
  4308. throw new Error('Use process(css).then(cb) to work with async plugins');
  4309. }
  4310. if (this.error) throw this.error;
  4311. this.result.processor.plugins.forEach(function (plugin) {
  4312. var promise = _this3.run(plugin);
  4313. if (isPromise(promise)) {
  4314. throw new Error('Use process(css).then(cb) to work with async plugins');
  4315. }
  4316. });
  4317. return this.result;
  4318. };
  4319. _proto.run = function run(plugin) {
  4320. this.result.lastPlugin = plugin;
  4321. try {
  4322. return plugin(this.result.root, this.result);
  4323. } catch (error) {
  4324. this.handleError(error, plugin);
  4325. throw error;
  4326. }
  4327. };
  4328. _proto.stringify = function stringify$1() {
  4329. if (this.stringified) return this.result;
  4330. this.stringified = true;
  4331. this.sync();
  4332. var opts = this.result.opts;
  4333. var str = stringify;
  4334. if (opts.syntax) str = opts.syntax.stringify;
  4335. if (opts.stringifier) str = opts.stringifier;
  4336. if (str.stringify) str = str.stringify;
  4337. var result = '';
  4338. str(this.root, function (i) {
  4339. result += i;
  4340. });
  4341. this.result.css = result;
  4342. return this.result;
  4343. };
  4344. _createClass(LazyResult, [{
  4345. key: "processor",
  4346. get: function get() {
  4347. return this.result.processor;
  4348. }
  4349. /**
  4350. * Options from the {@link Processor#process} call.
  4351. * @type {processOptions}
  4352. */
  4353. }, {
  4354. key: "opts",
  4355. get: function get() {
  4356. return this.result.opts;
  4357. }
  4358. /**
  4359. * Processes input CSS through synchronous plugins, converts `Root`
  4360. * to a CSS string and returns {@link Result#css}.
  4361. *
  4362. * This property will only work with synchronous plugins.
  4363. * If the processor contains any asynchronous plugins
  4364. * it will throw an error. This is why this method is only
  4365. * for debug purpose, you should always use {@link LazyResult#then}.
  4366. *
  4367. * @type {string}
  4368. * @see Result#css
  4369. */
  4370. }, {
  4371. key: "css",
  4372. get: function get() {
  4373. return this.stringify().css;
  4374. }
  4375. /**
  4376. * An alias for the `css` property. Use it with syntaxes
  4377. * that generate non-CSS output.
  4378. *
  4379. * This property will only work with synchronous plugins.
  4380. * If the processor contains any asynchronous plugins
  4381. * it will throw an error. This is why this method is only
  4382. * for debug purpose, you should always use {@link LazyResult#then}.
  4383. *
  4384. * @type {string}
  4385. * @see Result#content
  4386. */
  4387. }, {
  4388. key: "content",
  4389. get: function get() {
  4390. return this.stringify().content;
  4391. }
  4392. /**
  4393. * Processes input CSS through synchronous plugins
  4394. * and returns {@link Result#map}.
  4395. *
  4396. * This property will only work with synchronous plugins.
  4397. * If the processor contains any asynchronous plugins
  4398. * it will throw an error. This is why this method is only
  4399. * for debug purpose, you should always use {@link LazyResult#then}.
  4400. *
  4401. * @type {SourceMapGenerator}
  4402. * @see Result#map
  4403. */
  4404. }, {
  4405. key: "map",
  4406. get: function get() {
  4407. return this.stringify().map;
  4408. }
  4409. /**
  4410. * Processes input CSS through synchronous plugins
  4411. * and returns {@link Result#root}.
  4412. *
  4413. * This property will only work with synchronous plugins. If the processor
  4414. * contains any asynchronous plugins it will throw an error.
  4415. *
  4416. * This is why this method is only for debug purpose,
  4417. * you should always use {@link LazyResult#then}.
  4418. *
  4419. * @type {Root}
  4420. * @see Result#root
  4421. */
  4422. }, {
  4423. key: "root",
  4424. get: function get() {
  4425. return this.sync().root;
  4426. }
  4427. /**
  4428. * Processes input CSS through synchronous plugins
  4429. * and returns {@link Result#messages}.
  4430. *
  4431. * This property will only work with synchronous plugins. If the processor
  4432. * contains any asynchronous plugins it will throw an error.
  4433. *
  4434. * This is why this method is only for debug purpose,
  4435. * you should always use {@link LazyResult#then}.
  4436. *
  4437. * @type {Message[]}
  4438. * @see Result#messages
  4439. */
  4440. }, {
  4441. key: "messages",
  4442. get: function get() {
  4443. return this.sync().messages;
  4444. }
  4445. }]);
  4446. return LazyResult;
  4447. }();
  4448. //
  4449. /**
  4450. * @callback builder
  4451. * @param {string} part - part of generated CSS connected to this node
  4452. * @param {Node} node - AST node
  4453. * @param {"start"|"end"} [type] - node’s part type
  4454. */
  4455. /**
  4456. * @callback parser
  4457. *
  4458. * @param {string|toString} css - string with input CSS or any object
  4459. * with toString() method, like a Buffer
  4460. * @param {processOptions} [opts] - options with only `from` and `map` keys
  4461. *
  4462. * @return {Root} PostCSS AST
  4463. */
  4464. /**
  4465. * @callback stringifier
  4466. *
  4467. * @param {Node} node - start node for stringifing. Usually {@link Root}.
  4468. * @param {builder} builder - function to concatenate CSS from node’s parts
  4469. * or generate string and source map
  4470. *
  4471. * @return {void}
  4472. */
  4473. /**
  4474. * @typedef {object} syntax
  4475. * @property {parser} parse - function to generate AST by string
  4476. * @property {stringifier} stringify - function to generate string by AST
  4477. */
  4478. /**
  4479. * @typedef {object} toString
  4480. * @property {function} toString
  4481. */
  4482. /**
  4483. * @callback pluginFunction
  4484. * @param {Root} root - parsed input CSS
  4485. * @param {Result} result - result to set warnings or check other plugins
  4486. */
  4487. /**
  4488. * @typedef {object} Plugin
  4489. * @property {function} postcss - PostCSS plugin function
  4490. */
  4491. /**
  4492. * @typedef {object} processOptions
  4493. * @property {string} from - the path of the CSS source file.
  4494. * You should always set `from`,
  4495. * because it is used in source map
  4496. * generation and syntax error messages.
  4497. * @property {string} to - the path where you’ll put the output
  4498. * CSS file. You should always set `to`
  4499. * to generate correct source maps.
  4500. * @property {parser} parser - function to generate AST by string
  4501. * @property {stringifier} stringifier - class to generate string by AST
  4502. * @property {syntax} syntax - object with `parse` and `stringify`
  4503. * @property {object} map - source map options
  4504. * @property {boolean} map.inline - does source map should
  4505. * be embedded in the output
  4506. * CSS as a base64-encoded
  4507. * comment
  4508. * @property {string|object|false|function} map.prev - source map content
  4509. * from a previous
  4510. * processing step
  4511. * (for example, Sass).
  4512. * PostCSS will try to find
  4513. * previous map
  4514. * automatically, so you
  4515. * could disable it by
  4516. * `false` value.
  4517. * @property {boolean} map.sourcesContent - does PostCSS should set
  4518. * the origin content to map
  4519. * @property {string|false} map.annotation - does PostCSS should set
  4520. * annotation comment to map
  4521. * @property {string} map.from - override `from` in map’s
  4522. * `sources`
  4523. */
  4524. /**
  4525. * Contains plugins to process CSS. Create one `Processor` instance,
  4526. * initialize its plugins, and then use that instance on numerous CSS files.
  4527. *
  4528. * @example
  4529. * const processor = postcss([autoprefixer, precss]);
  4530. * processor.process(css1).then(result => console.log(result.css));
  4531. * processor.process(css2).then(result => console.log(result.css));
  4532. */
  4533. var Processor =
  4534. /*#__PURE__*/
  4535. function () {
  4536. /**
  4537. * @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
  4538. * plugins. See {@link Processor#use} for plugin format.
  4539. */
  4540. function Processor(plugins) {
  4541. if (plugins === void 0) {
  4542. plugins = [];
  4543. }
  4544. /**
  4545. * @member {string} - Current PostCSS version.
  4546. *
  4547. * @example
  4548. * if ( result.processor.version.split('.')[0] !== '5' ) {
  4549. * throw new Error('This plugin works only with PostCSS 5');
  4550. * }
  4551. */
  4552. this.version = '5.2.0';
  4553. /**
  4554. * @member {pluginFunction[]} - Plugins added to this processor.
  4555. *
  4556. * @example
  4557. * const processor = postcss([autoprefixer, precss]);
  4558. * processor.plugins.length //=> 2
  4559. */
  4560. this.plugins = this.normalize(plugins);
  4561. }
  4562. /**
  4563. * Adds a plugin to be used as a CSS processor.
  4564. *
  4565. * PostCSS plugin can be in 4 formats:
  4566. * * A plugin created by {@link postcss.plugin} method.
  4567. * * A function. PostCSS will pass the function a @{link Root}
  4568. * as the first argument and current {@link Result} instance
  4569. * as the second.
  4570. * * An object with a `postcss` method. PostCSS will use that method
  4571. * as described in #2.
  4572. * * Another {@link Processor} instance. PostCSS will copy plugins
  4573. * from that instance into this one.
  4574. *
  4575. * Plugins can also be added by passing them as arguments when creating
  4576. * a `postcss` instance (see [`postcss(plugins)`]).
  4577. *
  4578. * Asynchronous plugins should return a `Promise` instance.
  4579. *
  4580. * @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin
  4581. * or {@link Processor}
  4582. * with plugins
  4583. *
  4584. * @example
  4585. * const processor = postcss()
  4586. * .use(autoprefixer)
  4587. * .use(precss);
  4588. *
  4589. * @return {Processes} current processor to make methods chain
  4590. */
  4591. var _proto = Processor.prototype;
  4592. _proto.use = function use(plugin) {
  4593. this.plugins = this.plugins.concat(this.normalize([plugin]));
  4594. return this;
  4595. }
  4596. /**
  4597. * Parses source CSS and returns a {@link LazyResult} Promise proxy.
  4598. * Because some plugins can be asynchronous it doesn’t make
  4599. * any transformations. Transformations will be applied
  4600. * in the {@link LazyResult} methods.
  4601. *
  4602. * @param {string|toString|Result} css - String with input CSS or
  4603. * any object with a `toString()`
  4604. * method, like a Buffer.
  4605. * Optionally, send a {@link Result}
  4606. * instance and the processor will
  4607. * take the {@link Root} from it.
  4608. * @param {processOptions} [opts] - options
  4609. *
  4610. * @return {LazyResult} Promise proxy
  4611. *
  4612. * @example
  4613. * processor.process(css, { from: 'a.css', to: 'a.out.css' })
  4614. * .then(result => {
  4615. * console.log(result.css);
  4616. * });
  4617. */
  4618. ;
  4619. _proto.process = function process(css, opts) {
  4620. if (opts === void 0) {
  4621. opts = {};
  4622. }
  4623. return new LazyResult(this, css, opts);
  4624. };
  4625. _proto.normalize = function normalize(plugins) {
  4626. var normalized = [];
  4627. plugins.forEach(function (i) {
  4628. if (i.postcss) i = i.postcss;
  4629. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  4630. normalized = normalized.concat(i.plugins);
  4631. } else if (typeof i === 'function') {
  4632. normalized.push(i);
  4633. } else {
  4634. throw new Error(i + " is not a PostCSS plugin");
  4635. }
  4636. });
  4637. return normalized;
  4638. };
  4639. return Processor;
  4640. }();
  4641. /**
  4642. * Represents a CSS file and contains all its parsed nodes.
  4643. *
  4644. * @extends Container
  4645. *
  4646. * @example
  4647. * const root = postcss.parse('a{color:black} b{z-index:2}');
  4648. * root.type //=> 'root'
  4649. * root.nodes.length //=> 2
  4650. */
  4651. var Root =
  4652. /*#__PURE__*/
  4653. function (_Container) {
  4654. _inheritsLoose(Root, _Container);
  4655. function Root(defaults) {
  4656. var _this;
  4657. _this = _Container.call(this, defaults) || this;
  4658. _this.type = 'root';
  4659. if (!_this.nodes) _this.nodes = [];
  4660. return _this;
  4661. }
  4662. var _proto = Root.prototype;
  4663. _proto.removeChild = function removeChild(child) {
  4664. child = this.index(child);
  4665. if (child === 0 && this.nodes.length > 1) {
  4666. this.nodes[1].raws.before = this.nodes[child].raws.before;
  4667. }
  4668. return _Container.prototype.removeChild.call(this, child);
  4669. };
  4670. _proto.normalize = function normalize(child, sample, type) {
  4671. var nodes = _Container.prototype.normalize.call(this, child);
  4672. if (sample) {
  4673. if (type === 'prepend') {
  4674. if (this.nodes.length > 1) {
  4675. sample.raws.before = this.nodes[1].raws.before;
  4676. } else {
  4677. delete sample.raws.before;
  4678. }
  4679. } else if (this.first !== sample) {
  4680. nodes.forEach(function (node) {
  4681. node.raws.before = sample.raws.before;
  4682. });
  4683. }
  4684. }
  4685. return nodes;
  4686. }
  4687. /**
  4688. * Returns a {@link Result} instance representing the root’s CSS.
  4689. *
  4690. * @param {processOptions} [opts] - options with only `to` and `map` keys
  4691. *
  4692. * @return {Result} result with current root’s CSS
  4693. *
  4694. * @example
  4695. * const root1 = postcss.parse(css1, { from: 'a.css' });
  4696. * const root2 = postcss.parse(css2, { from: 'b.css' });
  4697. * root1.append(root2);
  4698. * const result = root1.toResult({ to: 'all.css', map: true });
  4699. */
  4700. ;
  4701. _proto.toResult = function toResult(opts) {
  4702. if (opts === void 0) {
  4703. opts = {};
  4704. }
  4705. var lazy = new LazyResult(new Processor(), this, opts);
  4706. return lazy.stringify();
  4707. };
  4708. _proto.remove = function remove(child) {
  4709. warnOnce('Root#remove is deprecated. Use Root#removeChild');
  4710. this.removeChild(child);
  4711. };
  4712. _proto.prevMap = function prevMap() {
  4713. warnOnce('Root#prevMap is deprecated. Use Root#source.input.map');
  4714. return this.source.input.map;
  4715. }
  4716. /**
  4717. * @memberof Root#
  4718. * @member {object} raws - Information to generate byte-to-byte equal
  4719. * node string as it was in the origin input.
  4720. *
  4721. * Every parser saves its own properties,
  4722. * but the default CSS parser uses:
  4723. *
  4724. * * `after`: the space symbols after the last child to the end of file.
  4725. * * `semicolon`: is the last child has an (optional) semicolon.
  4726. *
  4727. * @example
  4728. * postcss.parse('a {}\n').raws //=> { after: '\n' }
  4729. * postcss.parse('a {}').raws //=> { after: '' }
  4730. */
  4731. ;
  4732. return Root;
  4733. }(Container);
  4734. var sequence = 0;
  4735. /**
  4736. * @typedef {object} filePosition
  4737. * @property {string} file - path to file
  4738. * @property {number} line - source line in file
  4739. * @property {number} column - source column in file
  4740. */
  4741. /**
  4742. * Represents the source CSS.
  4743. *
  4744. * @example
  4745. * const root = postcss.parse(css, { from: file });
  4746. * const input = root.source.input;
  4747. */
  4748. var Input =
  4749. /*#__PURE__*/
  4750. function () {
  4751. /**
  4752. * @param {string} css - input CSS source
  4753. * @param {object} [opts] - {@link Processor#process} options
  4754. */
  4755. function Input(css, opts) {
  4756. if (opts === void 0) {
  4757. opts = {};
  4758. }
  4759. /**
  4760. * @member {string} - input CSS source
  4761. *
  4762. * @example
  4763. * const input = postcss.parse('a{}', { from: file }).input;
  4764. * input.css //=> "a{}";
  4765. */
  4766. this.css = css.toString();
  4767. if (this.css[0] === "\uFEFF" || this.css[0] === "\uFFFE") {
  4768. this.css = this.css.slice(1);
  4769. }
  4770. if (opts.from) {
  4771. if (/^\w+:\/\//.test(opts.from)) {
  4772. /**
  4773. * @member {string} - The absolute path to the CSS source file
  4774. * defined with the `from` option.
  4775. *
  4776. * @example
  4777. * const root = postcss.parse(css, { from: 'a.css' });
  4778. * root.source.input.file //=> '/home/ai/a.css'
  4779. */
  4780. this.file = opts.from;
  4781. } else {
  4782. this.file = path.resolve(opts.from);
  4783. }
  4784. }
  4785. /*
  4786. let map = new PreviousMap(this.css, opts);
  4787. if ( map.text ) {
  4788. /!**
  4789. * @member {PreviousMap} - The input source map passed from
  4790. * a compilation step before PostCSS
  4791. * (for example, from Sass compiler).
  4792. *
  4793. * @example
  4794. * root.source.input.map.consumer().sources //=> ['a.sass']
  4795. *!/
  4796. this.map = map;
  4797. let file = map.consumer().file;
  4798. if ( !this.file && file ) this.file = this.mapResolve(file);
  4799. }
  4800. */
  4801. if (!this.file) {
  4802. sequence += 1;
  4803. /**
  4804. * @member {string} - The unique ID of the CSS source. It will be
  4805. * created if `from` option is not provided
  4806. * (because PostCSS does not know the file path).
  4807. *
  4808. * @example
  4809. * const root = postcss.parse(css);
  4810. * root.source.input.file //=> undefined
  4811. * root.source.input.id //=> "<input css 1>"
  4812. */
  4813. this.id = "<input css " + sequence + ">";
  4814. }
  4815. if (this.map) this.map.file = this.from;
  4816. }
  4817. var _proto = Input.prototype;
  4818. _proto.error = function error(message, line, column, opts) {
  4819. if (opts === void 0) {
  4820. opts = {};
  4821. }
  4822. var result;
  4823. var origin = this.origin(line, column);
  4824. if (origin) {
  4825. result = new CssSyntaxError(message, origin.line, origin.column, origin.source, origin.file, opts.plugin);
  4826. } else {
  4827. result = new CssSyntaxError(message, line, column, this.css, this.file, opts.plugin);
  4828. }
  4829. result.input = {
  4830. line: line,
  4831. column: column,
  4832. source: this.css
  4833. };
  4834. if (this.file) result.input.file = this.file;
  4835. return result;
  4836. }
  4837. /**
  4838. * Reads the input source map and returns a symbol position
  4839. * in the input source (e.g., in a Sass file that was compiled
  4840. * to CSS before being passed to PostCSS).
  4841. *
  4842. * @param {number} line - line in input CSS
  4843. * @param {number} column - column in input CSS
  4844. *
  4845. * @return {filePosition} position in input source
  4846. *
  4847. * @example
  4848. * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
  4849. */
  4850. ;
  4851. _proto.origin = function origin(line, column) {
  4852. if (!this.map) return false;
  4853. var consumer = this.map.consumer();
  4854. var from = consumer.originalPositionFor({
  4855. line: line,
  4856. column: column
  4857. });
  4858. if (!from.source) return false;
  4859. var result = {
  4860. file: this.mapResolve(from.source),
  4861. line: from.line,
  4862. column: from.column
  4863. };
  4864. var source = consumer.sourceContentFor(from.source);
  4865. if (source) result.source = source;
  4866. return result;
  4867. };
  4868. _proto.mapResolve = function mapResolve(file) {
  4869. if (/^\w+:\/\//.test(file)) {
  4870. return file;
  4871. } else {
  4872. return path.resolve(this.map.consumer().sourceRoot || '.', file);
  4873. }
  4874. }
  4875. /**
  4876. * The CSS source identifier. Contains {@link Input#file} if the user
  4877. * set the `from` option, or {@link Input#id} if they did not.
  4878. * @type {string}
  4879. *
  4880. * @example
  4881. * const root = postcss.parse(css, { from: 'a.css' });
  4882. * root.source.input.from //=> "/home/ai/a.css"
  4883. *
  4884. * const root = postcss.parse(css);
  4885. * root.source.input.from //=> "<input css 1>"
  4886. */
  4887. ;
  4888. _createClass(Input, [{
  4889. key: "from",
  4890. get: function get() {
  4891. return this.file || this.id;
  4892. }
  4893. }]);
  4894. return Input;
  4895. }();
  4896. var SafeParser =
  4897. /*#__PURE__*/
  4898. function (_Parser) {
  4899. _inheritsLoose(SafeParser, _Parser);
  4900. function SafeParser() {
  4901. return _Parser.apply(this, arguments) || this;
  4902. }
  4903. var _proto = SafeParser.prototype;
  4904. _proto.tokenize = function tokenize$1() {
  4905. this.tokens = tokenize(this.input, {
  4906. ignoreErrors: true
  4907. });
  4908. };
  4909. _proto.comment = function comment(token) {
  4910. var node = new Comment();
  4911. this.init(node, token[2], token[3]);
  4912. node.source.end = {
  4913. line: token[4],
  4914. column: token[5]
  4915. };
  4916. var text = token[1].slice(2);
  4917. if (text.slice(-2) === '*/') text = text.slice(0, -2);
  4918. if (/^\s*$/.test(text)) {
  4919. node.text = '';
  4920. node.raws.left = text;
  4921. node.raws.right = '';
  4922. } else {
  4923. var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
  4924. node.text = match[2];
  4925. node.raws.left = match[1];
  4926. node.raws.right = match[3];
  4927. }
  4928. };
  4929. _proto.unclosedBracket = function unclosedBracket() {};
  4930. _proto.unknownWord = function unknownWord(start) {
  4931. var buffer = this.tokens.slice(start, this.pos + 1);
  4932. this.spaces += buffer.map(function (i) {
  4933. return i[1];
  4934. }).join('');
  4935. };
  4936. _proto.unexpectedClose = function unexpectedClose() {
  4937. this.current.raws.after += '}';
  4938. };
  4939. _proto.doubleColon = function doubleColon() {};
  4940. _proto.unnamedAtrule = function unnamedAtrule(node) {
  4941. node.name = '';
  4942. };
  4943. _proto.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
  4944. var colon = this.colon(tokens);
  4945. if (colon === false) return;
  4946. var split;
  4947. for (split = colon - 1; split >= 0; split--) {
  4948. if (tokens[split][0] === 'word') break;
  4949. }
  4950. for (split -= 1; split >= 0; split--) {
  4951. if (tokens[split][0] !== 'space') {
  4952. split += 1;
  4953. break;
  4954. }
  4955. }
  4956. var other = tokens.splice(split, tokens.length - split);
  4957. this.decl(other);
  4958. };
  4959. _proto.checkMissedSemicolon = function checkMissedSemicolon() {};
  4960. _proto.endFile = function endFile() {
  4961. if (this.current.nodes && this.current.nodes.length) {
  4962. this.current.raws.semicolon = this.semicolon;
  4963. }
  4964. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  4965. while (this.current.parent) {
  4966. this.current = this.current.parent;
  4967. this.current.raws.after = '';
  4968. }
  4969. };
  4970. return SafeParser;
  4971. }(Parser);
  4972. //
  4973. function safeParse(css, opts) {
  4974. var input = new Input(css, opts);
  4975. var parser = new SafeParser(input);
  4976. parser.tokenize();
  4977. parser.loop();
  4978. return parser.root;
  4979. }
  4980. //
  4981. var generated = {};
  4982. /*
  4983. InlineStyle takes arbitrary CSS and generates a flat object
  4984. */
  4985. var _InlineStyle = (function (styleSheet) {
  4986. var InlineStyle =
  4987. /*#__PURE__*/
  4988. function () {
  4989. function InlineStyle(rules) {
  4990. this.rules = rules;
  4991. }
  4992. var _proto = InlineStyle.prototype;
  4993. _proto.generateStyleObject = function generateStyleObject(executionContext) {
  4994. var flatCSS = flatten(this.rules, executionContext).join('');
  4995. var hash = generateComponentId(flatCSS);
  4996. if (!generated[hash]) {
  4997. var root = safeParse(flatCSS);
  4998. var declPairs = [];
  4999. root.each(function (node) {
  5000. if (node.type === 'decl') {
  5001. declPairs.push([node.prop, node.value]);
  5002. } else if (process.env.NODE_ENV !== 'production' && node.type !== 'comment') {
  5003. /* eslint-disable no-console */
  5004. console.warn("Node of type " + node.type + " not supported as an inline style");
  5005. }
  5006. }); // RN currently does not support differing values for the corner radii of Image
  5007. // components (but does for View). It is almost impossible to tell whether we'll have
  5008. // support, so we'll just disable multiple values here.
  5009. // https://github.com/styled-components/css-to-react-native/issues/11
  5010. var styleObject = transformDeclPairs(declPairs, ['borderRadius', 'borderWidth', 'borderColor', 'borderStyle']);
  5011. var styles = styleSheet.create({
  5012. generated: styleObject
  5013. });
  5014. generated[hash] = styles.generated;
  5015. }
  5016. return generated[hash];
  5017. };
  5018. return InlineStyle;
  5019. }();
  5020. return InlineStyle;
  5021. });
  5022. /* eslint-disable */
  5023. /**
  5024. mixin-deep; https://github.com/jonschlinkert/mixin-deep
  5025. Inlined such that it will be consistently transpiled to an IE-compatible syntax.
  5026. The MIT License (MIT)
  5027. Copyright (c) 2014-present, Jon Schlinkert.
  5028. Permission is hereby granted, free of charge, to any person obtaining a copy
  5029. of this software and associated documentation files (the "Software"), to deal
  5030. in the Software without restriction, including without limitation the rights
  5031. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5032. copies of the Software, and to permit persons to whom the Software is
  5033. furnished to do so, subject to the following conditions:
  5034. The above copyright notice and this permission notice shall be included in
  5035. all copies or substantial portions of the Software.
  5036. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5037. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5038. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5039. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5040. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5041. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  5042. THE SOFTWARE.
  5043. */
  5044. var isObject = function isObject(val) {
  5045. return typeof val === 'function' || typeof val === 'object' && val !== null && !Array.isArray(val);
  5046. };
  5047. var isValidKey = function isValidKey(key) {
  5048. return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
  5049. };
  5050. function mixin(target, val, key) {
  5051. var obj = target[key];
  5052. if (isObject(val) && isObject(obj)) {
  5053. mixinDeep(obj, val);
  5054. } else {
  5055. target[key] = val;
  5056. }
  5057. }
  5058. function mixinDeep(target) {
  5059. for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  5060. rest[_key - 1] = arguments[_key];
  5061. }
  5062. for (var _i = 0, _rest = rest; _i < _rest.length; _i++) {
  5063. var obj = _rest[_i];
  5064. if (isObject(obj)) {
  5065. for (var key in obj) {
  5066. if (isValidKey(key)) {
  5067. mixin(target, obj[key], key);
  5068. }
  5069. }
  5070. }
  5071. }
  5072. return target;
  5073. }
  5074. //
  5075. var determineTheme = (function (props, providedTheme, defaultProps) {
  5076. if (defaultProps === void 0) {
  5077. defaultProps = EMPTY_OBJECT;
  5078. }
  5079. return props.theme !== defaultProps.theme && props.theme || providedTheme || defaultProps.theme;
  5080. });
  5081. //
  5082. function isTag(target) {
  5083. return typeof target === 'string' && (process.env.NODE_ENV !== 'production' ? target.charAt(0) === target.charAt(0).toLowerCase() : true);
  5084. }
  5085. //
  5086. function generateDisplayName(target) {
  5087. // $FlowFixMe
  5088. return isTag(target) ? "styled." + target : "Styled(" + getComponentName(target) + ")";
  5089. }
  5090. var ThemeContext = React.createContext();
  5091. var ThemeConsumer = ThemeContext.Consumer;
  5092. function mergeTheme(theme, outerTheme) {
  5093. if (!theme) {
  5094. return throwStyledComponentsError(14);
  5095. }
  5096. if (isFunction(theme)) {
  5097. var mergedTheme = theme(outerTheme);
  5098. if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || typeof mergedTheme !== 'object')) {
  5099. return throwStyledComponentsError(7);
  5100. }
  5101. return mergedTheme;
  5102. }
  5103. if (Array.isArray(theme) || typeof theme !== 'object') {
  5104. return throwStyledComponentsError(8);
  5105. }
  5106. return outerTheme ? _extends({}, outerTheme, {}, theme) : theme;
  5107. }
  5108. /**
  5109. * Provide a theme to an entire react component tree via context
  5110. */
  5111. function ThemeProvider(props) {
  5112. var outerTheme = useContext(ThemeContext);
  5113. var themeContext = useMemo(function () {
  5114. return mergeTheme(props.theme, outerTheme);
  5115. }, [props.theme, outerTheme]);
  5116. if (!props.children) {
  5117. return null;
  5118. }
  5119. return React.createElement(ThemeContext.Provider, {
  5120. value: themeContext
  5121. }, props.children);
  5122. }
  5123. // if the user makes use of ThemeProvider or StyleSheetManager things will break.
  5124. var StyledNativeComponent =
  5125. /*#__PURE__*/
  5126. function (_Component) {
  5127. _inheritsLoose(StyledNativeComponent, _Component);
  5128. function StyledNativeComponent() {
  5129. var _this;
  5130. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  5131. args[_key] = arguments[_key];
  5132. }
  5133. _this = _Component.call.apply(_Component, [this].concat(args)) || this;
  5134. _this.attrs = {};
  5135. return _this;
  5136. }
  5137. var _proto = StyledNativeComponent.prototype;
  5138. _proto.render = function render() {
  5139. var _this2 = this;
  5140. return React.createElement(ThemeConsumer, null, function (theme) {
  5141. var _this2$props = _this2.props,
  5142. renderAs = _this2$props.as,
  5143. forwardedComponent = _this2$props.forwardedComponent,
  5144. forwardedAs = _this2$props.forwardedAs,
  5145. forwardedRef = _this2$props.forwardedRef,
  5146. _this2$props$style = _this2$props.style,
  5147. style = _this2$props$style === void 0 ? [] : _this2$props$style,
  5148. props = _objectWithoutPropertiesLoose(_this2$props, ["as", "forwardedComponent", "forwardedAs", "forwardedRef", "style"]);
  5149. var defaultProps = forwardedComponent.defaultProps,
  5150. target = forwardedComponent.target;
  5151. var generatedStyles = _this2.generateAndInjectStyles(determineTheme(_this2.props, theme, defaultProps) || EMPTY_OBJECT, _this2.props);
  5152. var propsForElement = _extends({}, props, {}, _this2.attrs, {
  5153. style: [generatedStyles].concat(style)
  5154. });
  5155. if (forwardedRef) propsForElement.ref = forwardedRef;
  5156. if (forwardedAs) propsForElement.as = forwardedAs;
  5157. return createElement(renderAs || target, propsForElement);
  5158. });
  5159. };
  5160. _proto.buildExecutionContext = function buildExecutionContext(theme, props, attrs) {
  5161. var _this3 = this;
  5162. var context = _extends({}, props, {
  5163. theme: theme
  5164. });
  5165. if (!attrs.length) return context;
  5166. this.attrs = {};
  5167. attrs.forEach(function (attrDef) {
  5168. var resolvedAttrDef = attrDef;
  5169. var attr;
  5170. var key;
  5171. if (isFunction(resolvedAttrDef)) {
  5172. resolvedAttrDef = resolvedAttrDef(context);
  5173. }
  5174. /* eslint-disable guard-for-in */
  5175. for (key in resolvedAttrDef) {
  5176. attr = resolvedAttrDef[key];
  5177. _this3.attrs[key] = attr;
  5178. context[key] = attr;
  5179. }
  5180. /* eslint-enable */
  5181. });
  5182. return context;
  5183. };
  5184. _proto.generateAndInjectStyles = function generateAndInjectStyles(theme, props) {
  5185. var inlineStyle = props.forwardedComponent.inlineStyle;
  5186. var executionContext = this.buildExecutionContext(theme, props, props.forwardedComponent.attrs);
  5187. return inlineStyle.generateStyleObject(executionContext);
  5188. };
  5189. _proto.setNativeProps = function setNativeProps(nativeProps) {
  5190. if (this.root !== undefined) {
  5191. // $FlowFixMe
  5192. this.root.setNativeProps(nativeProps);
  5193. } else if (process.env.NODE_ENV !== 'production') {
  5194. // eslint-disable-next-line no-console
  5195. console.warn('setNativeProps was called on a Styled Component wrapping a stateless functional component.');
  5196. }
  5197. };
  5198. return StyledNativeComponent;
  5199. }(Component);
  5200. var _StyledNativeComponent = (function (InlineStyle) {
  5201. var createStyledNativeComponent = function createStyledNativeComponent(target, options, rules) {
  5202. var _options$attrs = options.attrs,
  5203. attrs = _options$attrs === void 0 ? EMPTY_ARRAY : _options$attrs,
  5204. _options$displayName = options.displayName,
  5205. displayName = _options$displayName === void 0 ? generateDisplayName(target) : _options$displayName,
  5206. _options$ParentCompon = options.ParentComponent,
  5207. ParentComponent = _options$ParentCompon === void 0 ? StyledNativeComponent : _options$ParentCompon;
  5208. var isClass = !isTag(target);
  5209. var isTargetStyledComp = isStyledComponent(target); // $FlowFixMe
  5210. var WrappedStyledNativeComponent = React.forwardRef(function (props, ref) {
  5211. return React.createElement(ParentComponent, _extends({}, props, {
  5212. forwardedComponent: WrappedStyledNativeComponent,
  5213. forwardedRef: ref
  5214. }));
  5215. });
  5216. var finalAttrs = // $FlowFixMe
  5217. isTargetStyledComp && target.attrs ? Array.prototype.concat(target.attrs, attrs).filter(Boolean) : attrs;
  5218. /**
  5219. * forwardRef creates a new interim component, which we'll take advantage of
  5220. * instead of extending ParentComponent to create _another_ interim class
  5221. */
  5222. // $FlowFixMe
  5223. WrappedStyledNativeComponent.attrs = finalAttrs;
  5224. WrappedStyledNativeComponent.displayName = displayName; // $FlowFixMe
  5225. WrappedStyledNativeComponent.inlineStyle = new InlineStyle( // $FlowFixMe
  5226. isTargetStyledComp ? target.inlineStyle.rules.concat(rules) : rules); // $FlowFixMe
  5227. WrappedStyledNativeComponent.styledComponentId = 'StyledNativeComponent'; // $FlowFixMe
  5228. WrappedStyledNativeComponent.target = isTargetStyledComp ? // $FlowFixMe
  5229. target.target : target; // $FlowFixMe
  5230. WrappedStyledNativeComponent.withComponent = function withComponent(tag) {
  5231. var _ = options.displayName,
  5232. __ = options.componentId,
  5233. optionsToCopy = _objectWithoutPropertiesLoose(options, ["displayName", "componentId"]);
  5234. var newOptions = _extends({}, optionsToCopy, {
  5235. attrs: finalAttrs,
  5236. ParentComponent: ParentComponent
  5237. });
  5238. return createStyledNativeComponent(tag, newOptions, rules);
  5239. }; // $FlowFixMe
  5240. Object.defineProperty(WrappedStyledNativeComponent, 'defaultProps', {
  5241. get: function get() {
  5242. return this._foldedDefaultProps;
  5243. },
  5244. set: function set(obj) {
  5245. // $FlowFixMe
  5246. this._foldedDefaultProps = isTargetStyledComp ? mixinDeep({}, target.defaultProps, obj) : obj;
  5247. }
  5248. });
  5249. if (isClass) {
  5250. hoist(WrappedStyledNativeComponent, target, {
  5251. // all SC-specific things should not be hoisted
  5252. attrs: true,
  5253. displayName: true,
  5254. inlineStyle: true,
  5255. styledComponentId: true,
  5256. target: true,
  5257. withComponent: true
  5258. });
  5259. }
  5260. return WrappedStyledNativeComponent;
  5261. };
  5262. return createStyledNativeComponent;
  5263. });
  5264. //
  5265. var interleave = (function (strings, interpolations) {
  5266. var result = [strings[0]];
  5267. for (var i = 0, len = interpolations.length; i < len; i += 1) {
  5268. result.push(interpolations[i], strings[i + 1]);
  5269. }
  5270. return result;
  5271. });
  5272. //
  5273. function css(styles) {
  5274. for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  5275. interpolations[_key - 1] = arguments[_key];
  5276. }
  5277. if (isFunction(styles) || isPlainObject(styles)) {
  5278. // $FlowFixMe
  5279. return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations)));
  5280. }
  5281. if (interpolations.length === 0 && styles.length === 1 && typeof styles[0] === "string") {
  5282. // $FlowFixMe
  5283. return styles;
  5284. } // $FlowFixMe
  5285. return flatten(interleave(styles, interpolations));
  5286. }
  5287. function constructWithOptions(componentConstructor, tag, options) {
  5288. if (options === void 0) {
  5289. options = EMPTY_OBJECT;
  5290. }
  5291. if (!isValidElementType(tag)) {
  5292. return throwStyledComponentsError(1, String(tag));
  5293. }
  5294. /* This is callable directly as a template function */
  5295. // $FlowFixMe: Not typed to avoid destructuring arguments
  5296. var templateFunction = function templateFunction() {
  5297. return componentConstructor(tag, options, css.apply(void 0, arguments));
  5298. };
  5299. /* If config methods are called, wrap up a new template function and merge options */
  5300. templateFunction.withConfig = function (config) {
  5301. return constructWithOptions(componentConstructor, tag, _extends({}, options, {}, config));
  5302. };
  5303. /* Modify/inject new props at runtime */
  5304. templateFunction.attrs = function (attrs) {
  5305. return constructWithOptions(componentConstructor, tag, _extends({}, options, {
  5306. attrs: Array.prototype.concat(options.attrs, attrs).filter(Boolean)
  5307. }));
  5308. };
  5309. return templateFunction;
  5310. }
  5311. // export default <Config: { theme?: any }, Instance>(
  5312. // Component: AbstractComponent<Config, Instance>
  5313. // ): AbstractComponent<$Diff<Config, { theme?: any }> & { theme?: any }, Instance>
  5314. //
  5315. // but the old build system tooling doesn't support the syntax
  5316. var withTheme = (function (Component) {
  5317. // $FlowFixMe This should be React.forwardRef<Config, Instance>
  5318. var WithTheme = React.forwardRef(function (props, ref) {
  5319. var theme = useContext(ThemeContext); // $FlowFixMe defaultProps isn't declared so it can be inferrable
  5320. var defaultProps = Component.defaultProps;
  5321. var themeProp = determineTheme(props, theme, defaultProps);
  5322. if (process.env.NODE_ENV !== 'production' && themeProp === undefined) {
  5323. // eslint-disable-next-line no-console
  5324. console.warn("[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class \"" + getComponentName(Component) + "\"");
  5325. }
  5326. return React.createElement(Component, _extends({}, props, {
  5327. theme: themeProp,
  5328. ref: ref
  5329. }));
  5330. });
  5331. hoist(WithTheme, Component);
  5332. WithTheme.displayName = "WithTheme(" + getComponentName(Component) + ")";
  5333. return WithTheme;
  5334. });
  5335. //
  5336. var InlineStyle = _InlineStyle(reactPrimitives.StyleSheet);
  5337. var StyledNativeComponent$1 = _StyledNativeComponent(InlineStyle);
  5338. var styled = function styled(tag) {
  5339. return constructWithOptions(StyledNativeComponent$1, tag);
  5340. };
  5341. /* React native lazy-requires each of these modules for some reason, so let's
  5342. * assume it's for a good reason and not eagerly load them all */
  5343. var aliases = 'Image Text Touchable View ';
  5344. /* Define a getter for each alias which simply gets the reactNative component
  5345. * and passes it to styled */
  5346. aliases.split(/\s+/m).forEach(function (alias) {
  5347. return Object.defineProperty(styled, alias, {
  5348. enumerable: true,
  5349. configurable: false,
  5350. get: function get() {
  5351. return styled(reactPrimitives[alias]);
  5352. }
  5353. });
  5354. });
  5355. export default styled;
  5356. export { ThemeConsumer, ThemeContext, ThemeProvider, css, isStyledComponent, withTheme };
  5357. //# sourceMappingURL=styled-components-primitives.esm.js.map