styled-components.native.cjs.js 172 KB

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