智慧水务管理系统 - 精河县供水工程综合管理平台

compiler-sfc.cjs.js 849KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854
  1. /**
  2. * @vue/compiler-sfc v3.5.38
  3. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  4. * @license MIT
  5. **/
  6. 'use strict';
  7. Object.defineProperty(exports, '__esModule', { value: true });
  8. var compilerCore = require('@vue/compiler-core');
  9. var CompilerDOM = require('@vue/compiler-dom');
  10. var sourceMapJs = require('source-map-js');
  11. var shared = require('@vue/shared');
  12. var path$1 = require('path');
  13. var url = require('url');
  14. var CompilerSSR = require('@vue/compiler-ssr');
  15. var require$$2 = require('util');
  16. var require$$0 = require('fs');
  17. var require$$0$1 = require('postcss');
  18. var estreeWalker = require('estree-walker');
  19. var MagicString = require('magic-string');
  20. var parser$2 = require('@babel/parser');
  21. var process$1 = require('process');
  22. function _interopNamespaceDefault(e) {
  23. var n = Object.create(null);
  24. if (e) {
  25. for (var k in e) {
  26. n[k] = e[k];
  27. }
  28. }
  29. n.default = e;
  30. return Object.freeze(n);
  31. }
  32. var CompilerDOM__namespace = /*#__PURE__*/_interopNamespaceDefault(CompilerDOM);
  33. var CompilerSSR__namespace = /*#__PURE__*/_interopNamespaceDefault(CompilerSSR);
  34. var process__namespace = /*#__PURE__*/_interopNamespaceDefault(process$1);
  35. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  36. function getDefaultExportFromCjs (x) {
  37. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  38. }
  39. var hashSum;
  40. var hasRequiredHashSum;
  41. function requireHashSum () {
  42. if (hasRequiredHashSum) return hashSum;
  43. hasRequiredHashSum = 1;
  44. function pad (hash, len) {
  45. while (hash.length < len) {
  46. hash = '0' + hash;
  47. }
  48. return hash;
  49. }
  50. function fold (hash, text) {
  51. var i;
  52. var chr;
  53. var len;
  54. if (text.length === 0) {
  55. return hash;
  56. }
  57. for (i = 0, len = text.length; i < len; i++) {
  58. chr = text.charCodeAt(i);
  59. hash = ((hash << 5) - hash) + chr;
  60. hash |= 0;
  61. }
  62. return hash < 0 ? hash * -2 : hash;
  63. }
  64. function foldObject (hash, o, seen) {
  65. return Object.keys(o).sort().reduce(foldKey, hash);
  66. function foldKey (hash, key) {
  67. return foldValue(hash, o[key], key, seen);
  68. }
  69. }
  70. function foldValue (input, value, key, seen) {
  71. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  72. if (value === null) {
  73. return fold(hash, 'null');
  74. }
  75. if (value === undefined) {
  76. return fold(hash, 'undefined');
  77. }
  78. if (typeof value === 'object' || typeof value === 'function') {
  79. if (seen.indexOf(value) !== -1) {
  80. return fold(hash, '[Circular]' + key);
  81. }
  82. seen.push(value);
  83. var objHash = foldObject(hash, value, seen);
  84. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  85. return objHash;
  86. }
  87. try {
  88. return fold(objHash, String(value.valueOf()))
  89. } catch (err) {
  90. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  91. }
  92. }
  93. return fold(hash, value.toString());
  94. }
  95. function toString (o) {
  96. return Object.prototype.toString.call(o);
  97. }
  98. function sum (o) {
  99. return pad(foldValue(0, o, '', []).toString(16), 8);
  100. }
  101. hashSum = sum;
  102. return hashSum;
  103. }
  104. var hashSumExports = /*@__PURE__*/ requireHashSum();
  105. var hash = /*@__PURE__*/getDefaultExportFromCjs(hashSumExports);
  106. const CSS_VARS_HELPER = `useCssVars`;
  107. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  108. return `{
  109. ${vars.map(
  110. (key) => (
  111. // The `:` prefix here is used in `ssrRenderStyle` to distinguish whether
  112. // a custom property comes from `ssrCssVars`. If it does, we need to reset
  113. // its value to `initial` on the component instance to avoid unintentionally
  114. // inheriting the same property value from a different instance of the same
  115. // component in the outer scope.
  116. `"${isSSR ? `:--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  117. )
  118. ).join(",\n ")}
  119. }`;
  120. }
  121. function genVarName(id, raw, isProd, isSSR = false) {
  122. if (isProd) {
  123. return hash(id + raw).replace(/^\d/, (r) => `v${r}`);
  124. } else {
  125. return `${id}-${shared.getEscapedCssVarName(raw, isSSR)}`;
  126. }
  127. }
  128. function normalizeExpression(exp) {
  129. exp = exp.trim();
  130. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  131. return exp.slice(1, -1);
  132. }
  133. return exp;
  134. }
  135. const vBindRE = /v-bind\s*\(/g;
  136. function parseCssVars(sfc) {
  137. const vars = [];
  138. sfc.styles.forEach((style) => {
  139. let match;
  140. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  141. while (match = vBindRE.exec(content)) {
  142. const start = match.index + match[0].length;
  143. const end = lexBinding(content, start);
  144. if (end !== null) {
  145. const variable = normalizeExpression(content.slice(start, end));
  146. if (!vars.includes(variable)) {
  147. vars.push(variable);
  148. }
  149. }
  150. }
  151. });
  152. return vars;
  153. }
  154. function lexBinding(content, start) {
  155. let state = 0 /* inParens */;
  156. let parenDepth = 0;
  157. for (let i = start; i < content.length; i++) {
  158. const char = content.charAt(i);
  159. switch (state) {
  160. case 0 /* inParens */:
  161. if (char === `'`) {
  162. state = 1 /* inSingleQuoteString */;
  163. } else if (char === `"`) {
  164. state = 2 /* inDoubleQuoteString */;
  165. } else if (char === `(`) {
  166. parenDepth++;
  167. } else if (char === `)`) {
  168. if (parenDepth > 0) {
  169. parenDepth--;
  170. } else {
  171. return i;
  172. }
  173. }
  174. break;
  175. case 1 /* inSingleQuoteString */:
  176. if (char === `'`) {
  177. state = 0 /* inParens */;
  178. }
  179. break;
  180. case 2 /* inDoubleQuoteString */:
  181. if (char === `"`) {
  182. state = 0 /* inParens */;
  183. }
  184. break;
  185. }
  186. }
  187. return null;
  188. }
  189. const cssVarsPlugin = (opts) => {
  190. const { id, isProd } = opts;
  191. return {
  192. postcssPlugin: "vue-sfc-vars",
  193. Declaration(decl) {
  194. const value = decl.value;
  195. if (vBindRE.test(value)) {
  196. vBindRE.lastIndex = 0;
  197. let transformed = "";
  198. let lastIndex = 0;
  199. let match;
  200. while (match = vBindRE.exec(value)) {
  201. const start = match.index + match[0].length;
  202. const end = lexBinding(value, start);
  203. if (end !== null) {
  204. const variable = normalizeExpression(value.slice(start, end));
  205. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  206. lastIndex = end + 1;
  207. }
  208. }
  209. decl.value = transformed + value.slice(lastIndex);
  210. }
  211. }
  212. };
  213. };
  214. cssVarsPlugin.postcss = true;
  215. function genCssVarsCode(vars, bindings, id, isProd) {
  216. const varsExp = genCssVarsFromList(vars, id, isProd);
  217. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  218. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  219. prefixIdentifiers: true,
  220. inline: true,
  221. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  222. });
  223. const transformed = CompilerDOM.processExpression(exp, context);
  224. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  225. return typeof c === "string" ? c : c.content;
  226. }).join("");
  227. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  228. }
  229. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  230. return `
  231. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  232. const __injectCSSVars__ = () => {
  233. ${genCssVarsCode(
  234. cssVars,
  235. bindings,
  236. id,
  237. isProd
  238. )}}
  239. const __setup__ = ${defaultVar}.setup
  240. ${defaultVar}.setup = __setup__
  241. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  242. : __injectCSSVars__
  243. `;
  244. }
  245. /**
  246. * @module LRUCache
  247. */
  248. const perf = typeof performance === 'object' &&
  249. performance &&
  250. typeof performance.now === 'function'
  251. ? performance
  252. : Date;
  253. const warned = new Set();
  254. /* c8 ignore start */
  255. const PROCESS = (typeof process === 'object' && !!process ? process : {});
  256. /* c8 ignore start */
  257. const emitWarning = (msg, type, code, fn) => {
  258. typeof PROCESS.emitWarning === 'function'
  259. ? PROCESS.emitWarning(msg, type, code, fn)
  260. : console.error(`[${code}] ${type}: ${msg}`);
  261. };
  262. let AC = globalThis.AbortController;
  263. let AS = globalThis.AbortSignal;
  264. /* c8 ignore start */
  265. if (typeof AC === 'undefined') {
  266. //@ts-ignore
  267. AS = class AbortSignal {
  268. onabort;
  269. _onabort = [];
  270. reason;
  271. aborted = false;
  272. addEventListener(_, fn) {
  273. this._onabort.push(fn);
  274. }
  275. };
  276. //@ts-ignore
  277. AC = class AbortController {
  278. constructor() {
  279. warnACPolyfill();
  280. }
  281. signal = new AS();
  282. abort(reason) {
  283. if (this.signal.aborted)
  284. return;
  285. //@ts-ignore
  286. this.signal.reason = reason;
  287. //@ts-ignore
  288. this.signal.aborted = true;
  289. //@ts-ignore
  290. for (const fn of this.signal._onabort) {
  291. fn(reason);
  292. }
  293. this.signal.onabort?.(reason);
  294. }
  295. };
  296. let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
  297. const warnACPolyfill = () => {
  298. if (!printACPolyfillWarning)
  299. return;
  300. printACPolyfillWarning = false;
  301. emitWarning('AbortController is not defined. If using lru-cache in ' +
  302. 'node 14, load an AbortController polyfill from the ' +
  303. '`node-abort-controller` package. A minimal polyfill is ' +
  304. 'provided for use by LRUCache.fetch(), but it should not be ' +
  305. 'relied upon in other contexts (eg, passing it to other APIs that ' +
  306. 'use AbortController/AbortSignal might have undesirable effects). ' +
  307. 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
  308. };
  309. }
  310. /* c8 ignore stop */
  311. const shouldWarn = (code) => !warned.has(code);
  312. const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
  313. /* c8 ignore start */
  314. // This is a little bit ridiculous, tbh.
  315. // The maximum array length is 2^32-1 or thereabouts on most JS impls.
  316. // And well before that point, you're caching the entire world, I mean,
  317. // that's ~32GB of just integers for the next/prev links, plus whatever
  318. // else to hold that many keys and values. Just filling the memory with
  319. // zeroes at init time is brutal when you get that big.
  320. // But why not be complete?
  321. // Maybe in the future, these limits will have expanded.
  322. const getUintArray = (max) => !isPosInt(max)
  323. ? null
  324. : max <= Math.pow(2, 8)
  325. ? Uint8Array
  326. : max <= Math.pow(2, 16)
  327. ? Uint16Array
  328. : max <= Math.pow(2, 32)
  329. ? Uint32Array
  330. : max <= Number.MAX_SAFE_INTEGER
  331. ? ZeroArray
  332. : null;
  333. /* c8 ignore stop */
  334. class ZeroArray extends Array {
  335. constructor(size) {
  336. super(size);
  337. this.fill(0);
  338. }
  339. }
  340. class Stack {
  341. heap;
  342. length;
  343. // private constructor
  344. static #constructing = false;
  345. static create(max) {
  346. const HeapCls = getUintArray(max);
  347. if (!HeapCls)
  348. return [];
  349. Stack.#constructing = true;
  350. const s = new Stack(max, HeapCls);
  351. Stack.#constructing = false;
  352. return s;
  353. }
  354. constructor(max, HeapCls) {
  355. /* c8 ignore start */
  356. if (!Stack.#constructing) {
  357. throw new TypeError('instantiate Stack using Stack.create(n)');
  358. }
  359. /* c8 ignore stop */
  360. this.heap = new HeapCls(max);
  361. this.length = 0;
  362. }
  363. push(n) {
  364. this.heap[this.length++] = n;
  365. }
  366. pop() {
  367. return this.heap[--this.length];
  368. }
  369. }
  370. /**
  371. * Default export, the thing you're using this module to get.
  372. *
  373. * All properties from the options object (with the exception of
  374. * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
  375. * normal public members. (`max` and `maxBase` are read-only getters.)
  376. * Changing any of these will alter the defaults for subsequent method calls,
  377. * but is otherwise safe.
  378. */
  379. class LRUCache {
  380. // properties coming in from the options of these, only max and maxSize
  381. // really *need* to be protected. The rest can be modified, as they just
  382. // set defaults for various methods.
  383. #max;
  384. #maxSize;
  385. #dispose;
  386. #disposeAfter;
  387. #fetchMethod;
  388. /**
  389. * {@link LRUCache.OptionsBase.ttl}
  390. */
  391. ttl;
  392. /**
  393. * {@link LRUCache.OptionsBase.ttlResolution}
  394. */
  395. ttlResolution;
  396. /**
  397. * {@link LRUCache.OptionsBase.ttlAutopurge}
  398. */
  399. ttlAutopurge;
  400. /**
  401. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  402. */
  403. updateAgeOnGet;
  404. /**
  405. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  406. */
  407. updateAgeOnHas;
  408. /**
  409. * {@link LRUCache.OptionsBase.allowStale}
  410. */
  411. allowStale;
  412. /**
  413. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  414. */
  415. noDisposeOnSet;
  416. /**
  417. * {@link LRUCache.OptionsBase.noUpdateTTL}
  418. */
  419. noUpdateTTL;
  420. /**
  421. * {@link LRUCache.OptionsBase.maxEntrySize}
  422. */
  423. maxEntrySize;
  424. /**
  425. * {@link LRUCache.OptionsBase.sizeCalculation}
  426. */
  427. sizeCalculation;
  428. /**
  429. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  430. */
  431. noDeleteOnFetchRejection;
  432. /**
  433. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  434. */
  435. noDeleteOnStaleGet;
  436. /**
  437. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  438. */
  439. allowStaleOnFetchAbort;
  440. /**
  441. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  442. */
  443. allowStaleOnFetchRejection;
  444. /**
  445. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  446. */
  447. ignoreFetchAbort;
  448. // computed properties
  449. #size;
  450. #calculatedSize;
  451. #keyMap;
  452. #keyList;
  453. #valList;
  454. #next;
  455. #prev;
  456. #head;
  457. #tail;
  458. #free;
  459. #disposed;
  460. #sizes;
  461. #starts;
  462. #ttls;
  463. #hasDispose;
  464. #hasFetchMethod;
  465. #hasDisposeAfter;
  466. /**
  467. * Do not call this method unless you need to inspect the
  468. * inner workings of the cache. If anything returned by this
  469. * object is modified in any way, strange breakage may occur.
  470. *
  471. * These fields are private for a reason!
  472. *
  473. * @internal
  474. */
  475. static unsafeExposeInternals(c) {
  476. return {
  477. // properties
  478. starts: c.#starts,
  479. ttls: c.#ttls,
  480. sizes: c.#sizes,
  481. keyMap: c.#keyMap,
  482. keyList: c.#keyList,
  483. valList: c.#valList,
  484. next: c.#next,
  485. prev: c.#prev,
  486. get head() {
  487. return c.#head;
  488. },
  489. get tail() {
  490. return c.#tail;
  491. },
  492. free: c.#free,
  493. // methods
  494. isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
  495. backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
  496. moveToTail: (index) => c.#moveToTail(index),
  497. indexes: (options) => c.#indexes(options),
  498. rindexes: (options) => c.#rindexes(options),
  499. isStale: (index) => c.#isStale(index),
  500. };
  501. }
  502. // Protected read-only members
  503. /**
  504. * {@link LRUCache.OptionsBase.max} (read-only)
  505. */
  506. get max() {
  507. return this.#max;
  508. }
  509. /**
  510. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  511. */
  512. get maxSize() {
  513. return this.#maxSize;
  514. }
  515. /**
  516. * The total computed size of items in the cache (read-only)
  517. */
  518. get calculatedSize() {
  519. return this.#calculatedSize;
  520. }
  521. /**
  522. * The number of items stored in the cache (read-only)
  523. */
  524. get size() {
  525. return this.#size;
  526. }
  527. /**
  528. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  529. */
  530. get fetchMethod() {
  531. return this.#fetchMethod;
  532. }
  533. /**
  534. * {@link LRUCache.OptionsBase.dispose} (read-only)
  535. */
  536. get dispose() {
  537. return this.#dispose;
  538. }
  539. /**
  540. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  541. */
  542. get disposeAfter() {
  543. return this.#disposeAfter;
  544. }
  545. constructor(options) {
  546. const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
  547. if (max !== 0 && !isPosInt(max)) {
  548. throw new TypeError('max option must be a nonnegative integer');
  549. }
  550. const UintArray = max ? getUintArray(max) : Array;
  551. if (!UintArray) {
  552. throw new Error('invalid max value: ' + max);
  553. }
  554. this.#max = max;
  555. this.#maxSize = maxSize;
  556. this.maxEntrySize = maxEntrySize || this.#maxSize;
  557. this.sizeCalculation = sizeCalculation;
  558. if (this.sizeCalculation) {
  559. if (!this.#maxSize && !this.maxEntrySize) {
  560. throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
  561. }
  562. if (typeof this.sizeCalculation !== 'function') {
  563. throw new TypeError('sizeCalculation set to non-function');
  564. }
  565. }
  566. if (fetchMethod !== undefined &&
  567. typeof fetchMethod !== 'function') {
  568. throw new TypeError('fetchMethod must be a function if specified');
  569. }
  570. this.#fetchMethod = fetchMethod;
  571. this.#hasFetchMethod = !!fetchMethod;
  572. this.#keyMap = new Map();
  573. this.#keyList = new Array(max).fill(undefined);
  574. this.#valList = new Array(max).fill(undefined);
  575. this.#next = new UintArray(max);
  576. this.#prev = new UintArray(max);
  577. this.#head = 0;
  578. this.#tail = 0;
  579. this.#free = Stack.create(max);
  580. this.#size = 0;
  581. this.#calculatedSize = 0;
  582. if (typeof dispose === 'function') {
  583. this.#dispose = dispose;
  584. }
  585. if (typeof disposeAfter === 'function') {
  586. this.#disposeAfter = disposeAfter;
  587. this.#disposed = [];
  588. }
  589. else {
  590. this.#disposeAfter = undefined;
  591. this.#disposed = undefined;
  592. }
  593. this.#hasDispose = !!this.#dispose;
  594. this.#hasDisposeAfter = !!this.#disposeAfter;
  595. this.noDisposeOnSet = !!noDisposeOnSet;
  596. this.noUpdateTTL = !!noUpdateTTL;
  597. this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
  598. this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
  599. this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
  600. this.ignoreFetchAbort = !!ignoreFetchAbort;
  601. // NB: maxEntrySize is set to maxSize if it's set
  602. if (this.maxEntrySize !== 0) {
  603. if (this.#maxSize !== 0) {
  604. if (!isPosInt(this.#maxSize)) {
  605. throw new TypeError('maxSize must be a positive integer if specified');
  606. }
  607. }
  608. if (!isPosInt(this.maxEntrySize)) {
  609. throw new TypeError('maxEntrySize must be a positive integer if specified');
  610. }
  611. this.#initializeSizeTracking();
  612. }
  613. this.allowStale = !!allowStale;
  614. this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
  615. this.updateAgeOnGet = !!updateAgeOnGet;
  616. this.updateAgeOnHas = !!updateAgeOnHas;
  617. this.ttlResolution =
  618. isPosInt(ttlResolution) || ttlResolution === 0
  619. ? ttlResolution
  620. : 1;
  621. this.ttlAutopurge = !!ttlAutopurge;
  622. this.ttl = ttl || 0;
  623. if (this.ttl) {
  624. if (!isPosInt(this.ttl)) {
  625. throw new TypeError('ttl must be a positive integer if specified');
  626. }
  627. this.#initializeTTLTracking();
  628. }
  629. // do not allow completely unbounded caches
  630. if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
  631. throw new TypeError('At least one of max, maxSize, or ttl is required');
  632. }
  633. if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
  634. const code = 'LRU_CACHE_UNBOUNDED';
  635. if (shouldWarn(code)) {
  636. warned.add(code);
  637. const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
  638. 'result in unbounded memory consumption.';
  639. emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
  640. }
  641. }
  642. }
  643. /**
  644. * Return the remaining TTL time for a given entry key
  645. */
  646. getRemainingTTL(key) {
  647. return this.#keyMap.has(key) ? Infinity : 0;
  648. }
  649. #initializeTTLTracking() {
  650. const ttls = new ZeroArray(this.#max);
  651. const starts = new ZeroArray(this.#max);
  652. this.#ttls = ttls;
  653. this.#starts = starts;
  654. this.#setItemTTL = (index, ttl, start = perf.now()) => {
  655. starts[index] = ttl !== 0 ? start : 0;
  656. ttls[index] = ttl;
  657. if (ttl !== 0 && this.ttlAutopurge) {
  658. const t = setTimeout(() => {
  659. if (this.#isStale(index)) {
  660. this.delete(this.#keyList[index]);
  661. }
  662. }, ttl + 1);
  663. // unref() not supported on all platforms
  664. /* c8 ignore start */
  665. if (t.unref) {
  666. t.unref();
  667. }
  668. /* c8 ignore stop */
  669. }
  670. };
  671. this.#updateItemAge = index => {
  672. starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  673. };
  674. this.#statusTTL = (status, index) => {
  675. if (ttls[index]) {
  676. const ttl = ttls[index];
  677. const start = starts[index];
  678. /* c8 ignore next */
  679. if (!ttl || !start)
  680. return;
  681. status.ttl = ttl;
  682. status.start = start;
  683. status.now = cachedNow || getNow();
  684. const age = status.now - start;
  685. status.remainingTTL = ttl - age;
  686. }
  687. };
  688. // debounce calls to perf.now() to 1s so we're not hitting
  689. // that costly call repeatedly.
  690. let cachedNow = 0;
  691. const getNow = () => {
  692. const n = perf.now();
  693. if (this.ttlResolution > 0) {
  694. cachedNow = n;
  695. const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
  696. // not available on all platforms
  697. /* c8 ignore start */
  698. if (t.unref) {
  699. t.unref();
  700. }
  701. /* c8 ignore stop */
  702. }
  703. return n;
  704. };
  705. this.getRemainingTTL = key => {
  706. const index = this.#keyMap.get(key);
  707. if (index === undefined) {
  708. return 0;
  709. }
  710. const ttl = ttls[index];
  711. const start = starts[index];
  712. if (!ttl || !start) {
  713. return Infinity;
  714. }
  715. const age = (cachedNow || getNow()) - start;
  716. return ttl - age;
  717. };
  718. this.#isStale = index => {
  719. const s = starts[index];
  720. const t = ttls[index];
  721. return !!t && !!s && (cachedNow || getNow()) - s > t;
  722. };
  723. }
  724. // conditionally set private methods related to TTL
  725. #updateItemAge = () => { };
  726. #statusTTL = () => { };
  727. #setItemTTL = () => { };
  728. /* c8 ignore stop */
  729. #isStale = () => false;
  730. #initializeSizeTracking() {
  731. const sizes = new ZeroArray(this.#max);
  732. this.#calculatedSize = 0;
  733. this.#sizes = sizes;
  734. this.#removeItemSize = index => {
  735. this.#calculatedSize -= sizes[index];
  736. sizes[index] = 0;
  737. };
  738. this.#requireSize = (k, v, size, sizeCalculation) => {
  739. // provisionally accept background fetches.
  740. // actual value size will be checked when they return.
  741. if (this.#isBackgroundFetch(v)) {
  742. return 0;
  743. }
  744. if (!isPosInt(size)) {
  745. if (sizeCalculation) {
  746. if (typeof sizeCalculation !== 'function') {
  747. throw new TypeError('sizeCalculation must be a function');
  748. }
  749. size = sizeCalculation(v, k);
  750. if (!isPosInt(size)) {
  751. throw new TypeError('sizeCalculation return invalid (expect positive integer)');
  752. }
  753. }
  754. else {
  755. throw new TypeError('invalid size value (must be positive integer). ' +
  756. 'When maxSize or maxEntrySize is used, sizeCalculation ' +
  757. 'or size must be set.');
  758. }
  759. }
  760. return size;
  761. };
  762. this.#addItemSize = (index, size, status) => {
  763. sizes[index] = size;
  764. if (this.#maxSize) {
  765. const maxSize = this.#maxSize - sizes[index];
  766. while (this.#calculatedSize > maxSize) {
  767. this.#evict(true);
  768. }
  769. }
  770. this.#calculatedSize += sizes[index];
  771. if (status) {
  772. status.entrySize = size;
  773. status.totalCalculatedSize = this.#calculatedSize;
  774. }
  775. };
  776. }
  777. #removeItemSize = _i => { };
  778. #addItemSize = (_i, _s, _st) => { };
  779. #requireSize = (_k, _v, size, sizeCalculation) => {
  780. if (size || sizeCalculation) {
  781. throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
  782. }
  783. return 0;
  784. };
  785. *#indexes({ allowStale = this.allowStale } = {}) {
  786. if (this.#size) {
  787. for (let i = this.#tail; true;) {
  788. if (!this.#isValidIndex(i)) {
  789. break;
  790. }
  791. if (allowStale || !this.#isStale(i)) {
  792. yield i;
  793. }
  794. if (i === this.#head) {
  795. break;
  796. }
  797. else {
  798. i = this.#prev[i];
  799. }
  800. }
  801. }
  802. }
  803. *#rindexes({ allowStale = this.allowStale } = {}) {
  804. if (this.#size) {
  805. for (let i = this.#head; true;) {
  806. if (!this.#isValidIndex(i)) {
  807. break;
  808. }
  809. if (allowStale || !this.#isStale(i)) {
  810. yield i;
  811. }
  812. if (i === this.#tail) {
  813. break;
  814. }
  815. else {
  816. i = this.#next[i];
  817. }
  818. }
  819. }
  820. }
  821. #isValidIndex(index) {
  822. return (index !== undefined &&
  823. this.#keyMap.get(this.#keyList[index]) === index);
  824. }
  825. /**
  826. * Return a generator yielding `[key, value]` pairs,
  827. * in order from most recently used to least recently used.
  828. */
  829. *entries() {
  830. for (const i of this.#indexes()) {
  831. if (this.#valList[i] !== undefined &&
  832. this.#keyList[i] !== undefined &&
  833. !this.#isBackgroundFetch(this.#valList[i])) {
  834. yield [this.#keyList[i], this.#valList[i]];
  835. }
  836. }
  837. }
  838. /**
  839. * Inverse order version of {@link LRUCache.entries}
  840. *
  841. * Return a generator yielding `[key, value]` pairs,
  842. * in order from least recently used to most recently used.
  843. */
  844. *rentries() {
  845. for (const i of this.#rindexes()) {
  846. if (this.#valList[i] !== undefined &&
  847. this.#keyList[i] !== undefined &&
  848. !this.#isBackgroundFetch(this.#valList[i])) {
  849. yield [this.#keyList[i], this.#valList[i]];
  850. }
  851. }
  852. }
  853. /**
  854. * Return a generator yielding the keys in the cache,
  855. * in order from most recently used to least recently used.
  856. */
  857. *keys() {
  858. for (const i of this.#indexes()) {
  859. const k = this.#keyList[i];
  860. if (k !== undefined &&
  861. !this.#isBackgroundFetch(this.#valList[i])) {
  862. yield k;
  863. }
  864. }
  865. }
  866. /**
  867. * Inverse order version of {@link LRUCache.keys}
  868. *
  869. * Return a generator yielding the keys in the cache,
  870. * in order from least recently used to most recently used.
  871. */
  872. *rkeys() {
  873. for (const i of this.#rindexes()) {
  874. const k = this.#keyList[i];
  875. if (k !== undefined &&
  876. !this.#isBackgroundFetch(this.#valList[i])) {
  877. yield k;
  878. }
  879. }
  880. }
  881. /**
  882. * Return a generator yielding the values in the cache,
  883. * in order from most recently used to least recently used.
  884. */
  885. *values() {
  886. for (const i of this.#indexes()) {
  887. const v = this.#valList[i];
  888. if (v !== undefined &&
  889. !this.#isBackgroundFetch(this.#valList[i])) {
  890. yield this.#valList[i];
  891. }
  892. }
  893. }
  894. /**
  895. * Inverse order version of {@link LRUCache.values}
  896. *
  897. * Return a generator yielding the values in the cache,
  898. * in order from least recently used to most recently used.
  899. */
  900. *rvalues() {
  901. for (const i of this.#rindexes()) {
  902. const v = this.#valList[i];
  903. if (v !== undefined &&
  904. !this.#isBackgroundFetch(this.#valList[i])) {
  905. yield this.#valList[i];
  906. }
  907. }
  908. }
  909. /**
  910. * Iterating over the cache itself yields the same results as
  911. * {@link LRUCache.entries}
  912. */
  913. [Symbol.iterator]() {
  914. return this.entries();
  915. }
  916. /**
  917. * Find a value for which the supplied fn method returns a truthy value,
  918. * similar to Array.find(). fn is called as fn(value, key, cache).
  919. */
  920. find(fn, getOptions = {}) {
  921. for (const i of this.#indexes()) {
  922. const v = this.#valList[i];
  923. const value = this.#isBackgroundFetch(v)
  924. ? v.__staleWhileFetching
  925. : v;
  926. if (value === undefined)
  927. continue;
  928. if (fn(value, this.#keyList[i], this)) {
  929. return this.get(this.#keyList[i], getOptions);
  930. }
  931. }
  932. }
  933. /**
  934. * Call the supplied function on each item in the cache, in order from
  935. * most recently used to least recently used. fn is called as
  936. * fn(value, key, cache). Does not update age or recenty of use.
  937. * Does not iterate over stale values.
  938. */
  939. forEach(fn, thisp = this) {
  940. for (const i of this.#indexes()) {
  941. const v = this.#valList[i];
  942. const value = this.#isBackgroundFetch(v)
  943. ? v.__staleWhileFetching
  944. : v;
  945. if (value === undefined)
  946. continue;
  947. fn.call(thisp, value, this.#keyList[i], this);
  948. }
  949. }
  950. /**
  951. * The same as {@link LRUCache.forEach} but items are iterated over in
  952. * reverse order. (ie, less recently used items are iterated over first.)
  953. */
  954. rforEach(fn, thisp = this) {
  955. for (const i of this.#rindexes()) {
  956. const v = this.#valList[i];
  957. const value = this.#isBackgroundFetch(v)
  958. ? v.__staleWhileFetching
  959. : v;
  960. if (value === undefined)
  961. continue;
  962. fn.call(thisp, value, this.#keyList[i], this);
  963. }
  964. }
  965. /**
  966. * Delete any stale entries. Returns true if anything was removed,
  967. * false otherwise.
  968. */
  969. purgeStale() {
  970. let deleted = false;
  971. for (const i of this.#rindexes({ allowStale: true })) {
  972. if (this.#isStale(i)) {
  973. this.delete(this.#keyList[i]);
  974. deleted = true;
  975. }
  976. }
  977. return deleted;
  978. }
  979. /**
  980. * Get the extended info about a given entry, to get its value, size, and
  981. * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a
  982. * single key. Always returns stale values, if their info is found in the
  983. * cache, so be sure to check for expired TTLs if relevant.
  984. */
  985. info(key) {
  986. const i = this.#keyMap.get(key);
  987. if (i === undefined)
  988. return undefined;
  989. const v = this.#valList[i];
  990. const value = this.#isBackgroundFetch(v)
  991. ? v.__staleWhileFetching
  992. : v;
  993. if (value === undefined)
  994. return undefined;
  995. const entry = { value };
  996. if (this.#ttls && this.#starts) {
  997. const ttl = this.#ttls[i];
  998. const start = this.#starts[i];
  999. if (ttl && start) {
  1000. const remain = ttl - (perf.now() - start);
  1001. entry.ttl = remain;
  1002. entry.start = Date.now();
  1003. }
  1004. }
  1005. if (this.#sizes) {
  1006. entry.size = this.#sizes[i];
  1007. }
  1008. return entry;
  1009. }
  1010. /**
  1011. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  1012. * passed to cache.load()
  1013. */
  1014. dump() {
  1015. const arr = [];
  1016. for (const i of this.#indexes({ allowStale: true })) {
  1017. const key = this.#keyList[i];
  1018. const v = this.#valList[i];
  1019. const value = this.#isBackgroundFetch(v)
  1020. ? v.__staleWhileFetching
  1021. : v;
  1022. if (value === undefined || key === undefined)
  1023. continue;
  1024. const entry = { value };
  1025. if (this.#ttls && this.#starts) {
  1026. entry.ttl = this.#ttls[i];
  1027. // always dump the start relative to a portable timestamp
  1028. // it's ok for this to be a bit slow, it's a rare operation.
  1029. const age = perf.now() - this.#starts[i];
  1030. entry.start = Math.floor(Date.now() - age);
  1031. }
  1032. if (this.#sizes) {
  1033. entry.size = this.#sizes[i];
  1034. }
  1035. arr.unshift([key, entry]);
  1036. }
  1037. return arr;
  1038. }
  1039. /**
  1040. * Reset the cache and load in the items in entries in the order listed.
  1041. * Note that the shape of the resulting cache may be different if the
  1042. * same options are not used in both caches.
  1043. */
  1044. load(arr) {
  1045. this.clear();
  1046. for (const [key, entry] of arr) {
  1047. if (entry.start) {
  1048. // entry.start is a portable timestamp, but we may be using
  1049. // node's performance.now(), so calculate the offset, so that
  1050. // we get the intended remaining TTL, no matter how long it's
  1051. // been on ice.
  1052. //
  1053. // it's ok for this to be a bit slow, it's a rare operation.
  1054. const age = Date.now() - entry.start;
  1055. entry.start = perf.now() - age;
  1056. }
  1057. this.set(key, entry.value, entry);
  1058. }
  1059. }
  1060. /**
  1061. * Add a value to the cache.
  1062. *
  1063. * Note: if `undefined` is specified as a value, this is an alias for
  1064. * {@link LRUCache#delete}
  1065. */
  1066. set(k, v, setOptions = {}) {
  1067. if (v === undefined) {
  1068. this.delete(k);
  1069. return this;
  1070. }
  1071. const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
  1072. let { noUpdateTTL = this.noUpdateTTL } = setOptions;
  1073. const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
  1074. // if the item doesn't fit, don't do anything
  1075. // NB: maxEntrySize set to maxSize by default
  1076. if (this.maxEntrySize && size > this.maxEntrySize) {
  1077. if (status) {
  1078. status.set = 'miss';
  1079. status.maxEntrySizeExceeded = true;
  1080. }
  1081. // have to delete, in case something is there already.
  1082. this.delete(k);
  1083. return this;
  1084. }
  1085. let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
  1086. if (index === undefined) {
  1087. // addition
  1088. index = (this.#size === 0
  1089. ? this.#tail
  1090. : this.#free.length !== 0
  1091. ? this.#free.pop()
  1092. : this.#size === this.#max
  1093. ? this.#evict(false)
  1094. : this.#size);
  1095. this.#keyList[index] = k;
  1096. this.#valList[index] = v;
  1097. this.#keyMap.set(k, index);
  1098. this.#next[this.#tail] = index;
  1099. this.#prev[index] = this.#tail;
  1100. this.#tail = index;
  1101. this.#size++;
  1102. this.#addItemSize(index, size, status);
  1103. if (status)
  1104. status.set = 'add';
  1105. noUpdateTTL = false;
  1106. }
  1107. else {
  1108. // update
  1109. this.#moveToTail(index);
  1110. const oldVal = this.#valList[index];
  1111. if (v !== oldVal) {
  1112. if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
  1113. oldVal.__abortController.abort(new Error('replaced'));
  1114. const { __staleWhileFetching: s } = oldVal;
  1115. if (s !== undefined && !noDisposeOnSet) {
  1116. if (this.#hasDispose) {
  1117. this.#dispose?.(s, k, 'set');
  1118. }
  1119. if (this.#hasDisposeAfter) {
  1120. this.#disposed?.push([s, k, 'set']);
  1121. }
  1122. }
  1123. }
  1124. else if (!noDisposeOnSet) {
  1125. if (this.#hasDispose) {
  1126. this.#dispose?.(oldVal, k, 'set');
  1127. }
  1128. if (this.#hasDisposeAfter) {
  1129. this.#disposed?.push([oldVal, k, 'set']);
  1130. }
  1131. }
  1132. this.#removeItemSize(index);
  1133. this.#addItemSize(index, size, status);
  1134. this.#valList[index] = v;
  1135. if (status) {
  1136. status.set = 'replace';
  1137. const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
  1138. ? oldVal.__staleWhileFetching
  1139. : oldVal;
  1140. if (oldValue !== undefined)
  1141. status.oldValue = oldValue;
  1142. }
  1143. }
  1144. else if (status) {
  1145. status.set = 'update';
  1146. }
  1147. }
  1148. if (ttl !== 0 && !this.#ttls) {
  1149. this.#initializeTTLTracking();
  1150. }
  1151. if (this.#ttls) {
  1152. if (!noUpdateTTL) {
  1153. this.#setItemTTL(index, ttl, start);
  1154. }
  1155. if (status)
  1156. this.#statusTTL(status, index);
  1157. }
  1158. if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
  1159. const dt = this.#disposed;
  1160. let task;
  1161. while ((task = dt?.shift())) {
  1162. this.#disposeAfter?.(...task);
  1163. }
  1164. }
  1165. return this;
  1166. }
  1167. /**
  1168. * Evict the least recently used item, returning its value or
  1169. * `undefined` if cache is empty.
  1170. */
  1171. pop() {
  1172. try {
  1173. while (this.#size) {
  1174. const val = this.#valList[this.#head];
  1175. this.#evict(true);
  1176. if (this.#isBackgroundFetch(val)) {
  1177. if (val.__staleWhileFetching) {
  1178. return val.__staleWhileFetching;
  1179. }
  1180. }
  1181. else if (val !== undefined) {
  1182. return val;
  1183. }
  1184. }
  1185. }
  1186. finally {
  1187. if (this.#hasDisposeAfter && this.#disposed) {
  1188. const dt = this.#disposed;
  1189. let task;
  1190. while ((task = dt?.shift())) {
  1191. this.#disposeAfter?.(...task);
  1192. }
  1193. }
  1194. }
  1195. }
  1196. #evict(free) {
  1197. const head = this.#head;
  1198. const k = this.#keyList[head];
  1199. const v = this.#valList[head];
  1200. if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
  1201. v.__abortController.abort(new Error('evicted'));
  1202. }
  1203. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1204. if (this.#hasDispose) {
  1205. this.#dispose?.(v, k, 'evict');
  1206. }
  1207. if (this.#hasDisposeAfter) {
  1208. this.#disposed?.push([v, k, 'evict']);
  1209. }
  1210. }
  1211. this.#removeItemSize(head);
  1212. // if we aren't about to use the index, then null these out
  1213. if (free) {
  1214. this.#keyList[head] = undefined;
  1215. this.#valList[head] = undefined;
  1216. this.#free.push(head);
  1217. }
  1218. if (this.#size === 1) {
  1219. this.#head = this.#tail = 0;
  1220. this.#free.length = 0;
  1221. }
  1222. else {
  1223. this.#head = this.#next[head];
  1224. }
  1225. this.#keyMap.delete(k);
  1226. this.#size--;
  1227. return head;
  1228. }
  1229. /**
  1230. * Check if a key is in the cache, without updating the recency of use.
  1231. * Will return false if the item is stale, even though it is technically
  1232. * in the cache.
  1233. *
  1234. * Will not update item age unless
  1235. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  1236. */
  1237. has(k, hasOptions = {}) {
  1238. const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
  1239. const index = this.#keyMap.get(k);
  1240. if (index !== undefined) {
  1241. const v = this.#valList[index];
  1242. if (this.#isBackgroundFetch(v) &&
  1243. v.__staleWhileFetching === undefined) {
  1244. return false;
  1245. }
  1246. if (!this.#isStale(index)) {
  1247. if (updateAgeOnHas) {
  1248. this.#updateItemAge(index);
  1249. }
  1250. if (status) {
  1251. status.has = 'hit';
  1252. this.#statusTTL(status, index);
  1253. }
  1254. return true;
  1255. }
  1256. else if (status) {
  1257. status.has = 'stale';
  1258. this.#statusTTL(status, index);
  1259. }
  1260. }
  1261. else if (status) {
  1262. status.has = 'miss';
  1263. }
  1264. return false;
  1265. }
  1266. /**
  1267. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  1268. * items.
  1269. *
  1270. * Returns `undefined` if the item is stale, unless
  1271. * {@link LRUCache.OptionsBase.allowStale} is set.
  1272. */
  1273. peek(k, peekOptions = {}) {
  1274. const { allowStale = this.allowStale } = peekOptions;
  1275. const index = this.#keyMap.get(k);
  1276. if (index === undefined ||
  1277. (!allowStale && this.#isStale(index))) {
  1278. return;
  1279. }
  1280. const v = this.#valList[index];
  1281. // either stale and allowed, or forcing a refresh of non-stale value
  1282. return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  1283. }
  1284. #backgroundFetch(k, index, options, context) {
  1285. const v = index === undefined ? undefined : this.#valList[index];
  1286. if (this.#isBackgroundFetch(v)) {
  1287. return v;
  1288. }
  1289. const ac = new AC();
  1290. const { signal } = options;
  1291. // when/if our AC signals, then stop listening to theirs.
  1292. signal?.addEventListener('abort', () => ac.abort(signal.reason), {
  1293. signal: ac.signal,
  1294. });
  1295. const fetchOpts = {
  1296. signal: ac.signal,
  1297. options,
  1298. context,
  1299. };
  1300. const cb = (v, updateCache = false) => {
  1301. const { aborted } = ac.signal;
  1302. const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
  1303. if (options.status) {
  1304. if (aborted && !updateCache) {
  1305. options.status.fetchAborted = true;
  1306. options.status.fetchError = ac.signal.reason;
  1307. if (ignoreAbort)
  1308. options.status.fetchAbortIgnored = true;
  1309. }
  1310. else {
  1311. options.status.fetchResolved = true;
  1312. }
  1313. }
  1314. if (aborted && !ignoreAbort && !updateCache) {
  1315. return fetchFail(ac.signal.reason);
  1316. }
  1317. // either we didn't abort, and are still here, or we did, and ignored
  1318. const bf = p;
  1319. if (this.#valList[index] === p) {
  1320. if (v === undefined) {
  1321. if (bf.__staleWhileFetching) {
  1322. this.#valList[index] = bf.__staleWhileFetching;
  1323. }
  1324. else {
  1325. this.delete(k);
  1326. }
  1327. }
  1328. else {
  1329. if (options.status)
  1330. options.status.fetchUpdated = true;
  1331. this.set(k, v, fetchOpts.options);
  1332. }
  1333. }
  1334. return v;
  1335. };
  1336. const eb = (er) => {
  1337. if (options.status) {
  1338. options.status.fetchRejected = true;
  1339. options.status.fetchError = er;
  1340. }
  1341. return fetchFail(er);
  1342. };
  1343. const fetchFail = (er) => {
  1344. const { aborted } = ac.signal;
  1345. const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
  1346. const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
  1347. const noDelete = allowStale || options.noDeleteOnFetchRejection;
  1348. const bf = p;
  1349. if (this.#valList[index] === p) {
  1350. // if we allow stale on fetch rejections, then we need to ensure that
  1351. // the stale value is not removed from the cache when the fetch fails.
  1352. const del = !noDelete || bf.__staleWhileFetching === undefined;
  1353. if (del) {
  1354. this.delete(k);
  1355. }
  1356. else if (!allowStaleAborted) {
  1357. // still replace the *promise* with the stale value,
  1358. // since we are done with the promise at this point.
  1359. // leave it untouched if we're still waiting for an
  1360. // aborted background fetch that hasn't yet returned.
  1361. this.#valList[index] = bf.__staleWhileFetching;
  1362. }
  1363. }
  1364. if (allowStale) {
  1365. if (options.status && bf.__staleWhileFetching !== undefined) {
  1366. options.status.returnedStale = true;
  1367. }
  1368. return bf.__staleWhileFetching;
  1369. }
  1370. else if (bf.__returned === bf) {
  1371. throw er;
  1372. }
  1373. };
  1374. const pcall = (res, rej) => {
  1375. const fmp = this.#fetchMethod?.(k, v, fetchOpts);
  1376. if (fmp && fmp instanceof Promise) {
  1377. fmp.then(v => res(v === undefined ? undefined : v), rej);
  1378. }
  1379. // ignored, we go until we finish, regardless.
  1380. // defer check until we are actually aborting,
  1381. // so fetchMethod can override.
  1382. ac.signal.addEventListener('abort', () => {
  1383. if (!options.ignoreFetchAbort ||
  1384. options.allowStaleOnFetchAbort) {
  1385. res(undefined);
  1386. // when it eventually resolves, update the cache.
  1387. if (options.allowStaleOnFetchAbort) {
  1388. res = v => cb(v, true);
  1389. }
  1390. }
  1391. });
  1392. };
  1393. if (options.status)
  1394. options.status.fetchDispatched = true;
  1395. const p = new Promise(pcall).then(cb, eb);
  1396. const bf = Object.assign(p, {
  1397. __abortController: ac,
  1398. __staleWhileFetching: v,
  1399. __returned: undefined,
  1400. });
  1401. if (index === undefined) {
  1402. // internal, don't expose status.
  1403. this.set(k, bf, { ...fetchOpts.options, status: undefined });
  1404. index = this.#keyMap.get(k);
  1405. }
  1406. else {
  1407. this.#valList[index] = bf;
  1408. }
  1409. return bf;
  1410. }
  1411. #isBackgroundFetch(p) {
  1412. if (!this.#hasFetchMethod)
  1413. return false;
  1414. const b = p;
  1415. return (!!b &&
  1416. b instanceof Promise &&
  1417. b.hasOwnProperty('__staleWhileFetching') &&
  1418. b.__abortController instanceof AC);
  1419. }
  1420. async fetch(k, fetchOptions = {}) {
  1421. const {
  1422. // get options
  1423. allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
  1424. // set options
  1425. ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
  1426. // fetch exclusive options
  1427. noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
  1428. if (!this.#hasFetchMethod) {
  1429. if (status)
  1430. status.fetch = 'get';
  1431. return this.get(k, {
  1432. allowStale,
  1433. updateAgeOnGet,
  1434. noDeleteOnStaleGet,
  1435. status,
  1436. });
  1437. }
  1438. const options = {
  1439. allowStale,
  1440. updateAgeOnGet,
  1441. noDeleteOnStaleGet,
  1442. ttl,
  1443. noDisposeOnSet,
  1444. size,
  1445. sizeCalculation,
  1446. noUpdateTTL,
  1447. noDeleteOnFetchRejection,
  1448. allowStaleOnFetchRejection,
  1449. allowStaleOnFetchAbort,
  1450. ignoreFetchAbort,
  1451. status,
  1452. signal,
  1453. };
  1454. let index = this.#keyMap.get(k);
  1455. if (index === undefined) {
  1456. if (status)
  1457. status.fetch = 'miss';
  1458. const p = this.#backgroundFetch(k, index, options, context);
  1459. return (p.__returned = p);
  1460. }
  1461. else {
  1462. // in cache, maybe already fetching
  1463. const v = this.#valList[index];
  1464. if (this.#isBackgroundFetch(v)) {
  1465. const stale = allowStale && v.__staleWhileFetching !== undefined;
  1466. if (status) {
  1467. status.fetch = 'inflight';
  1468. if (stale)
  1469. status.returnedStale = true;
  1470. }
  1471. return stale ? v.__staleWhileFetching : (v.__returned = v);
  1472. }
  1473. // if we force a refresh, that means do NOT serve the cached value,
  1474. // unless we are already in the process of refreshing the cache.
  1475. const isStale = this.#isStale(index);
  1476. if (!forceRefresh && !isStale) {
  1477. if (status)
  1478. status.fetch = 'hit';
  1479. this.#moveToTail(index);
  1480. if (updateAgeOnGet) {
  1481. this.#updateItemAge(index);
  1482. }
  1483. if (status)
  1484. this.#statusTTL(status, index);
  1485. return v;
  1486. }
  1487. // ok, it is stale or a forced refresh, and not already fetching.
  1488. // refresh the cache.
  1489. const p = this.#backgroundFetch(k, index, options, context);
  1490. const hasStale = p.__staleWhileFetching !== undefined;
  1491. const staleVal = hasStale && allowStale;
  1492. if (status) {
  1493. status.fetch = isStale ? 'stale' : 'refresh';
  1494. if (staleVal && isStale)
  1495. status.returnedStale = true;
  1496. }
  1497. return staleVal ? p.__staleWhileFetching : (p.__returned = p);
  1498. }
  1499. }
  1500. /**
  1501. * Return a value from the cache. Will update the recency of the cache
  1502. * entry found.
  1503. *
  1504. * If the key is not found, get() will return `undefined`.
  1505. */
  1506. get(k, getOptions = {}) {
  1507. const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
  1508. const index = this.#keyMap.get(k);
  1509. if (index !== undefined) {
  1510. const value = this.#valList[index];
  1511. const fetching = this.#isBackgroundFetch(value);
  1512. if (status)
  1513. this.#statusTTL(status, index);
  1514. if (this.#isStale(index)) {
  1515. if (status)
  1516. status.get = 'stale';
  1517. // delete only if not an in-flight background fetch
  1518. if (!fetching) {
  1519. if (!noDeleteOnStaleGet) {
  1520. this.delete(k);
  1521. }
  1522. if (status && allowStale)
  1523. status.returnedStale = true;
  1524. return allowStale ? value : undefined;
  1525. }
  1526. else {
  1527. if (status &&
  1528. allowStale &&
  1529. value.__staleWhileFetching !== undefined) {
  1530. status.returnedStale = true;
  1531. }
  1532. return allowStale ? value.__staleWhileFetching : undefined;
  1533. }
  1534. }
  1535. else {
  1536. if (status)
  1537. status.get = 'hit';
  1538. // if we're currently fetching it, we don't actually have it yet
  1539. // it's not stale, which means this isn't a staleWhileRefetching.
  1540. // If it's not stale, and fetching, AND has a __staleWhileFetching
  1541. // value, then that means the user fetched with {forceRefresh:true},
  1542. // so it's safe to return that value.
  1543. if (fetching) {
  1544. return value.__staleWhileFetching;
  1545. }
  1546. this.#moveToTail(index);
  1547. if (updateAgeOnGet) {
  1548. this.#updateItemAge(index);
  1549. }
  1550. return value;
  1551. }
  1552. }
  1553. else if (status) {
  1554. status.get = 'miss';
  1555. }
  1556. }
  1557. #connect(p, n) {
  1558. this.#prev[n] = p;
  1559. this.#next[p] = n;
  1560. }
  1561. #moveToTail(index) {
  1562. // if tail already, nothing to do
  1563. // if head, move head to next[index]
  1564. // else
  1565. // move next[prev[index]] to next[index] (head has no prev)
  1566. // move prev[next[index]] to prev[index]
  1567. // prev[index] = tail
  1568. // next[tail] = index
  1569. // tail = index
  1570. if (index !== this.#tail) {
  1571. if (index === this.#head) {
  1572. this.#head = this.#next[index];
  1573. }
  1574. else {
  1575. this.#connect(this.#prev[index], this.#next[index]);
  1576. }
  1577. this.#connect(this.#tail, index);
  1578. this.#tail = index;
  1579. }
  1580. }
  1581. /**
  1582. * Deletes a key out of the cache.
  1583. * Returns true if the key was deleted, false otherwise.
  1584. */
  1585. delete(k) {
  1586. let deleted = false;
  1587. if (this.#size !== 0) {
  1588. const index = this.#keyMap.get(k);
  1589. if (index !== undefined) {
  1590. deleted = true;
  1591. if (this.#size === 1) {
  1592. this.clear();
  1593. }
  1594. else {
  1595. this.#removeItemSize(index);
  1596. const v = this.#valList[index];
  1597. if (this.#isBackgroundFetch(v)) {
  1598. v.__abortController.abort(new Error('deleted'));
  1599. }
  1600. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1601. if (this.#hasDispose) {
  1602. this.#dispose?.(v, k, 'delete');
  1603. }
  1604. if (this.#hasDisposeAfter) {
  1605. this.#disposed?.push([v, k, 'delete']);
  1606. }
  1607. }
  1608. this.#keyMap.delete(k);
  1609. this.#keyList[index] = undefined;
  1610. this.#valList[index] = undefined;
  1611. if (index === this.#tail) {
  1612. this.#tail = this.#prev[index];
  1613. }
  1614. else if (index === this.#head) {
  1615. this.#head = this.#next[index];
  1616. }
  1617. else {
  1618. const pi = this.#prev[index];
  1619. this.#next[pi] = this.#next[index];
  1620. const ni = this.#next[index];
  1621. this.#prev[ni] = this.#prev[index];
  1622. }
  1623. this.#size--;
  1624. this.#free.push(index);
  1625. }
  1626. }
  1627. }
  1628. if (this.#hasDisposeAfter && this.#disposed?.length) {
  1629. const dt = this.#disposed;
  1630. let task;
  1631. while ((task = dt?.shift())) {
  1632. this.#disposeAfter?.(...task);
  1633. }
  1634. }
  1635. return deleted;
  1636. }
  1637. /**
  1638. * Clear the cache entirely, throwing away all values.
  1639. */
  1640. clear() {
  1641. for (const index of this.#rindexes({ allowStale: true })) {
  1642. const v = this.#valList[index];
  1643. if (this.#isBackgroundFetch(v)) {
  1644. v.__abortController.abort(new Error('deleted'));
  1645. }
  1646. else {
  1647. const k = this.#keyList[index];
  1648. if (this.#hasDispose) {
  1649. this.#dispose?.(v, k, 'delete');
  1650. }
  1651. if (this.#hasDisposeAfter) {
  1652. this.#disposed?.push([v, k, 'delete']);
  1653. }
  1654. }
  1655. }
  1656. this.#keyMap.clear();
  1657. this.#valList.fill(undefined);
  1658. this.#keyList.fill(undefined);
  1659. if (this.#ttls && this.#starts) {
  1660. this.#ttls.fill(0);
  1661. this.#starts.fill(0);
  1662. }
  1663. if (this.#sizes) {
  1664. this.#sizes.fill(0);
  1665. }
  1666. this.#head = 0;
  1667. this.#tail = 0;
  1668. this.#free.length = 0;
  1669. this.#calculatedSize = 0;
  1670. this.#size = 0;
  1671. if (this.#hasDisposeAfter && this.#disposed) {
  1672. const dt = this.#disposed;
  1673. let task;
  1674. while ((task = dt?.shift())) {
  1675. this.#disposeAfter?.(...task);
  1676. }
  1677. }
  1678. }
  1679. }
  1680. function createCache(max = 500) {
  1681. return new LRUCache({ max });
  1682. }
  1683. function isImportUsed(local, sfc) {
  1684. return resolveTemplateUsedIdentifiers(sfc).has(local);
  1685. }
  1686. const templateAnalysisCache = createCache();
  1687. function resolveTemplateVModelIdentifiers(sfc) {
  1688. return resolveTemplateAnalysisResult(sfc, false).vModelIds;
  1689. }
  1690. function resolveTemplateUsedIdentifiers(sfc) {
  1691. return resolveTemplateAnalysisResult(sfc).usedIds;
  1692. }
  1693. function resolveTemplateAnalysisResult(sfc, collectUsedIds = true) {
  1694. const { content, ast } = sfc.template;
  1695. const cached = templateAnalysisCache.get(content);
  1696. if (cached && (!collectUsedIds || cached.usedIds)) {
  1697. return cached;
  1698. }
  1699. const ids = collectUsedIds ? /* @__PURE__ */ new Set() : void 0;
  1700. const vModelIds = /* @__PURE__ */ new Set();
  1701. ast.children.forEach(walk);
  1702. function walk(node) {
  1703. var _a;
  1704. switch (node.type) {
  1705. case 1:
  1706. let tag = node.tag;
  1707. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  1708. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1709. if (ids) {
  1710. ids.add(shared.camelize(tag));
  1711. ids.add(shared.capitalize(shared.camelize(tag)));
  1712. }
  1713. }
  1714. for (let i = 0; i < node.props.length; i++) {
  1715. const prop = node.props[i];
  1716. if (prop.type === 7) {
  1717. if (ids) {
  1718. if (!shared.isBuiltInDirective(prop.name)) {
  1719. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1720. }
  1721. }
  1722. if (prop.name === "model") {
  1723. const exp = prop.exp;
  1724. if (exp && exp.type === 4) {
  1725. const expString = exp.content.trim();
  1726. if (CompilerDOM.isSimpleIdentifier(expString) && expString !== "undefined") {
  1727. vModelIds.add(expString);
  1728. }
  1729. }
  1730. }
  1731. if (ids && prop.arg && !prop.arg.isStatic) {
  1732. extractIdentifiers(ids, prop.arg);
  1733. }
  1734. if (ids) {
  1735. if (prop.name === "for") {
  1736. extractIdentifiers(ids, prop.forParseResult.source);
  1737. } else if (prop.exp) {
  1738. extractIdentifiers(ids, prop.exp);
  1739. } else if (prop.name === "bind" && !prop.exp) {
  1740. ids.add(shared.camelize(prop.arg.content));
  1741. }
  1742. }
  1743. }
  1744. if (ids && prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1745. ids.add(prop.value.content);
  1746. }
  1747. }
  1748. node.children.forEach(walk);
  1749. break;
  1750. case 5:
  1751. if (ids) extractIdentifiers(ids, node.content);
  1752. break;
  1753. }
  1754. }
  1755. const result = { usedIds: ids, vModelIds };
  1756. templateAnalysisCache.set(content, result);
  1757. return result;
  1758. }
  1759. function extractIdentifiers(ids, node) {
  1760. if (node.ast) {
  1761. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1762. } else if (node.ast === null) {
  1763. ids.add(node.content);
  1764. }
  1765. }
  1766. const DEFAULT_FILENAME = "anonymous.vue";
  1767. const parseCache$1 = createCache();
  1768. function parse$1(source, options = {}) {
  1769. var _a;
  1770. const sourceKey = shared.genCacheKey(source, {
  1771. ...options,
  1772. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1773. });
  1774. const cache = parseCache$1.get(sourceKey);
  1775. if (cache) {
  1776. return cache;
  1777. }
  1778. const {
  1779. sourceMap = true,
  1780. filename = DEFAULT_FILENAME,
  1781. sourceRoot = "",
  1782. pad = false,
  1783. ignoreEmpty = true,
  1784. compiler = CompilerDOM__namespace,
  1785. templateParseOptions = {}
  1786. } = options;
  1787. const descriptor = {
  1788. filename,
  1789. source,
  1790. template: null,
  1791. script: null,
  1792. scriptSetup: null,
  1793. styles: [],
  1794. customBlocks: [],
  1795. cssVars: [],
  1796. slotted: false,
  1797. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1798. };
  1799. const errors = [];
  1800. const ast = compiler.parse(source, {
  1801. parseMode: "sfc",
  1802. prefixIdentifiers: true,
  1803. ...templateParseOptions,
  1804. onError: (e) => {
  1805. errors.push(e);
  1806. }
  1807. });
  1808. ast.children.forEach((node) => {
  1809. if (node.type !== 1) {
  1810. return;
  1811. }
  1812. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1813. return;
  1814. }
  1815. switch (node.tag) {
  1816. case "template":
  1817. if (!descriptor.template) {
  1818. const templateBlock = descriptor.template = createBlock(
  1819. node,
  1820. source,
  1821. false
  1822. );
  1823. if (!templateBlock.attrs.src) {
  1824. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1825. }
  1826. if (templateBlock.attrs.functional) {
  1827. const err = new SyntaxError(
  1828. `<template functional> is no longer supported in Vue 3, since functional components no longer have significant performance difference from stateful ones. Just use a normal <template> instead.`
  1829. );
  1830. err.loc = node.props.find(
  1831. (p) => p.type === 6 && p.name === "functional"
  1832. ).loc;
  1833. errors.push(err);
  1834. }
  1835. } else {
  1836. errors.push(createDuplicateBlockError(node));
  1837. }
  1838. break;
  1839. case "script":
  1840. const scriptBlock = createBlock(node, source, pad);
  1841. const isSetup = !!scriptBlock.attrs.setup;
  1842. if (isSetup && !descriptor.scriptSetup) {
  1843. descriptor.scriptSetup = scriptBlock;
  1844. break;
  1845. }
  1846. if (!isSetup && !descriptor.script) {
  1847. descriptor.script = scriptBlock;
  1848. break;
  1849. }
  1850. errors.push(createDuplicateBlockError(node, isSetup));
  1851. break;
  1852. case "style":
  1853. const styleBlock = createBlock(node, source, pad);
  1854. if (styleBlock.attrs.vars) {
  1855. errors.push(
  1856. new SyntaxError(
  1857. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1858. )
  1859. );
  1860. }
  1861. descriptor.styles.push(styleBlock);
  1862. break;
  1863. default:
  1864. descriptor.customBlocks.push(createBlock(node, source, pad));
  1865. break;
  1866. }
  1867. });
  1868. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1869. errors.push(
  1870. new SyntaxError(
  1871. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  1872. )
  1873. );
  1874. }
  1875. if (descriptor.scriptSetup) {
  1876. if (descriptor.scriptSetup.src) {
  1877. errors.push(
  1878. new SyntaxError(
  1879. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1880. )
  1881. );
  1882. descriptor.scriptSetup = null;
  1883. }
  1884. if (descriptor.script && descriptor.script.src) {
  1885. errors.push(
  1886. new SyntaxError(
  1887. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1888. )
  1889. );
  1890. descriptor.script = null;
  1891. }
  1892. }
  1893. let templateColumnOffset = 0;
  1894. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1895. [descriptor.template.content, templateColumnOffset] = dedent(
  1896. descriptor.template.content
  1897. );
  1898. }
  1899. if (sourceMap) {
  1900. const genMap = (block, columnOffset = 0) => {
  1901. if (block && !block.src) {
  1902. block.map = generateSourceMap(
  1903. filename,
  1904. source,
  1905. block.content,
  1906. sourceRoot,
  1907. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1908. columnOffset
  1909. );
  1910. }
  1911. };
  1912. genMap(descriptor.template, templateColumnOffset);
  1913. genMap(descriptor.script);
  1914. descriptor.styles.forEach((s) => genMap(s));
  1915. descriptor.customBlocks.forEach((s) => genMap(s));
  1916. }
  1917. descriptor.cssVars = parseCssVars(descriptor);
  1918. const slottedRE = /(?:::v-|:)slotted\(/;
  1919. descriptor.slotted = descriptor.styles.some(
  1920. (s) => s.scoped && slottedRE.test(s.content)
  1921. );
  1922. const result = {
  1923. descriptor,
  1924. errors
  1925. };
  1926. parseCache$1.set(sourceKey, result);
  1927. return result;
  1928. }
  1929. function createDuplicateBlockError(node, isScriptSetup = false) {
  1930. const err = new SyntaxError(
  1931. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1932. );
  1933. err.loc = node.loc;
  1934. return err;
  1935. }
  1936. function createBlock(node, source, pad) {
  1937. const type = node.tag;
  1938. const loc = node.innerLoc;
  1939. const attrs = {};
  1940. const block = {
  1941. type,
  1942. content: source.slice(loc.start.offset, loc.end.offset),
  1943. loc,
  1944. attrs
  1945. };
  1946. if (pad) {
  1947. block.content = padContent(source, block, pad) + block.content;
  1948. }
  1949. node.props.forEach((p) => {
  1950. if (p.type === 6) {
  1951. const name = p.name;
  1952. attrs[name] = p.value ? p.value.content || true : true;
  1953. if (name === "lang") {
  1954. block.lang = p.value && p.value.content;
  1955. } else if (name === "src") {
  1956. block.src = p.value && p.value.content;
  1957. } else if (type === "style") {
  1958. if (name === "scoped") {
  1959. block.scoped = true;
  1960. } else if (name === "module") {
  1961. block.module = attrs[name];
  1962. }
  1963. } else if (type === "script" && name === "setup") {
  1964. block.setup = attrs.setup;
  1965. }
  1966. }
  1967. });
  1968. return block;
  1969. }
  1970. const splitRE = /\r?\n/g;
  1971. const emptyRE = /^(?:\/\/)?\s*$/;
  1972. const replaceRE = /./g;
  1973. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  1974. const map = new sourceMapJs.SourceMapGenerator({
  1975. file: filename.replace(/\\/g, "/"),
  1976. sourceRoot: sourceRoot.replace(/\\/g, "/")
  1977. });
  1978. map.setSourceContent(filename, source);
  1979. map._sources.add(filename);
  1980. generated.split(splitRE).forEach((line, index) => {
  1981. if (!emptyRE.test(line)) {
  1982. const originalLine = index + 1 + lineOffset;
  1983. const generatedLine = index + 1;
  1984. for (let i = 0; i < line.length; i++) {
  1985. if (!/\s/.test(line[i])) {
  1986. map._mappings.add({
  1987. originalLine,
  1988. originalColumn: i + columnOffset,
  1989. generatedLine,
  1990. generatedColumn: i,
  1991. source: filename,
  1992. name: null
  1993. });
  1994. }
  1995. }
  1996. }
  1997. });
  1998. return map.toJSON();
  1999. }
  2000. function padContent(content, block, pad) {
  2001. content = content.slice(0, block.loc.start.offset);
  2002. if (pad === "space") {
  2003. return content.replace(replaceRE, " ");
  2004. } else {
  2005. const offset = content.split(splitRE).length;
  2006. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  2007. return Array(offset).join(padChar);
  2008. }
  2009. }
  2010. function hasSrc(node) {
  2011. return node.props.some((p) => {
  2012. if (p.type !== 6) {
  2013. return false;
  2014. }
  2015. return p.name === "src";
  2016. });
  2017. }
  2018. function isEmpty(node) {
  2019. for (let i = 0; i < node.children.length; i++) {
  2020. const child = node.children[i];
  2021. if (child.type !== 2 || child.content.trim() !== "") {
  2022. return false;
  2023. }
  2024. }
  2025. return true;
  2026. }
  2027. function hmrShouldReload(prevImports, next) {
  2028. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  2029. return false;
  2030. }
  2031. for (const key in prevImports) {
  2032. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2033. return true;
  2034. }
  2035. }
  2036. return false;
  2037. }
  2038. function dedent(s) {
  2039. const lines = s.split("\n");
  2040. const minIndent = lines.reduce(function(minIndent2, line) {
  2041. var _a, _b;
  2042. if (line.trim() === "") {
  2043. return minIndent2;
  2044. }
  2045. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2046. return Math.min(indent, minIndent2);
  2047. }, Infinity);
  2048. if (minIndent === 0) {
  2049. return [s, minIndent];
  2050. }
  2051. return [
  2052. lines.map(function(line) {
  2053. return line.slice(minIndent);
  2054. }).join("\n"),
  2055. minIndent
  2056. ];
  2057. }
  2058. function isRelativeUrl(url) {
  2059. const firstChar = url.charAt(0);
  2060. return firstChar === "." || firstChar === "~" || firstChar === "@" || firstChar === "#";
  2061. }
  2062. const externalRE = /^(?:https?:)?\/\//;
  2063. function isExternalUrl(url) {
  2064. return externalRE.test(url);
  2065. }
  2066. const dataUrlRE = /^\s*data:/i;
  2067. function isDataUrl(url) {
  2068. return dataUrlRE.test(url);
  2069. }
  2070. function normalizeDecodedImportPath(source) {
  2071. try {
  2072. return decodeURIComponent(source);
  2073. } catch {
  2074. return source;
  2075. }
  2076. }
  2077. function parseUrl(url) {
  2078. const firstChar = url.charAt(0);
  2079. if (firstChar === "~") {
  2080. const secondChar = url.charAt(1);
  2081. url = url.slice(secondChar === "/" ? 2 : 1);
  2082. }
  2083. return parseUriParts(url);
  2084. }
  2085. function parseUriParts(urlString) {
  2086. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2087. }
  2088. const resourceUrlTagConfig = {
  2089. video: ["src", "poster"],
  2090. source: ["src"],
  2091. img: ["src"]
  2092. };
  2093. const defaultAssetUrlOptions = {
  2094. base: null,
  2095. includeAbsolute: false,
  2096. tags: {
  2097. ...resourceUrlTagConfig,
  2098. image: ["xlink:href", "href"],
  2099. use: ["xlink:href", "href"]
  2100. }
  2101. };
  2102. const normalizeOptions = (options) => {
  2103. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2104. return {
  2105. ...defaultAssetUrlOptions,
  2106. tags: options
  2107. };
  2108. }
  2109. return {
  2110. ...defaultAssetUrlOptions,
  2111. ...options
  2112. };
  2113. };
  2114. const createAssetUrlTransformWithOptions = (options) => {
  2115. return (node, context) => transformAssetUrl(node, context, options);
  2116. };
  2117. function canTransformHashImport(tag, attrName) {
  2118. var _a;
  2119. return !!((_a = resourceUrlTagConfig[tag]) == null ? void 0 : _a.includes(attrName));
  2120. }
  2121. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2122. if (node.type === 1) {
  2123. if (!node.props.length) {
  2124. return;
  2125. }
  2126. const tags = options.tags || defaultAssetUrlOptions.tags;
  2127. const attrs = tags[node.tag];
  2128. const wildCardAttrs = tags["*"];
  2129. if (!attrs && !wildCardAttrs) {
  2130. return;
  2131. }
  2132. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2133. node.props.forEach((attr, index) => {
  2134. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value) {
  2135. return;
  2136. }
  2137. const urlValue = attr.value.content;
  2138. const isHashOnlyValue = urlValue[0] === "#";
  2139. if (isExternalUrl(urlValue) || isDataUrl(urlValue) || // a bare `#` is never a valid import specifier
  2140. urlValue === "#" || isHashOnlyValue && !canTransformHashImport(node.tag, attr.name) || !options.includeAbsolute && !isRelativeUrl(urlValue)) {
  2141. return;
  2142. }
  2143. const url = parseUrl(urlValue);
  2144. if (options.base && urlValue[0] === ".") {
  2145. const base = parseUrl(options.base);
  2146. const protocol = base.protocol || "";
  2147. const host = base.host ? protocol + "//" + base.host : "";
  2148. const basePath = base.path || "/";
  2149. attr.value.content = host + (path$1.posix || path$1).join(basePath, url.path + (url.hash || ""));
  2150. return;
  2151. }
  2152. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2153. node.props[index] = {
  2154. type: 7,
  2155. name: "bind",
  2156. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2157. exp,
  2158. modifiers: [],
  2159. loc: attr.loc
  2160. };
  2161. });
  2162. }
  2163. };
  2164. function resolveOrRegisterImport(source, loc, context) {
  2165. const normalizedSource = normalizeDecodedImportPath(source);
  2166. const existingIndex = context.imports.findIndex(
  2167. (i) => i.path === normalizedSource
  2168. );
  2169. if (existingIndex > -1) {
  2170. return {
  2171. name: `_imports_${existingIndex}`,
  2172. exp: context.imports[existingIndex].exp
  2173. };
  2174. }
  2175. const name = `_imports_${context.imports.length}`;
  2176. const exp = compilerCore.createSimpleExpression(
  2177. name,
  2178. false,
  2179. loc,
  2180. 3
  2181. );
  2182. context.imports.push({
  2183. exp,
  2184. path: normalizedSource
  2185. });
  2186. return { name, exp };
  2187. }
  2188. function getImportsExpressionExp(path2, hash, loc, context) {
  2189. if (!path2 && !hash) {
  2190. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2191. }
  2192. if (!path2 && hash) {
  2193. const { exp } = resolveOrRegisterImport(hash, loc, context);
  2194. return exp;
  2195. }
  2196. if (path2 && !hash) {
  2197. const { exp } = resolveOrRegisterImport(path2, loc, context);
  2198. return exp;
  2199. }
  2200. const { name } = resolveOrRegisterImport(path2, loc, context);
  2201. const hashExp = `${name} + '${hash}'`;
  2202. const finalExp = compilerCore.createSimpleExpression(
  2203. hashExp,
  2204. false,
  2205. loc,
  2206. 3
  2207. );
  2208. if (!context.hoistStatic) {
  2209. return finalExp;
  2210. }
  2211. const existingHoistIndex = context.hoists.findIndex((h) => {
  2212. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2213. });
  2214. if (existingHoistIndex > -1) {
  2215. return compilerCore.createSimpleExpression(
  2216. `_hoisted_${existingHoistIndex + 1}`,
  2217. false,
  2218. loc,
  2219. 3
  2220. );
  2221. }
  2222. return context.hoist(finalExp);
  2223. }
  2224. const srcsetTags = ["img", "source"];
  2225. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2226. const createSrcsetTransformWithOptions = (options) => {
  2227. return (node, context) => transformSrcset(node, context, options);
  2228. };
  2229. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2230. if (node.type === 1) {
  2231. if (srcsetTags.includes(node.tag) && node.props.length) {
  2232. node.props.forEach((attr, index) => {
  2233. if (attr.name === "srcset" && attr.type === 6) {
  2234. if (!attr.value) return;
  2235. const value = attr.value.content;
  2236. if (!value) return;
  2237. const imageCandidates = value.split(",").map((s) => {
  2238. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2239. return { url, descriptor };
  2240. });
  2241. for (let i = 0; i < imageCandidates.length; i++) {
  2242. const { url } = imageCandidates[i];
  2243. if (isDataUrl(url)) {
  2244. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2245. imageCandidates.splice(i, 1);
  2246. }
  2247. }
  2248. const shouldProcessUrl = (url) => {
  2249. return url && !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2250. };
  2251. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2252. return;
  2253. }
  2254. if (options.base) {
  2255. const base = options.base;
  2256. const set = [];
  2257. let needImportTransform = false;
  2258. imageCandidates.forEach((candidate) => {
  2259. let { url, descriptor } = candidate;
  2260. descriptor = descriptor ? ` ${descriptor}` : ``;
  2261. if (url[0] === ".") {
  2262. candidate.url = (path$1.posix || path$1).join(base, url);
  2263. set.push(candidate.url + descriptor);
  2264. } else if (shouldProcessUrl(url)) {
  2265. needImportTransform = true;
  2266. } else {
  2267. set.push(url + descriptor);
  2268. }
  2269. });
  2270. if (!needImportTransform) {
  2271. attr.value.content = set.join(", ");
  2272. return;
  2273. }
  2274. }
  2275. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2276. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2277. if (shouldProcessUrl(url)) {
  2278. const { path: path2, hash } = parseUrl(url);
  2279. const source = path2 ? path2 : hash;
  2280. if (source) {
  2281. const normalizedSource = normalizeDecodedImportPath(source);
  2282. const existingImportsIndex = context.imports.findIndex(
  2283. (i) => i.path === normalizedSource
  2284. );
  2285. let exp2;
  2286. if (existingImportsIndex > -1) {
  2287. exp2 = compilerCore.createSimpleExpression(
  2288. `_imports_${existingImportsIndex}`,
  2289. false,
  2290. attr.loc,
  2291. 3
  2292. );
  2293. } else {
  2294. exp2 = compilerCore.createSimpleExpression(
  2295. `_imports_${context.imports.length}`,
  2296. false,
  2297. attr.loc,
  2298. 3
  2299. );
  2300. context.imports.push({ exp: exp2, path: normalizedSource });
  2301. }
  2302. if (path2 && hash) {
  2303. exp2 = compilerCore.createSimpleExpression(
  2304. `${exp2.content} + '${hash}'`,
  2305. false,
  2306. attr.loc,
  2307. 3
  2308. );
  2309. }
  2310. compoundExpression.children.push(exp2);
  2311. }
  2312. } else {
  2313. const exp2 = compilerCore.createSimpleExpression(
  2314. `"${url}"`,
  2315. false,
  2316. attr.loc,
  2317. 3
  2318. );
  2319. compoundExpression.children.push(exp2);
  2320. }
  2321. const isNotLast = imageCandidates.length - 1 > index2;
  2322. if (descriptor && isNotLast) {
  2323. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2324. } else if (descriptor) {
  2325. compoundExpression.children.push(` + ' ${descriptor}'`);
  2326. } else if (isNotLast) {
  2327. compoundExpression.children.push(` + ', ' + `);
  2328. }
  2329. });
  2330. let exp = compoundExpression;
  2331. if (context.hoistStatic) {
  2332. exp = context.hoist(compoundExpression);
  2333. exp.constType = 3;
  2334. }
  2335. node.props[index] = {
  2336. type: 7,
  2337. name: "bind",
  2338. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2339. exp,
  2340. modifiers: [],
  2341. loc: attr.loc
  2342. };
  2343. }
  2344. });
  2345. }
  2346. }
  2347. };
  2348. function commonjsRequire(path) {
  2349. throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  2350. }
  2351. var consolidate$2 = {exports: {}};
  2352. var hasRequiredConsolidate$1;
  2353. function requireConsolidate$1 () {
  2354. if (hasRequiredConsolidate$1) return consolidate$2.exports;
  2355. hasRequiredConsolidate$1 = 1;
  2356. (function (module, exports) {
  2357. /*
  2358. * Engines which do not support caching of their file contents
  2359. * should use the `read()` function defined in consolidate.js
  2360. * On top of this, when an engine compiles to a `Function`,
  2361. * these functions should either be cached within consolidate.js
  2362. * or the engine itself via `options.cache`. This will allow
  2363. * users and frameworks to pass `options.cache = true` for
  2364. * `NODE_ENV=production`, however edit the file(s) without
  2365. * re-loading the application in development.
  2366. */
  2367. /**
  2368. * Module dependencies.
  2369. */
  2370. var fs = require$$0;
  2371. var path = path$1;
  2372. var util = require$$2;
  2373. var join = path.join;
  2374. var resolve = path.resolve;
  2375. var extname = path.extname;
  2376. var dirname = path.dirname;
  2377. var isAbsolute = path.isAbsolute;
  2378. var readCache = {};
  2379. /**
  2380. * Require cache.
  2381. */
  2382. var cacheStore = {};
  2383. /**
  2384. * Require cache.
  2385. */
  2386. var requires = {};
  2387. /**
  2388. * Clear the cache.
  2389. *
  2390. * @api public
  2391. */
  2392. exports.clearCache = function() {
  2393. readCache = {};
  2394. cacheStore = {};
  2395. };
  2396. /**
  2397. * Conditionally cache `compiled` template based
  2398. * on the `options` filename and `.cache` boolean.
  2399. *
  2400. * @param {Object} options
  2401. * @param {Function} compiled
  2402. * @return {Function}
  2403. * @api private
  2404. */
  2405. function cache(options, compiled) {
  2406. // cachable
  2407. if (compiled && options.filename && options.cache) {
  2408. delete readCache[options.filename];
  2409. cacheStore[options.filename] = compiled;
  2410. return compiled;
  2411. }
  2412. // check cache
  2413. if (options.filename && options.cache) {
  2414. return cacheStore[options.filename];
  2415. }
  2416. return compiled;
  2417. }
  2418. /**
  2419. * Read `path` with `options` with
  2420. * callback `(err, str)`. When `options.cache`
  2421. * is true the template string will be cached.
  2422. *
  2423. * @param {String} options
  2424. * @param {Function} cb
  2425. * @api private
  2426. */
  2427. function read(path, options, cb) {
  2428. var str = readCache[path];
  2429. var cached = options.cache && str && typeof str === 'string';
  2430. // cached (only if cached is a string and not a compiled template function)
  2431. if (cached) return cb(null, str);
  2432. // read
  2433. fs.readFile(path, 'utf8', function(err, str) {
  2434. if (err) return cb(err);
  2435. // remove extraneous utf8 BOM marker
  2436. str = str.replace(/^\uFEFF/, '');
  2437. if (options.cache) readCache[path] = str;
  2438. cb(null, str);
  2439. });
  2440. }
  2441. /**
  2442. * Read `path` with `options` with
  2443. * callback `(err, str)`. When `options.cache`
  2444. * is true the partial string will be cached.
  2445. *
  2446. * @param {String} options
  2447. * @param {Function} fn
  2448. * @api private
  2449. */
  2450. function readPartials(path, options, cb) {
  2451. if (!options.partials) return cb();
  2452. var keys = Object.keys(options.partials);
  2453. var partials = {};
  2454. function next(index) {
  2455. if (index === keys.length) return cb(null, partials);
  2456. var key = keys[index];
  2457. var partialPath = options.partials[key];
  2458. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2459. return next(++index);
  2460. }
  2461. var file;
  2462. if (isAbsolute(partialPath)) {
  2463. if (extname(partialPath) !== '') {
  2464. file = partialPath;
  2465. } else {
  2466. file = join(partialPath + extname(path));
  2467. }
  2468. } else {
  2469. file = join(dirname(path), partialPath + extname(path));
  2470. }
  2471. read(file, options, function(err, str) {
  2472. if (err) return cb(err);
  2473. partials[key] = str;
  2474. next(++index);
  2475. });
  2476. }
  2477. next(0);
  2478. }
  2479. /**
  2480. * promisify
  2481. */
  2482. function promisify(cb, fn) {
  2483. return new Promise(function(resolve, reject) {
  2484. cb = cb || function(err, html) {
  2485. if (err) {
  2486. return reject(err);
  2487. }
  2488. resolve(html);
  2489. };
  2490. fn(cb);
  2491. });
  2492. }
  2493. /**
  2494. * fromStringRenderer
  2495. */
  2496. function fromStringRenderer(name) {
  2497. return function(path, options, cb) {
  2498. options.filename = path;
  2499. return promisify(cb, function(cb) {
  2500. readPartials(path, options, function(err, partials) {
  2501. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2502. var opts = extend({}, options);
  2503. opts.partials = partials;
  2504. if (err) return cb(err);
  2505. if (cache(opts)) {
  2506. exports[name].render('', opts, cb);
  2507. } else {
  2508. read(path, opts, function(err, str) {
  2509. if (err) return cb(err);
  2510. exports[name].render(str, opts, cb);
  2511. });
  2512. }
  2513. });
  2514. });
  2515. };
  2516. }
  2517. /**
  2518. * velocity support.
  2519. */
  2520. exports.velocityjs = fromStringRenderer('velocityjs');
  2521. /**
  2522. * velocity string support.
  2523. */
  2524. exports.velocityjs.render = function(str, options, cb) {
  2525. return promisify(cb, function(cb) {
  2526. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2527. try {
  2528. options.locals = options;
  2529. cb(null, engine.render(str, options).trimLeft());
  2530. } catch (err) {
  2531. cb(err);
  2532. }
  2533. });
  2534. };
  2535. /**
  2536. * Liquid support.
  2537. */
  2538. exports.liquid = fromStringRenderer('liquid');
  2539. /**
  2540. * Liquid string support.
  2541. */
  2542. /**
  2543. * Note that in order to get filters and custom tags we've had to push
  2544. * all user-defined locals down into @locals. However, just to make things
  2545. * backwards-compatible, any property of `options` that is left after
  2546. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2547. * `includeDir` will also become a local.
  2548. */
  2549. function _renderTinyliquid(engine, str, options, cb) {
  2550. var context = engine.newContext();
  2551. var k;
  2552. /**
  2553. * Note that there's a bug in the library that doesn't allow us to pass
  2554. * the locals to newContext(), hence looping through the keys:
  2555. */
  2556. if (options.locals) {
  2557. for (k in options.locals) {
  2558. context.setLocals(k, options.locals[k]);
  2559. }
  2560. delete options.locals;
  2561. }
  2562. if (options.meta) {
  2563. context.setLocals('page', options.meta);
  2564. delete options.meta;
  2565. }
  2566. /**
  2567. * Add any defined filters:
  2568. */
  2569. if (options.filters) {
  2570. for (k in options.filters) {
  2571. context.setFilter(k, options.filters[k]);
  2572. }
  2573. delete options.filters;
  2574. }
  2575. /**
  2576. * Set up a callback for the include directory:
  2577. */
  2578. var includeDir = options.includeDir || process.cwd();
  2579. context.onInclude(function(name, callback) {
  2580. var extname = path.extname(name) ? '' : '.liquid';
  2581. var filename = path.resolve(includeDir, name + extname);
  2582. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2583. if (err) return callback(err);
  2584. callback(null, engine.parse(data));
  2585. });
  2586. });
  2587. delete options.includeDir;
  2588. /**
  2589. * The custom tag functions need to have their results pushed back
  2590. * through the parser, so set up a shim before calling the provided
  2591. * callback:
  2592. */
  2593. var compileOptions = {
  2594. customTags: {}
  2595. };
  2596. if (options.customTags) {
  2597. var tagFunctions = options.customTags;
  2598. for (k in options.customTags) {
  2599. /*Tell jshint there's no problem with having this function in the loop */
  2600. /*jshint -W083 */
  2601. compileOptions.customTags[k] = function(context, name, body) {
  2602. var tpl = tagFunctions[name](body.trim());
  2603. context.astStack.push(engine.parse(tpl));
  2604. };
  2605. /*jshint +W083 */
  2606. }
  2607. delete options.customTags;
  2608. }
  2609. /**
  2610. * Now anything left in `options` becomes a local:
  2611. */
  2612. for (k in options) {
  2613. context.setLocals(k, options[k]);
  2614. }
  2615. /**
  2616. * Finally, execute the template:
  2617. */
  2618. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2619. tmpl(context, cb);
  2620. }
  2621. exports.liquid.render = function(str, options, cb) {
  2622. return promisify(cb, function(cb) {
  2623. var engine = requires.liquid;
  2624. var Liquid;
  2625. try {
  2626. // set up tinyliquid engine
  2627. engine = requires.liquid = require('tinyliquid');
  2628. // use tinyliquid engine
  2629. _renderTinyliquid(engine, str, options, cb);
  2630. return;
  2631. } catch (err) {
  2632. // set up liquid-node engine
  2633. try {
  2634. Liquid = requires.liquid = require('liquid-node');
  2635. engine = new Liquid.Engine();
  2636. } catch (err) {
  2637. throw err;
  2638. }
  2639. }
  2640. // use liquid-node engine
  2641. try {
  2642. var locals = options.locals || {};
  2643. if (options.meta) {
  2644. locals.pages = options.meta;
  2645. delete options.meta;
  2646. }
  2647. /**
  2648. * Add any defined filters:
  2649. */
  2650. if (options.filters) {
  2651. engine.registerFilters(options.filters);
  2652. delete options.filters;
  2653. }
  2654. /**
  2655. * Set up a callback for the include directory:
  2656. */
  2657. var includeDir = options.includeDir || process.cwd();
  2658. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2659. delete options.includeDir;
  2660. /**
  2661. * The custom tag functions need to have their results pushed back
  2662. * through the parser, so set up a shim before calling the provided
  2663. * callback:
  2664. */
  2665. if (options.customTags) {
  2666. var tagFunctions = options.customTags;
  2667. for (k in options.customTags) {
  2668. engine.registerTag(k, tagFunctions[k]);
  2669. }
  2670. delete options.customTags;
  2671. }
  2672. /**
  2673. * Now anything left in `options` becomes a local:
  2674. */
  2675. for (var k in options) {
  2676. locals[k] = options[k];
  2677. }
  2678. /**
  2679. * Finally, execute the template:
  2680. */
  2681. return engine
  2682. .parseAndRender(str, locals)
  2683. .nodeify(function(err, result) {
  2684. if (err) {
  2685. throw new Error(err);
  2686. } else {
  2687. return cb(null, result);
  2688. }
  2689. });
  2690. } catch (err) {
  2691. cb(err);
  2692. }
  2693. });
  2694. };
  2695. /**
  2696. * Jade support.
  2697. */
  2698. exports.jade = function(path, options, cb) {
  2699. return promisify(cb, function(cb) {
  2700. var engine = requires.jade;
  2701. if (!engine) {
  2702. try {
  2703. engine = requires.jade = require('jade');
  2704. } catch (err) {
  2705. try {
  2706. engine = requires.jade = require('then-jade');
  2707. } catch (otherError) {
  2708. throw err;
  2709. }
  2710. }
  2711. }
  2712. try {
  2713. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2714. cb(null, tmpl(options));
  2715. } catch (err) {
  2716. cb(err);
  2717. }
  2718. });
  2719. };
  2720. /**
  2721. * Jade string support.
  2722. */
  2723. exports.jade.render = function(str, options, cb) {
  2724. return promisify(cb, function(cb) {
  2725. var engine = requires.jade;
  2726. if (!engine) {
  2727. try {
  2728. engine = requires.jade = require('jade');
  2729. } catch (err) {
  2730. try {
  2731. engine = requires.jade = require('then-jade');
  2732. } catch (otherError) {
  2733. throw err;
  2734. }
  2735. }
  2736. }
  2737. try {
  2738. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2739. cb(null, tmpl(options));
  2740. } catch (err) {
  2741. cb(err);
  2742. }
  2743. });
  2744. };
  2745. /**
  2746. * Dust support.
  2747. */
  2748. exports.dust = fromStringRenderer('dust');
  2749. /**
  2750. * Dust string support.
  2751. */
  2752. exports.dust.render = function(str, options, cb) {
  2753. return promisify(cb, function(cb) {
  2754. var engine = requires.dust;
  2755. if (!engine) {
  2756. try {
  2757. engine = requires.dust = require('dust');
  2758. } catch (err) {
  2759. try {
  2760. engine = requires.dust = require('dustjs-helpers');
  2761. } catch (err) {
  2762. engine = requires.dust = require('dustjs-linkedin');
  2763. }
  2764. }
  2765. }
  2766. var ext = 'dust';
  2767. var views = '.';
  2768. if (options) {
  2769. if (options.ext) ext = options.ext;
  2770. if (options.views) views = options.views;
  2771. if (options.settings && options.settings.views) views = options.settings.views;
  2772. }
  2773. if (!options || (options && !options.cache)) engine.cache = {};
  2774. engine.onLoad = function(path, callback) {
  2775. if (extname(path) === '') path += '.' + ext;
  2776. if (path[0] !== '/') path = views + '/' + path;
  2777. read(path, options, callback);
  2778. };
  2779. try {
  2780. var templateName;
  2781. if (options.filename) {
  2782. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2783. }
  2784. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2785. tmpl(options, cb);
  2786. } catch (err) {
  2787. cb(err);
  2788. }
  2789. });
  2790. };
  2791. /**
  2792. * Swig support.
  2793. */
  2794. exports.swig = fromStringRenderer('swig');
  2795. /**
  2796. * Swig string support.
  2797. */
  2798. exports.swig.render = function(str, options, cb) {
  2799. return promisify(cb, function(cb) {
  2800. var engine = requires.swig;
  2801. if (!engine) {
  2802. try {
  2803. engine = requires.swig = require('swig');
  2804. } catch (err) {
  2805. try {
  2806. engine = requires.swig = require('swig-templates');
  2807. } catch (otherError) {
  2808. throw err;
  2809. }
  2810. }
  2811. }
  2812. try {
  2813. if (options.cache === true) options.cache = 'memory';
  2814. engine.setDefaults({ cache: options.cache });
  2815. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2816. cb(null, tmpl(options));
  2817. } catch (err) {
  2818. cb(err);
  2819. }
  2820. });
  2821. };
  2822. /**
  2823. * Razor support.
  2824. */
  2825. exports.razor = function(path, options, cb) {
  2826. return promisify(cb, function(cb) {
  2827. var engine = requires.razor;
  2828. if (!engine) {
  2829. try {
  2830. engine = requires.razor = require('razor-tmpl');
  2831. } catch (err) {
  2832. throw err;
  2833. }
  2834. }
  2835. try {
  2836. var tmpl = cache(options) || cache(options, (locals) => {
  2837. console.log('Rendering razor file', path);
  2838. return engine.renderFileSync(path, locals);
  2839. });
  2840. cb(null, tmpl(options));
  2841. } catch (err) {
  2842. cb(err);
  2843. }
  2844. });
  2845. };
  2846. /**
  2847. * razor string support.
  2848. */
  2849. exports.razor.render = function(str, options, cb) {
  2850. return promisify(cb, function(cb) {
  2851. try {
  2852. var engine = requires.razor = require('razor-tmpl');
  2853. } catch (err) {
  2854. throw err;
  2855. }
  2856. try {
  2857. var tf = engine.compile(str);
  2858. var tmpl = cache(options) || cache(options, tf);
  2859. cb(null, tmpl(options));
  2860. } catch (err) {
  2861. cb(err);
  2862. }
  2863. });
  2864. };
  2865. /**
  2866. * Atpl support.
  2867. */
  2868. exports.atpl = fromStringRenderer('atpl');
  2869. /**
  2870. * Atpl string support.
  2871. */
  2872. exports.atpl.render = function(str, options, cb) {
  2873. return promisify(cb, function(cb) {
  2874. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2875. try {
  2876. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2877. cb(null, tmpl(options));
  2878. } catch (err) {
  2879. cb(err);
  2880. }
  2881. });
  2882. };
  2883. /**
  2884. * Liquor support,
  2885. */
  2886. exports.liquor = fromStringRenderer('liquor');
  2887. /**
  2888. * Liquor string support.
  2889. */
  2890. exports.liquor.render = function(str, options, cb) {
  2891. return promisify(cb, function(cb) {
  2892. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2893. try {
  2894. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2895. cb(null, tmpl(options));
  2896. } catch (err) {
  2897. cb(err);
  2898. }
  2899. });
  2900. };
  2901. /**
  2902. * Twig support.
  2903. */
  2904. exports.twig = fromStringRenderer('twig');
  2905. /**
  2906. * Twig string support.
  2907. */
  2908. exports.twig.render = function(str, options, cb) {
  2909. return promisify(cb, function(cb) {
  2910. var engine = requires.twig || (requires.twig = require('twig').twig);
  2911. var templateData = {
  2912. data: str,
  2913. allowInlineIncludes: options.allowInlineIncludes,
  2914. namespaces: options.namespaces,
  2915. path: options.path
  2916. };
  2917. try {
  2918. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2919. cb(null, tmpl.render(options));
  2920. } catch (err) {
  2921. cb(err);
  2922. }
  2923. });
  2924. };
  2925. /**
  2926. * EJS support.
  2927. */
  2928. exports.ejs = fromStringRenderer('ejs');
  2929. /**
  2930. * EJS string support.
  2931. */
  2932. exports.ejs.render = function(str, options, cb) {
  2933. return promisify(cb, function(cb) {
  2934. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2935. try {
  2936. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2937. cb(null, tmpl(options));
  2938. } catch (err) {
  2939. cb(err);
  2940. }
  2941. });
  2942. };
  2943. /**
  2944. * Eco support.
  2945. */
  2946. exports.eco = fromStringRenderer('eco');
  2947. /**
  2948. * Eco string support.
  2949. */
  2950. exports.eco.render = function(str, options, cb) {
  2951. return promisify(cb, function(cb) {
  2952. var engine = requires.eco || (requires.eco = require('eco'));
  2953. try {
  2954. cb(null, engine.render(str, options));
  2955. } catch (err) {
  2956. cb(err);
  2957. }
  2958. });
  2959. };
  2960. /**
  2961. * Jazz support.
  2962. */
  2963. exports.jazz = fromStringRenderer('jazz');
  2964. /**
  2965. * Jazz string support.
  2966. */
  2967. exports.jazz.render = function(str, options, cb) {
  2968. return promisify(cb, function(cb) {
  2969. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2970. try {
  2971. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2972. tmpl.eval(options, function(str) {
  2973. cb(null, str);
  2974. });
  2975. } catch (err) {
  2976. cb(err);
  2977. }
  2978. });
  2979. };
  2980. /**
  2981. * JQTPL support.
  2982. */
  2983. exports.jqtpl = fromStringRenderer('jqtpl');
  2984. /**
  2985. * JQTPL string support.
  2986. */
  2987. exports.jqtpl.render = function(str, options, cb) {
  2988. return promisify(cb, function(cb) {
  2989. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2990. try {
  2991. engine.template(str, str);
  2992. cb(null, engine.tmpl(str, options));
  2993. } catch (err) {
  2994. cb(err);
  2995. }
  2996. });
  2997. };
  2998. /**
  2999. * Haml support.
  3000. */
  3001. exports.haml = fromStringRenderer('haml');
  3002. /**
  3003. * Haml string support.
  3004. */
  3005. exports.haml.render = function(str, options, cb) {
  3006. return promisify(cb, function(cb) {
  3007. var engine = requires.haml || (requires.haml = require('hamljs'));
  3008. try {
  3009. options.locals = options;
  3010. cb(null, engine.render(str, options).trimLeft());
  3011. } catch (err) {
  3012. cb(err);
  3013. }
  3014. });
  3015. };
  3016. /**
  3017. * Hamlet support.
  3018. */
  3019. exports.hamlet = fromStringRenderer('hamlet');
  3020. /**
  3021. * Hamlet string support.
  3022. */
  3023. exports.hamlet.render = function(str, options, cb) {
  3024. return promisify(cb, function(cb) {
  3025. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  3026. try {
  3027. options.locals = options;
  3028. cb(null, engine.render(str, options).trimLeft());
  3029. } catch (err) {
  3030. cb(err);
  3031. }
  3032. });
  3033. };
  3034. /**
  3035. * Whiskers support.
  3036. */
  3037. exports.whiskers = function(path, options, cb) {
  3038. return promisify(cb, function(cb) {
  3039. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3040. engine.__express(path, options, cb);
  3041. });
  3042. };
  3043. /**
  3044. * Whiskers string support.
  3045. */
  3046. exports.whiskers.render = function(str, options, cb) {
  3047. return promisify(cb, function(cb) {
  3048. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3049. try {
  3050. cb(null, engine.render(str, options));
  3051. } catch (err) {
  3052. cb(err);
  3053. }
  3054. });
  3055. };
  3056. /**
  3057. * Coffee-HAML support.
  3058. */
  3059. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  3060. /**
  3061. * Coffee-HAML string support.
  3062. */
  3063. exports['haml-coffee'].render = function(str, options, cb) {
  3064. return promisify(cb, function(cb) {
  3065. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  3066. try {
  3067. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3068. cb(null, tmpl(options));
  3069. } catch (err) {
  3070. cb(err);
  3071. }
  3072. });
  3073. };
  3074. /**
  3075. * Hogan support.
  3076. */
  3077. exports.hogan = fromStringRenderer('hogan');
  3078. /**
  3079. * Hogan string support.
  3080. */
  3081. exports.hogan.render = function(str, options, cb) {
  3082. return promisify(cb, function(cb) {
  3083. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3084. try {
  3085. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3086. cb(null, tmpl.render(options, options.partials));
  3087. } catch (err) {
  3088. cb(err);
  3089. }
  3090. });
  3091. };
  3092. /**
  3093. * templayed.js support.
  3094. */
  3095. exports.templayed = fromStringRenderer('templayed');
  3096. /**
  3097. * templayed.js string support.
  3098. */
  3099. exports.templayed.render = function(str, options, cb) {
  3100. return promisify(cb, function(cb) {
  3101. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3102. try {
  3103. var tmpl = cache(options) || cache(options, engine(str));
  3104. cb(null, tmpl(options));
  3105. } catch (err) {
  3106. cb(err);
  3107. }
  3108. });
  3109. };
  3110. /**
  3111. * Handlebars support.
  3112. */
  3113. exports.handlebars = fromStringRenderer('handlebars');
  3114. /**
  3115. * Handlebars string support.
  3116. */
  3117. exports.handlebars.render = function(str, options, cb) {
  3118. return promisify(cb, function(cb) {
  3119. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3120. try {
  3121. for (var partial in options.partials) {
  3122. engine.registerPartial(partial, options.partials[partial]);
  3123. }
  3124. for (var helper in options.helpers) {
  3125. engine.registerHelper(helper, options.helpers[helper]);
  3126. }
  3127. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3128. cb(null, tmpl(options));
  3129. } catch (err) {
  3130. cb(err);
  3131. }
  3132. });
  3133. };
  3134. /**
  3135. * Underscore support.
  3136. */
  3137. exports.underscore = fromStringRenderer('underscore');
  3138. /**
  3139. * Underscore string support.
  3140. */
  3141. exports.underscore.render = function(str, options, cb) {
  3142. return promisify(cb, function(cb) {
  3143. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3144. try {
  3145. const partials = {};
  3146. for (var partial in options.partials) {
  3147. partials[partial] = engine.template(options.partials[partial]);
  3148. }
  3149. options.partials = partials;
  3150. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3151. cb(null, tmpl(options).replace(/\n$/, ''));
  3152. } catch (err) {
  3153. cb(err);
  3154. }
  3155. });
  3156. };
  3157. /**
  3158. * Lodash support.
  3159. */
  3160. exports.lodash = fromStringRenderer('lodash');
  3161. /**
  3162. * Lodash string support.
  3163. */
  3164. exports.lodash.render = function(str, options, cb) {
  3165. return promisify(cb, function(cb) {
  3166. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3167. try {
  3168. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3169. cb(null, tmpl(options).replace(/\n$/, ''));
  3170. } catch (err) {
  3171. cb(err);
  3172. }
  3173. });
  3174. };
  3175. /**
  3176. * Pug support. (formerly Jade)
  3177. */
  3178. exports.pug = function(path, options, cb) {
  3179. return promisify(cb, function(cb) {
  3180. var engine = requires.pug;
  3181. if (!engine) {
  3182. try {
  3183. engine = requires.pug = require('pug');
  3184. } catch (err) {
  3185. try {
  3186. engine = requires.pug = require('then-pug');
  3187. } catch (otherError) {
  3188. throw err;
  3189. }
  3190. }
  3191. }
  3192. try {
  3193. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3194. cb(null, tmpl(options));
  3195. } catch (err) {
  3196. cb(err);
  3197. }
  3198. });
  3199. };
  3200. /**
  3201. * Pug string support.
  3202. */
  3203. exports.pug.render = function(str, options, cb) {
  3204. return promisify(cb, function(cb) {
  3205. var engine = requires.pug;
  3206. if (!engine) {
  3207. try {
  3208. engine = requires.pug = require('pug');
  3209. } catch (err) {
  3210. try {
  3211. engine = requires.pug = require('then-pug');
  3212. } catch (otherError) {
  3213. throw err;
  3214. }
  3215. }
  3216. }
  3217. try {
  3218. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3219. cb(null, tmpl(options));
  3220. } catch (err) {
  3221. cb(err);
  3222. }
  3223. });
  3224. };
  3225. /**
  3226. * QEJS support.
  3227. */
  3228. exports.qejs = fromStringRenderer('qejs');
  3229. /**
  3230. * QEJS string support.
  3231. */
  3232. exports.qejs.render = function(str, options, cb) {
  3233. return promisify(cb, function(cb) {
  3234. try {
  3235. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3236. engine.render(str, options).then(function(result) {
  3237. cb(null, result);
  3238. }, function(err) {
  3239. cb(err);
  3240. }).done();
  3241. } catch (err) {
  3242. cb(err);
  3243. }
  3244. });
  3245. };
  3246. /**
  3247. * Walrus support.
  3248. */
  3249. exports.walrus = fromStringRenderer('walrus');
  3250. /**
  3251. * Walrus string support.
  3252. */
  3253. exports.walrus.render = function(str, options, cb) {
  3254. return promisify(cb, function(cb) {
  3255. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3256. try {
  3257. var tmpl = cache(options) || cache(options, engine.parse(str));
  3258. cb(null, tmpl.compile(options));
  3259. } catch (err) {
  3260. cb(err);
  3261. }
  3262. });
  3263. };
  3264. /**
  3265. * Mustache support.
  3266. */
  3267. exports.mustache = fromStringRenderer('mustache');
  3268. /**
  3269. * Mustache string support.
  3270. */
  3271. exports.mustache.render = function(str, options, cb) {
  3272. return promisify(cb, function(cb) {
  3273. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3274. try {
  3275. cb(null, engine.render(str, options, options.partials));
  3276. } catch (err) {
  3277. cb(err);
  3278. }
  3279. });
  3280. };
  3281. /**
  3282. * Just support.
  3283. */
  3284. exports.just = function(path, options, cb) {
  3285. return promisify(cb, function(cb) {
  3286. var engine = requires.just;
  3287. if (!engine) {
  3288. var JUST = require('just');
  3289. engine = requires.just = new JUST();
  3290. }
  3291. engine.configure({ useCache: options.cache });
  3292. engine.render(path, options, cb);
  3293. });
  3294. };
  3295. /**
  3296. * Just string support.
  3297. */
  3298. exports.just.render = function(str, options, cb) {
  3299. return promisify(cb, function(cb) {
  3300. var JUST = require('just');
  3301. var engine = new JUST({ root: { page: str }});
  3302. engine.render('page', options, cb);
  3303. });
  3304. };
  3305. /**
  3306. * ECT support.
  3307. */
  3308. exports.ect = function(path, options, cb) {
  3309. return promisify(cb, function(cb) {
  3310. var engine = requires.ect;
  3311. if (!engine) {
  3312. var ECT = require('ect');
  3313. engine = requires.ect = new ECT(options);
  3314. }
  3315. engine.configure({ cache: options.cache });
  3316. engine.render(path, options, cb);
  3317. });
  3318. };
  3319. /**
  3320. * ECT string support.
  3321. */
  3322. exports.ect.render = function(str, options, cb) {
  3323. return promisify(cb, function(cb) {
  3324. var ECT = require('ect');
  3325. var engine = new ECT({ root: { page: str }});
  3326. engine.render('page', options, cb);
  3327. });
  3328. };
  3329. /**
  3330. * mote support.
  3331. */
  3332. exports.mote = fromStringRenderer('mote');
  3333. /**
  3334. * mote string support.
  3335. */
  3336. exports.mote.render = function(str, options, cb) {
  3337. return promisify(cb, function(cb) {
  3338. var engine = requires.mote || (requires.mote = require('mote'));
  3339. try {
  3340. var tmpl = cache(options) || cache(options, engine.compile(str));
  3341. cb(null, tmpl(options));
  3342. } catch (err) {
  3343. cb(err);
  3344. }
  3345. });
  3346. };
  3347. /**
  3348. * Toffee support.
  3349. */
  3350. exports.toffee = function(path, options, cb) {
  3351. return promisify(cb, function(cb) {
  3352. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3353. toffee.__consolidate_engine_render(path, options, cb);
  3354. });
  3355. };
  3356. /**
  3357. * Toffee string support.
  3358. */
  3359. exports.toffee.render = function(str, options, cb) {
  3360. return promisify(cb, function(cb) {
  3361. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3362. try {
  3363. engine.str_render(str, options, cb);
  3364. } catch (err) {
  3365. cb(err);
  3366. }
  3367. });
  3368. };
  3369. /**
  3370. * doT support.
  3371. */
  3372. exports.dot = fromStringRenderer('dot');
  3373. /**
  3374. * doT string support.
  3375. */
  3376. exports.dot.render = function(str, options, cb) {
  3377. return promisify(cb, function(cb) {
  3378. var engine = requires.dot || (requires.dot = require('dot'));
  3379. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3380. try {
  3381. var settings = {};
  3382. settings = extend(settings, engine.templateSettings);
  3383. settings = extend(settings, options ? options.dot : {});
  3384. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3385. cb(null, tmpl(options));
  3386. } catch (err) {
  3387. cb(err);
  3388. }
  3389. });
  3390. };
  3391. /**
  3392. * bracket support.
  3393. */
  3394. exports.bracket = fromStringRenderer('bracket');
  3395. /**
  3396. * bracket string support.
  3397. */
  3398. exports.bracket.render = function(str, options, cb) {
  3399. return promisify(cb, function(cb) {
  3400. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3401. try {
  3402. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3403. cb(null, tmpl(options));
  3404. } catch (err) {
  3405. cb(err);
  3406. }
  3407. });
  3408. };
  3409. /**
  3410. * Ractive support.
  3411. */
  3412. exports.ractive = fromStringRenderer('ractive');
  3413. /**
  3414. * Ractive string support.
  3415. */
  3416. exports.ractive.render = function(str, options, cb) {
  3417. return promisify(cb, function(cb) {
  3418. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3419. var template = cache(options) || cache(options, Engine.parse(str));
  3420. options.template = template;
  3421. if (options.data === null || options.data === undefined) {
  3422. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3423. // Shallow clone the options object
  3424. options.data = extend({}, options);
  3425. // Remove consolidate-specific properties from the clone
  3426. var i;
  3427. var length;
  3428. var properties = ['template', 'filename', 'cache', 'partials'];
  3429. for (i = 0, length = properties.length; i < length; i++) {
  3430. var property = properties[i];
  3431. delete options.data[property];
  3432. }
  3433. }
  3434. try {
  3435. cb(null, new Engine(options).toHTML());
  3436. } catch (err) {
  3437. cb(err);
  3438. }
  3439. });
  3440. };
  3441. /**
  3442. * Nunjucks support.
  3443. */
  3444. exports.nunjucks = fromStringRenderer('nunjucks');
  3445. /**
  3446. * Nunjucks string support.
  3447. */
  3448. exports.nunjucks.render = function(str, options, cb) {
  3449. return promisify(cb, function(cb) {
  3450. try {
  3451. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3452. var env = engine;
  3453. // deprecated fallback support for express
  3454. // <https://github.com/tj/consolidate.js/pull/152>
  3455. // <https://github.com/tj/consolidate.js/pull/224>
  3456. if (options.settings && options.settings.views) {
  3457. env = engine.configure(options.settings.views);
  3458. } else if (options.nunjucks && options.nunjucks.configure) {
  3459. env = engine.configure.apply(engine, options.nunjucks.configure);
  3460. }
  3461. //
  3462. // because `renderString` does not initiate loaders
  3463. // we must manually create a loader for it based off
  3464. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3465. //
  3466. // <https://github.com/mozilla/nunjucks/issues/730>
  3467. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3468. //
  3469. // so instead we simply check if we passed a custom loader
  3470. // otherwise we create a simple file based loader
  3471. if (options.loader) {
  3472. env = new engine.Environment(options.loader);
  3473. } else if (options.settings && options.settings.views) {
  3474. env = new engine.Environment(
  3475. new engine.FileSystemLoader(options.settings.views)
  3476. );
  3477. } else if (options.nunjucks && options.nunjucks.loader) {
  3478. if (typeof options.nunjucks.loader === 'string') {
  3479. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3480. } else {
  3481. env = new engine.Environment(
  3482. new engine.FileSystemLoader(
  3483. options.nunjucks.loader[0],
  3484. options.nunjucks.loader[1]
  3485. )
  3486. );
  3487. }
  3488. }
  3489. env.renderString(str, options, cb);
  3490. } catch (err) {
  3491. throw cb(err);
  3492. }
  3493. });
  3494. };
  3495. /**
  3496. * HTMLing support.
  3497. */
  3498. exports.htmling = fromStringRenderer('htmling');
  3499. /**
  3500. * HTMLing string support.
  3501. */
  3502. exports.htmling.render = function(str, options, cb) {
  3503. return promisify(cb, function(cb) {
  3504. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3505. try {
  3506. var tmpl = cache(options) || cache(options, engine.string(str));
  3507. cb(null, tmpl.render(options));
  3508. } catch (err) {
  3509. cb(err);
  3510. }
  3511. });
  3512. };
  3513. /**
  3514. * Rendering function
  3515. */
  3516. function requireReact(module, filename) {
  3517. var babel = requires.babel || (requires.babel = require('babel-core'));
  3518. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3519. return module._compile(compiled, filename);
  3520. }
  3521. exports.requireReact = requireReact;
  3522. /**
  3523. * Converting a string into a node module.
  3524. */
  3525. function requireReactString(src, filename) {
  3526. var babel = requires.babel || (requires.babel = require('babel-core'));
  3527. if (!filename) filename = '';
  3528. var m = new module.constructor();
  3529. filename = filename || '';
  3530. // Compile Using React
  3531. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3532. // Compile as a module
  3533. m.paths = module.paths;
  3534. m._compile(compiled, filename);
  3535. return m.exports;
  3536. }
  3537. /**
  3538. * A naive helper to replace {{tags}} with options.tags content
  3539. */
  3540. function reactBaseTmpl(data, options) {
  3541. var exp;
  3542. var regex;
  3543. // Iterates through the keys in file object
  3544. // and interpolate / replace {{key}} with it's value
  3545. for (var k in options) {
  3546. if (options.hasOwnProperty(k)) {
  3547. exp = '{{' + k + '}}';
  3548. regex = new RegExp(exp, 'g');
  3549. if (data.match(regex)) {
  3550. data = data.replace(regex, options[k]);
  3551. }
  3552. }
  3553. }
  3554. return data;
  3555. }
  3556. /**
  3557. * Plates Support.
  3558. */
  3559. exports.plates = fromStringRenderer('plates');
  3560. /**
  3561. * Plates string support.
  3562. */
  3563. exports.plates.render = function(str, options, cb) {
  3564. return promisify(cb, function(cb) {
  3565. var engine = requires.plates || (requires.plates = require('plates'));
  3566. var map = options.map || undefined;
  3567. try {
  3568. var tmpl = engine.bind(str, options, map);
  3569. cb(null, tmpl);
  3570. } catch (err) {
  3571. cb(err);
  3572. }
  3573. });
  3574. };
  3575. /**
  3576. * The main render parser for React bsaed templates
  3577. */
  3578. function reactRenderer(type) {
  3579. if (commonjsRequire.extensions) {
  3580. // Ensure JSX is transformed on require
  3581. if (!commonjsRequire.extensions['.jsx']) {
  3582. commonjsRequire.extensions['.jsx'] = requireReact;
  3583. }
  3584. // Supporting .react extension as well as test cases
  3585. // Using .react extension is not recommended.
  3586. if (!commonjsRequire.extensions['.react']) {
  3587. commonjsRequire.extensions['.react'] = requireReact;
  3588. }
  3589. }
  3590. // Return rendering fx
  3591. return function(str, options, cb) {
  3592. return promisify(cb, function(cb) {
  3593. // React Import
  3594. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3595. var react = requires.react || (requires.react = require('react'));
  3596. // Assign HTML Base
  3597. var base = options.base;
  3598. delete options.base;
  3599. var enableCache = options.cache;
  3600. delete options.cache;
  3601. var isNonStatic = options.isNonStatic;
  3602. delete options.isNonStatic;
  3603. // Start Conversion
  3604. try {
  3605. var Code;
  3606. var Factory;
  3607. var baseStr;
  3608. var content;
  3609. var parsed;
  3610. if (!cache(options)) {
  3611. // Parsing
  3612. if (type === 'path') {
  3613. var path = resolve(str);
  3614. delete require.cache[path];
  3615. Code = commonjsRequire(path);
  3616. } else {
  3617. Code = requireReactString(str);
  3618. }
  3619. Factory = cache(options, react.createFactory(Code));
  3620. } else {
  3621. Factory = cache(options);
  3622. }
  3623. parsed = new Factory(options);
  3624. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3625. if (base) {
  3626. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3627. if (enableCache) {
  3628. readCache[str] = baseStr;
  3629. }
  3630. options.content = content;
  3631. content = reactBaseTmpl(baseStr, options);
  3632. }
  3633. cb(null, content);
  3634. } catch (err) {
  3635. cb(err);
  3636. }
  3637. });
  3638. };
  3639. }
  3640. /**
  3641. * React JS Support
  3642. */
  3643. exports.react = reactRenderer('path');
  3644. /**
  3645. * React JS string support.
  3646. */
  3647. exports.react.render = reactRenderer('string');
  3648. /**
  3649. * ARC-templates support.
  3650. */
  3651. exports['arc-templates'] = fromStringRenderer('arc-templates');
  3652. /**
  3653. * ARC-templates string support.
  3654. */
  3655. exports['arc-templates'].render = function(str, options, cb) {
  3656. var readFileWithOptions = util.promisify(read);
  3657. var consolidateFileSystem = {};
  3658. consolidateFileSystem.readFile = function(path) {
  3659. return readFileWithOptions(path, options);
  3660. };
  3661. return promisify(cb, function(cb) {
  3662. try {
  3663. var engine = requires['arc-templates'];
  3664. if (!engine) {
  3665. var Engine = require('arc-templates/dist/es5');
  3666. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3667. }
  3668. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3669. compiler.then(function(func) { return func(options); })
  3670. .then(function(result) { cb(null, result.content); })
  3671. .catch(cb);
  3672. } catch (err) {
  3673. cb(err);
  3674. }
  3675. });
  3676. };
  3677. /**
  3678. * Vash support
  3679. */
  3680. exports.vash = fromStringRenderer('vash');
  3681. /**
  3682. * Vash string support
  3683. */
  3684. exports.vash.render = function(str, options, cb) {
  3685. return promisify(cb, function(cb) {
  3686. var engine = requires.vash || (requires.vash = require('vash'));
  3687. try {
  3688. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3689. if (options.helpers) {
  3690. for (var key in options.helpers) {
  3691. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3692. continue;
  3693. }
  3694. engine.helpers[key] = options.helpers[key];
  3695. }
  3696. }
  3697. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3698. tmpl(options, function sealLayout(err, ctx) {
  3699. if (err) cb(err);
  3700. ctx.finishLayout();
  3701. cb(null, ctx.toString().replace(/\n$/, ''));
  3702. });
  3703. } catch (err) {
  3704. cb(err);
  3705. }
  3706. });
  3707. };
  3708. /**
  3709. * Slm support.
  3710. */
  3711. exports.slm = fromStringRenderer('slm');
  3712. /**
  3713. * Slm string support.
  3714. */
  3715. exports.slm.render = function(str, options, cb) {
  3716. return promisify(cb, function(cb) {
  3717. var engine = requires.slm || (requires.slm = require('slm'));
  3718. try {
  3719. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3720. cb(null, tmpl(options));
  3721. } catch (err) {
  3722. cb(err);
  3723. }
  3724. });
  3725. };
  3726. /**
  3727. * Marko support.
  3728. */
  3729. exports.marko = function(path, options, cb) {
  3730. return promisify(cb, function(cb) {
  3731. var engine = requires.marko || (requires.marko = require('marko'));
  3732. options.writeToDisk = !!options.cache;
  3733. try {
  3734. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3735. tmpl.renderToString(options, cb);
  3736. } catch (err) {
  3737. cb(err);
  3738. }
  3739. });
  3740. };
  3741. /**
  3742. * Marko string support.
  3743. */
  3744. exports.marko.render = function(str, options, cb) {
  3745. return promisify(cb, function(cb) {
  3746. var engine = requires.marko || (requires.marko = require('marko'));
  3747. options.writeToDisk = !!options.cache;
  3748. options.filename = options.filename || 'string.marko';
  3749. try {
  3750. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3751. tmpl.renderToString(options, cb);
  3752. } catch (err) {
  3753. cb(err);
  3754. }
  3755. });
  3756. };
  3757. /**
  3758. * Teacup support.
  3759. */
  3760. exports.teacup = function(path, options, cb) {
  3761. return promisify(cb, function(cb) {
  3762. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3763. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3764. if (path[0] !== '/') {
  3765. path = join(process.cwd(), path);
  3766. }
  3767. if (!options.cache) {
  3768. var callback = cb;
  3769. cb = function() {
  3770. delete require.cache[path];
  3771. callback.apply(this, arguments);
  3772. };
  3773. }
  3774. engine.renderFile(path, options, cb);
  3775. });
  3776. };
  3777. /**
  3778. * Teacup string support.
  3779. */
  3780. exports.teacup.render = function(str, options, cb) {
  3781. var coffee = require('coffee-script');
  3782. var vm = require('vm');
  3783. var sandbox = {
  3784. module: {exports: {}},
  3785. require: commonjsRequire
  3786. };
  3787. return promisify(cb, function(cb) {
  3788. vm.runInNewContext(coffee.compile(str), sandbox);
  3789. var tmpl = sandbox.module.exports;
  3790. cb(null, tmpl(options));
  3791. });
  3792. };
  3793. /**
  3794. * Squirrelly support.
  3795. */
  3796. exports.squirrelly = fromStringRenderer('squirrelly');
  3797. /**
  3798. * Squirrelly string support.
  3799. */
  3800. exports.squirrelly.render = function(str, options, cb) {
  3801. return promisify(cb, function(cb) {
  3802. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3803. try {
  3804. for (var partial in options.partials) {
  3805. engine.definePartial(partial, options.partials[partial]);
  3806. }
  3807. for (var helper in options.helpers) {
  3808. engine.defineHelper(helper, options.helpers[helper]);
  3809. }
  3810. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3811. cb(null, tmpl(options, engine));
  3812. } catch (err) {
  3813. cb(err);
  3814. }
  3815. });
  3816. };
  3817. /**
  3818. * Twing support.
  3819. */
  3820. exports.twing = fromStringRenderer('twing');
  3821. /**
  3822. * Twing string support.
  3823. */
  3824. exports.twing.render = function(str, options, cb) {
  3825. return promisify(cb, function(cb) {
  3826. var engine = requires.twing || (requires.twing = require('twing'));
  3827. try {
  3828. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3829. twingTemplate.render(options).then((rendTmpl) => {
  3830. var tmpl = cache(options) || cache(options, rendTmpl);
  3831. cb(null, tmpl);
  3832. });
  3833. });
  3834. } catch (err) {
  3835. cb(err);
  3836. }
  3837. });
  3838. };
  3839. /**
  3840. * expose the instance of the engine
  3841. */
  3842. exports.requires = requires;
  3843. } (consolidate$2, consolidate$2.exports));
  3844. return consolidate$2.exports;
  3845. }
  3846. var consolidate$1;
  3847. var hasRequiredConsolidate;
  3848. function requireConsolidate () {
  3849. if (hasRequiredConsolidate) return consolidate$1;
  3850. hasRequiredConsolidate = 1;
  3851. consolidate$1 = /*@__PURE__*/ requireConsolidate$1();
  3852. return consolidate$1;
  3853. }
  3854. var consolidateExports = /*@__PURE__*/ requireConsolidate();
  3855. var consolidate = /*@__PURE__*/getDefaultExportFromCjs(consolidateExports);
  3856. const hasWarned = {};
  3857. function warnOnce(msg) {
  3858. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3859. if (!isNodeProd && true && !hasWarned[msg]) {
  3860. hasWarned[msg] = true;
  3861. warn(msg);
  3862. }
  3863. }
  3864. function warn(msg) {
  3865. console.warn(
  3866. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3867. `
  3868. );
  3869. }
  3870. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3871. let res = "";
  3872. let err = null;
  3873. preprocessor.render(
  3874. source,
  3875. { filename, ...preprocessOptions },
  3876. (_err, _res) => {
  3877. if (_err) err = _err;
  3878. res = _res;
  3879. }
  3880. );
  3881. if (err) throw err;
  3882. return res;
  3883. }
  3884. function compileTemplate(options) {
  3885. const { preprocessLang, preprocessCustomRequire } = options;
  3886. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate[preprocessLang] : false;
  3887. if (preprocessor) {
  3888. try {
  3889. return doCompileTemplate({
  3890. ...options,
  3891. source: preprocess$1(options, preprocessor),
  3892. ast: void 0
  3893. // invalidate AST if template goes through preprocessor
  3894. });
  3895. } catch (e) {
  3896. return {
  3897. code: `export default function render() {}`,
  3898. source: options.source,
  3899. tips: [],
  3900. errors: [e]
  3901. };
  3902. }
  3903. } else if (preprocessLang) {
  3904. return {
  3905. code: `export default function render() {}`,
  3906. source: options.source,
  3907. tips: [
  3908. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3909. ],
  3910. errors: [
  3911. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3912. ]
  3913. };
  3914. } else {
  3915. return doCompileTemplate(options);
  3916. }
  3917. }
  3918. function doCompileTemplate({
  3919. filename,
  3920. id,
  3921. scoped,
  3922. slotted,
  3923. inMap,
  3924. source,
  3925. ast: inAST,
  3926. ssr = false,
  3927. ssrCssVars,
  3928. isProd = false,
  3929. compiler,
  3930. compilerOptions = {},
  3931. transformAssetUrls
  3932. }) {
  3933. const errors = [];
  3934. const warnings = [];
  3935. let nodeTransforms = [];
  3936. if (shared.isObject(transformAssetUrls)) {
  3937. const assetOptions = normalizeOptions(transformAssetUrls);
  3938. nodeTransforms = [
  3939. createAssetUrlTransformWithOptions(assetOptions),
  3940. createSrcsetTransformWithOptions(assetOptions)
  3941. ];
  3942. } else if (transformAssetUrls !== false) {
  3943. nodeTransforms = [transformAssetUrl, transformSrcset];
  3944. }
  3945. if (ssr && !ssrCssVars) {
  3946. warnOnce(
  3947. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  3948. );
  3949. }
  3950. if (!id) {
  3951. warnOnce(`compileTemplate now requires the \`id\` option.`);
  3952. id = "";
  3953. }
  3954. const shortId = id.replace(/^data-v-/, "");
  3955. const longId = `data-v-${shortId}`;
  3956. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3957. compiler = compiler || defaultCompiler;
  3958. if (compiler !== defaultCompiler) {
  3959. inAST = void 0;
  3960. }
  3961. if (inAST == null ? void 0 : inAST.transformed) {
  3962. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3963. prefixIdentifiers: true,
  3964. ...compilerOptions,
  3965. parseMode: "sfc",
  3966. onError: (e) => errors.push(e)
  3967. });
  3968. const template = newAST.children.find(
  3969. (node) => node.type === 1 && node.tag === "template"
  3970. );
  3971. inAST = compilerCore.createRoot(template.children, inAST.source);
  3972. }
  3973. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3974. mode: "module",
  3975. prefixIdentifiers: true,
  3976. hoistStatic: true,
  3977. cacheHandlers: true,
  3978. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3979. scopeId: scoped ? longId : void 0,
  3980. slotted,
  3981. sourceMap: true,
  3982. ...compilerOptions,
  3983. hmr: !isProd,
  3984. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3985. filename,
  3986. onError: (e) => errors.push(e),
  3987. onWarn: (w) => warnings.push(w)
  3988. });
  3989. if (inMap && !inAST) {
  3990. if (map) {
  3991. map = mapLines(inMap, map);
  3992. }
  3993. if (errors.length) {
  3994. patchErrors(errors, source, inMap);
  3995. }
  3996. }
  3997. const tips = warnings.map((w) => {
  3998. let msg = w.message;
  3999. if (w.loc) {
  4000. msg += `
  4001. ${shared.generateCodeFrame(
  4002. (inAST == null ? void 0 : inAST.source) || source,
  4003. w.loc.start.offset,
  4004. w.loc.end.offset
  4005. )}`;
  4006. }
  4007. return msg;
  4008. });
  4009. return { code, ast, preamble, source, errors, tips, map };
  4010. }
  4011. function mapLines(oldMap, newMap) {
  4012. if (!oldMap) return newMap;
  4013. if (!newMap) return oldMap;
  4014. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  4015. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  4016. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  4017. newMapConsumer.eachMapping((m) => {
  4018. if (m.originalLine == null) {
  4019. return;
  4020. }
  4021. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  4022. line: m.originalLine,
  4023. column: m.originalColumn
  4024. });
  4025. if (origPosInOldMap.source == null) {
  4026. return;
  4027. }
  4028. mergedMapGenerator.addMapping({
  4029. generated: {
  4030. line: m.generatedLine,
  4031. column: m.generatedColumn
  4032. },
  4033. original: {
  4034. line: origPosInOldMap.line,
  4035. // map line
  4036. // use current column, since the oldMap produced by @vue/compiler-sfc
  4037. // does not
  4038. column: m.originalColumn
  4039. },
  4040. source: origPosInOldMap.source,
  4041. name: origPosInOldMap.name
  4042. });
  4043. });
  4044. const generator = mergedMapGenerator;
  4045. oldMapConsumer.sources.forEach((sourceFile) => {
  4046. generator._sources.add(sourceFile);
  4047. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  4048. if (sourceContent != null) {
  4049. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  4050. }
  4051. });
  4052. generator._sourceRoot = oldMap.sourceRoot;
  4053. generator._file = oldMap.file;
  4054. return generator.toJSON();
  4055. }
  4056. function patchErrors(errors, source, inMap) {
  4057. const originalSource = inMap.sourcesContent[0];
  4058. const offset = originalSource.indexOf(source);
  4059. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  4060. errors.forEach((err) => {
  4061. if (err.loc) {
  4062. err.loc.start.line += lineOffset;
  4063. err.loc.start.offset += offset;
  4064. if (err.loc.end !== err.loc.start) {
  4065. err.loc.end.line += lineOffset;
  4066. err.loc.end.offset += offset;
  4067. }
  4068. }
  4069. });
  4070. }
  4071. const trimPlugin = () => {
  4072. return {
  4073. postcssPlugin: "vue-sfc-trim",
  4074. Once(root) {
  4075. root.walk(({ type, raws }) => {
  4076. if (type === "rule" || type === "atrule") {
  4077. if (raws.before) raws.before = "\n";
  4078. if ("after" in raws && raws.after) raws.after = "\n";
  4079. }
  4080. });
  4081. }
  4082. };
  4083. };
  4084. trimPlugin.postcss = true;
  4085. var dist$1 = {exports: {}};
  4086. var processor$1 = {exports: {}};
  4087. var parser$1 = {exports: {}};
  4088. var root$1 = {exports: {}};
  4089. var container$1 = {exports: {}};
  4090. var util$2 = {};
  4091. var unesc$1 = {exports: {}};
  4092. var hasRequiredUnesc$1;
  4093. function requireUnesc$1 () {
  4094. if (hasRequiredUnesc$1) return unesc$1.exports;
  4095. hasRequiredUnesc$1 = 1;
  4096. (function (module, exports) {
  4097. exports.__esModule = true;
  4098. exports["default"] = unesc;
  4099. // Many thanks for this post which made this migration much easier.
  4100. // https://mathiasbynens.be/notes/css-escapes
  4101. /**
  4102. *
  4103. * @param {string} str
  4104. * @returns {[string, number]|undefined}
  4105. */
  4106. function gobbleHex(str) {
  4107. var lower = str.toLowerCase();
  4108. var hex = '';
  4109. var spaceTerminated = false;
  4110. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4111. var code = lower.charCodeAt(i);
  4112. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4113. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4114. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4115. spaceTerminated = code === 32;
  4116. if (!valid) {
  4117. break;
  4118. }
  4119. hex += lower[i];
  4120. }
  4121. if (hex.length === 0) {
  4122. return undefined;
  4123. }
  4124. var codePoint = parseInt(hex, 16);
  4125. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4126. // Add special case for
  4127. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4128. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4129. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4130. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4131. }
  4132. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4133. }
  4134. var CONTAINS_ESCAPE = /\\/;
  4135. function unesc(str) {
  4136. var needToProcess = CONTAINS_ESCAPE.test(str);
  4137. if (!needToProcess) {
  4138. return str;
  4139. }
  4140. var ret = "";
  4141. for (var i = 0; i < str.length; i++) {
  4142. if (str[i] === "\\") {
  4143. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4144. if (gobbled !== undefined) {
  4145. ret += gobbled[0];
  4146. i += gobbled[1];
  4147. continue;
  4148. }
  4149. // Retain a pair of \\ if double escaped `\\\\`
  4150. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4151. if (str[i + 1] === "\\") {
  4152. ret += "\\";
  4153. i++;
  4154. continue;
  4155. }
  4156. // if \\ is at the end of the string retain it
  4157. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4158. if (str.length === i + 1) {
  4159. ret += str[i];
  4160. }
  4161. continue;
  4162. }
  4163. ret += str[i];
  4164. }
  4165. return ret;
  4166. }
  4167. module.exports = exports.default;
  4168. } (unesc$1, unesc$1.exports));
  4169. return unesc$1.exports;
  4170. }
  4171. var getProp$1 = {exports: {}};
  4172. var hasRequiredGetProp$1;
  4173. function requireGetProp$1 () {
  4174. if (hasRequiredGetProp$1) return getProp$1.exports;
  4175. hasRequiredGetProp$1 = 1;
  4176. (function (module, exports) {
  4177. exports.__esModule = true;
  4178. exports["default"] = getProp;
  4179. function getProp(obj) {
  4180. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4181. props[_key - 1] = arguments[_key];
  4182. }
  4183. while (props.length > 0) {
  4184. var prop = props.shift();
  4185. if (!obj[prop]) {
  4186. return undefined;
  4187. }
  4188. obj = obj[prop];
  4189. }
  4190. return obj;
  4191. }
  4192. module.exports = exports.default;
  4193. } (getProp$1, getProp$1.exports));
  4194. return getProp$1.exports;
  4195. }
  4196. var ensureObject$1 = {exports: {}};
  4197. var hasRequiredEnsureObject$1;
  4198. function requireEnsureObject$1 () {
  4199. if (hasRequiredEnsureObject$1) return ensureObject$1.exports;
  4200. hasRequiredEnsureObject$1 = 1;
  4201. (function (module, exports) {
  4202. exports.__esModule = true;
  4203. exports["default"] = ensureObject;
  4204. function ensureObject(obj) {
  4205. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4206. props[_key - 1] = arguments[_key];
  4207. }
  4208. while (props.length > 0) {
  4209. var prop = props.shift();
  4210. if (!obj[prop]) {
  4211. obj[prop] = {};
  4212. }
  4213. obj = obj[prop];
  4214. }
  4215. }
  4216. module.exports = exports.default;
  4217. } (ensureObject$1, ensureObject$1.exports));
  4218. return ensureObject$1.exports;
  4219. }
  4220. var stripComments$1 = {exports: {}};
  4221. var hasRequiredStripComments$1;
  4222. function requireStripComments$1 () {
  4223. if (hasRequiredStripComments$1) return stripComments$1.exports;
  4224. hasRequiredStripComments$1 = 1;
  4225. (function (module, exports) {
  4226. exports.__esModule = true;
  4227. exports["default"] = stripComments;
  4228. function stripComments(str) {
  4229. var s = "";
  4230. var commentStart = str.indexOf("/*");
  4231. var lastEnd = 0;
  4232. while (commentStart >= 0) {
  4233. s = s + str.slice(lastEnd, commentStart);
  4234. var commentEnd = str.indexOf("*/", commentStart + 2);
  4235. if (commentEnd < 0) {
  4236. return s;
  4237. }
  4238. lastEnd = commentEnd + 2;
  4239. commentStart = str.indexOf("/*", lastEnd);
  4240. }
  4241. s = s + str.slice(lastEnd);
  4242. return s;
  4243. }
  4244. module.exports = exports.default;
  4245. } (stripComments$1, stripComments$1.exports));
  4246. return stripComments$1.exports;
  4247. }
  4248. var maxNestingDepth = {};
  4249. var hasRequiredMaxNestingDepth;
  4250. function requireMaxNestingDepth () {
  4251. if (hasRequiredMaxNestingDepth) return maxNestingDepth;
  4252. hasRequiredMaxNestingDepth = 1;
  4253. (function (exports) {
  4254. exports.__esModule = true;
  4255. exports.MAX_NESTING_DEPTH = void 0;
  4256. exports["default"] = resolveMaxNestingDepth;
  4257. /**
  4258. * The default maximum selector nesting depth allowed when parsing or
  4259. * serializing a selector. Going beyond this would otherwise recurse deeply
  4260. * enough to overflow the call stack (CVE-2026-9358 / CWE-674). Real-world
  4261. * selectors never get anywhere near this, so it acts purely as a safety net
  4262. * that turns an uncatchable stack overflow into a catchable error.
  4263. */
  4264. var MAX_NESTING_DEPTH = exports.MAX_NESTING_DEPTH = 256;
  4265. /**
  4266. * Coerce a user-supplied nesting-depth limit into a safe value. Anything that
  4267. * is not a non-negative safe integer (NaN, Infinity, negative numbers, or a
  4268. * non-number) would disable or break the guard, so it falls back to the
  4269. * default.
  4270. *
  4271. * @param {unknown} value the limit provided through the `maxNestingDepth` option
  4272. * @returns {number} a safe, non-negative integer limit
  4273. */
  4274. function resolveMaxNestingDepth(value) {
  4275. return Number.isSafeInteger(value) && value >= 0 ? value : MAX_NESTING_DEPTH;
  4276. }
  4277. } (maxNestingDepth));
  4278. return maxNestingDepth;
  4279. }
  4280. var hasRequiredUtil$2;
  4281. function requireUtil$2 () {
  4282. if (hasRequiredUtil$2) return util$2;
  4283. hasRequiredUtil$2 = 1;
  4284. util$2.__esModule = true;
  4285. util$2.unesc = util$2.stripComments = util$2.resolveMaxNestingDepth = util$2.getProp = util$2.ensureObject = util$2.MAX_NESTING_DEPTH = void 0;
  4286. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  4287. util$2.unesc = _unesc["default"];
  4288. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp$1());
  4289. util$2.getProp = _getProp["default"];
  4290. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject$1());
  4291. util$2.ensureObject = _ensureObject["default"];
  4292. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments$1());
  4293. util$2.stripComments = _stripComments["default"];
  4294. var _maxNestingDepth = _interopRequireWildcard(/*@__PURE__*/ requireMaxNestingDepth());
  4295. util$2.resolveMaxNestingDepth = _maxNestingDepth["default"];
  4296. util$2.MAX_NESTING_DEPTH = _maxNestingDepth.MAX_NESTING_DEPTH;
  4297. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  4298. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  4299. return util$2;
  4300. }
  4301. var node$2 = {exports: {}};
  4302. var hasRequiredNode$2;
  4303. function requireNode$2 () {
  4304. if (hasRequiredNode$2) return node$2.exports;
  4305. hasRequiredNode$2 = 1;
  4306. (function (module, exports) {
  4307. exports.__esModule = true;
  4308. exports["default"] = void 0;
  4309. var _util = /*@__PURE__*/ requireUtil$2();
  4310. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  4311. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  4312. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  4313. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  4314. var cloneNode = function cloneNode(obj, parent) {
  4315. if (typeof obj !== 'object' || obj === null) {
  4316. return obj;
  4317. }
  4318. var cloned = new obj.constructor();
  4319. for (var i in obj) {
  4320. if (!obj.hasOwnProperty(i)) {
  4321. continue;
  4322. }
  4323. var value = obj[i];
  4324. var type = typeof value;
  4325. if (i === 'parent' && type === 'object') {
  4326. if (parent) {
  4327. cloned[i] = parent;
  4328. }
  4329. } else if (value instanceof Array) {
  4330. cloned[i] = value.map(function (j) {
  4331. return cloneNode(j, cloned);
  4332. });
  4333. } else {
  4334. cloned[i] = cloneNode(value, cloned);
  4335. }
  4336. }
  4337. return cloned;
  4338. };
  4339. exports["default"] = /*#__PURE__*/function () {
  4340. function Node(opts) {
  4341. if (opts === void 0) {
  4342. opts = {};
  4343. }
  4344. Object.assign(this, opts);
  4345. this.spaces = this.spaces || {};
  4346. this.spaces.before = this.spaces.before || '';
  4347. this.spaces.after = this.spaces.after || '';
  4348. }
  4349. var _proto = Node.prototype;
  4350. _proto.remove = function remove() {
  4351. if (this.parent) {
  4352. this.parent.removeChild(this);
  4353. }
  4354. this.parent = undefined;
  4355. return this;
  4356. };
  4357. _proto.replaceWith = function replaceWith() {
  4358. if (this.parent) {
  4359. for (var index in arguments) {
  4360. this.parent.insertBefore(this, arguments[index]);
  4361. }
  4362. this.remove();
  4363. }
  4364. return this;
  4365. };
  4366. _proto.next = function next() {
  4367. return this.parent.at(this.parent.index(this) + 1);
  4368. };
  4369. _proto.prev = function prev() {
  4370. return this.parent.at(this.parent.index(this) - 1);
  4371. };
  4372. _proto.clone = function clone(overrides) {
  4373. if (overrides === void 0) {
  4374. overrides = {};
  4375. }
  4376. var cloned = cloneNode(this);
  4377. for (var name in overrides) {
  4378. cloned[name] = overrides[name];
  4379. }
  4380. return cloned;
  4381. }
  4382. /**
  4383. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4384. * This allows non standard syntax to be appended to an existing property
  4385. * by specifying the escaped value. By specifying the escaped value,
  4386. * illegal characters are allowed to be directly inserted into css output.
  4387. * @param {string} name the property to set
  4388. * @param {any} value the unescaped value of the property
  4389. * @param {string} valueEscaped optional. the escaped value of the property.
  4390. */;
  4391. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4392. if (!this.raws) {
  4393. this.raws = {};
  4394. }
  4395. var originalValue = this[name];
  4396. var originalEscaped = this.raws[name];
  4397. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4398. if (originalEscaped || valueEscaped !== value) {
  4399. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4400. } else {
  4401. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4402. }
  4403. }
  4404. /**
  4405. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4406. * This allows the escaped value to be specified directly, allowing illegal
  4407. * characters to be directly inserted into css output.
  4408. * @param {string} name the property to set
  4409. * @param {any} value the unescaped value of the property
  4410. * @param {string} valueEscaped the escaped value of the property.
  4411. */;
  4412. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4413. if (!this.raws) {
  4414. this.raws = {};
  4415. }
  4416. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4417. this.raws[name] = valueEscaped;
  4418. }
  4419. /**
  4420. * When you want a value to passed through to CSS directly. This method
  4421. * deletes the corresponding raw value causing the stringifier to fallback
  4422. * to the unescaped value.
  4423. * @param {string} name the property to set.
  4424. * @param {any} value The value that is both escaped and unescaped.
  4425. */;
  4426. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4427. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4428. if (this.raws) {
  4429. delete this.raws[name];
  4430. }
  4431. }
  4432. /**
  4433. *
  4434. * @param {number} line The number (starting with 1)
  4435. * @param {number} column The column number (starting with 1)
  4436. */;
  4437. _proto.isAtPosition = function isAtPosition(line, column) {
  4438. if (this.source && this.source.start && this.source.end) {
  4439. if (this.source.start.line > line) {
  4440. return false;
  4441. }
  4442. if (this.source.end.line < line) {
  4443. return false;
  4444. }
  4445. if (this.source.start.line === line && this.source.start.column > column) {
  4446. return false;
  4447. }
  4448. if (this.source.end.line === line && this.source.end.column < column) {
  4449. return false;
  4450. }
  4451. return true;
  4452. }
  4453. return undefined;
  4454. };
  4455. _proto.stringifyProperty = function stringifyProperty(name) {
  4456. return this.raws && this.raws[name] || this[name];
  4457. };
  4458. _proto.valueToString = function valueToString() {
  4459. return String(this.stringifyProperty("value"));
  4460. };
  4461. _proto.toString = function toString() {
  4462. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4463. }
  4464. // Internal recursion entry point used by Container serialization. Leaf
  4465. // nodes don't recurse, so they ignore the depth/limit and stringify
  4466. // themselves. Containers override this to thread the nesting depth.
  4467. ;
  4468. _proto._stringify = function _stringify() {
  4469. return this.toString();
  4470. };
  4471. _createClass(Node, [{
  4472. key: "rawSpaceBefore",
  4473. get: function get() {
  4474. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4475. if (rawSpace === undefined) {
  4476. rawSpace = this.spaces && this.spaces.before;
  4477. }
  4478. return rawSpace || "";
  4479. },
  4480. set: function set(raw) {
  4481. (0, _util.ensureObject)(this, "raws", "spaces");
  4482. this.raws.spaces.before = raw;
  4483. }
  4484. }, {
  4485. key: "rawSpaceAfter",
  4486. get: function get() {
  4487. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4488. if (rawSpace === undefined) {
  4489. rawSpace = this.spaces.after;
  4490. }
  4491. return rawSpace || "";
  4492. },
  4493. set: function set(raw) {
  4494. (0, _util.ensureObject)(this, "raws", "spaces");
  4495. this.raws.spaces.after = raw;
  4496. }
  4497. }]);
  4498. return Node;
  4499. }();
  4500. module.exports = exports.default;
  4501. } (node$2, node$2.exports));
  4502. return node$2.exports;
  4503. }
  4504. var types$2 = {};
  4505. var hasRequiredTypes$1;
  4506. function requireTypes$1 () {
  4507. if (hasRequiredTypes$1) return types$2;
  4508. hasRequiredTypes$1 = 1;
  4509. types$2.__esModule = true;
  4510. types$2.UNIVERSAL = types$2.TAG = types$2.STRING = types$2.SELECTOR = types$2.ROOT = types$2.PSEUDO = types$2.NESTING = types$2.ID = types$2.COMMENT = types$2.COMBINATOR = types$2.CLASS = types$2.ATTRIBUTE = void 0;
  4511. types$2.TAG = 'tag';
  4512. types$2.STRING = 'string';
  4513. types$2.SELECTOR = 'selector';
  4514. types$2.ROOT = 'root';
  4515. types$2.PSEUDO = 'pseudo';
  4516. types$2.NESTING = 'nesting';
  4517. types$2.ID = 'id';
  4518. types$2.COMMENT = 'comment';
  4519. types$2.COMBINATOR = 'combinator';
  4520. types$2.CLASS = 'class';
  4521. types$2.ATTRIBUTE = 'attribute';
  4522. types$2.UNIVERSAL = 'universal';
  4523. return types$2;
  4524. }
  4525. var hasRequiredContainer$1;
  4526. function requireContainer$1 () {
  4527. if (hasRequiredContainer$1) return container$1.exports;
  4528. hasRequiredContainer$1 = 1;
  4529. (function (module, exports) {
  4530. exports.__esModule = true;
  4531. exports["default"] = void 0;
  4532. var _util = /*@__PURE__*/ requireUtil$2();
  4533. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4534. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  4535. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  4536. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  4537. function _createForOfIteratorHelperLoose(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (t) return (t = t.call(r)).next.bind(t); if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) { t && (r = t); var o = 0; return function () { return o >= r.length ? { done: true } : { done: false, value: r[o++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  4538. function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
  4539. function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
  4540. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  4541. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  4542. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  4543. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  4544. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  4545. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  4546. exports["default"] = /*#__PURE__*/function (_Node) {
  4547. _inheritsLoose(Container, _Node);
  4548. function Container(opts) {
  4549. var _this;
  4550. _this = _Node.call(this, opts) || this;
  4551. if (!_this.nodes) {
  4552. _this.nodes = [];
  4553. }
  4554. return _this;
  4555. }
  4556. var _proto = Container.prototype;
  4557. _proto.append = function append(selector) {
  4558. selector.parent = this;
  4559. this.nodes.push(selector);
  4560. return this;
  4561. };
  4562. _proto.prepend = function prepend(selector) {
  4563. selector.parent = this;
  4564. this.nodes.unshift(selector);
  4565. for (var id in this.indexes) {
  4566. this.indexes[id]++;
  4567. }
  4568. return this;
  4569. };
  4570. _proto.at = function at(index) {
  4571. return this.nodes[index];
  4572. };
  4573. _proto.index = function index(child) {
  4574. if (typeof child === 'number') {
  4575. return child;
  4576. }
  4577. return this.nodes.indexOf(child);
  4578. };
  4579. _proto.removeChild = function removeChild(child) {
  4580. child = this.index(child);
  4581. this.at(child).parent = undefined;
  4582. this.nodes.splice(child, 1);
  4583. var index;
  4584. for (var id in this.indexes) {
  4585. index = this.indexes[id];
  4586. if (index >= child) {
  4587. this.indexes[id] = index - 1;
  4588. }
  4589. }
  4590. return this;
  4591. };
  4592. _proto.removeAll = function removeAll() {
  4593. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4594. var node = _step.value;
  4595. node.parent = undefined;
  4596. }
  4597. this.nodes = [];
  4598. return this;
  4599. };
  4600. _proto.empty = function empty() {
  4601. return this.removeAll();
  4602. };
  4603. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4604. var _this$nodes;
  4605. newNode.parent = this;
  4606. var oldIndex = this.index(oldNode);
  4607. var resetNode = [];
  4608. for (var i = 2; i < arguments.length; i++) {
  4609. resetNode.push(arguments[i]);
  4610. }
  4611. (_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
  4612. newNode.parent = this;
  4613. var index;
  4614. for (var id in this.indexes) {
  4615. index = this.indexes[id];
  4616. if (oldIndex < index) {
  4617. this.indexes[id] = index + arguments.length - 1;
  4618. }
  4619. }
  4620. return this;
  4621. };
  4622. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4623. var _this$nodes2;
  4624. newNode.parent = this;
  4625. var oldIndex = this.index(oldNode);
  4626. var resetNode = [];
  4627. for (var i = 2; i < arguments.length; i++) {
  4628. resetNode.push(arguments[i]);
  4629. }
  4630. (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
  4631. newNode.parent = this;
  4632. var index;
  4633. for (var id in this.indexes) {
  4634. index = this.indexes[id];
  4635. if (index >= oldIndex) {
  4636. this.indexes[id] = index + arguments.length - 1;
  4637. }
  4638. }
  4639. return this;
  4640. };
  4641. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4642. var found = undefined;
  4643. this.each(function (node) {
  4644. if (node.atPosition) {
  4645. var foundChild = node.atPosition(line, col);
  4646. if (foundChild) {
  4647. found = foundChild;
  4648. return false;
  4649. }
  4650. } else if (node.isAtPosition(line, col)) {
  4651. found = node;
  4652. return false;
  4653. }
  4654. });
  4655. return found;
  4656. }
  4657. /**
  4658. * Return the most specific node at the line and column number given.
  4659. * The source location is based on the original parsed location, locations aren't
  4660. * updated as selector nodes are mutated.
  4661. *
  4662. * Note that this location is relative to the location of the first character
  4663. * of the selector, and not the location of the selector in the overall document
  4664. * when used in conjunction with postcss.
  4665. *
  4666. * If not found, returns undefined.
  4667. * @param {number} line The line number of the node to find. (1-based index)
  4668. * @param {number} col The column number of the node to find. (1-based index)
  4669. */;
  4670. _proto.atPosition = function atPosition(line, col) {
  4671. if (this.isAtPosition(line, col)) {
  4672. return this._findChildAtPosition(line, col) || this;
  4673. } else {
  4674. return undefined;
  4675. }
  4676. };
  4677. _proto._inferEndPosition = function _inferEndPosition() {
  4678. if (this.last && this.last.source && this.last.source.end) {
  4679. this.source = this.source || {};
  4680. this.source.end = this.source.end || {};
  4681. Object.assign(this.source.end, this.last.source.end);
  4682. }
  4683. };
  4684. _proto.each = function each(callback) {
  4685. if (!this.lastEach) {
  4686. this.lastEach = 0;
  4687. }
  4688. if (!this.indexes) {
  4689. this.indexes = {};
  4690. }
  4691. this.lastEach++;
  4692. var id = this.lastEach;
  4693. this.indexes[id] = 0;
  4694. if (!this.length) {
  4695. return undefined;
  4696. }
  4697. var index, result;
  4698. while (this.indexes[id] < this.length) {
  4699. index = this.indexes[id];
  4700. result = callback(this.at(index), index);
  4701. if (result === false) {
  4702. break;
  4703. }
  4704. this.indexes[id] += 1;
  4705. }
  4706. delete this.indexes[id];
  4707. if (result === false) {
  4708. return false;
  4709. }
  4710. };
  4711. _proto.walk = function walk(callback) {
  4712. return this.each(function (node, i) {
  4713. var result = callback(node, i);
  4714. if (result !== false && node.length) {
  4715. result = node.walk(callback);
  4716. }
  4717. if (result === false) {
  4718. return false;
  4719. }
  4720. });
  4721. };
  4722. _proto.walkAttributes = function walkAttributes(callback) {
  4723. var _this2 = this;
  4724. return this.walk(function (selector) {
  4725. if (selector.type === types.ATTRIBUTE) {
  4726. return callback.call(_this2, selector);
  4727. }
  4728. });
  4729. };
  4730. _proto.walkClasses = function walkClasses(callback) {
  4731. var _this3 = this;
  4732. return this.walk(function (selector) {
  4733. if (selector.type === types.CLASS) {
  4734. return callback.call(_this3, selector);
  4735. }
  4736. });
  4737. };
  4738. _proto.walkCombinators = function walkCombinators(callback) {
  4739. var _this4 = this;
  4740. return this.walk(function (selector) {
  4741. if (selector.type === types.COMBINATOR) {
  4742. return callback.call(_this4, selector);
  4743. }
  4744. });
  4745. };
  4746. _proto.walkComments = function walkComments(callback) {
  4747. var _this5 = this;
  4748. return this.walk(function (selector) {
  4749. if (selector.type === types.COMMENT) {
  4750. return callback.call(_this5, selector);
  4751. }
  4752. });
  4753. };
  4754. _proto.walkIds = function walkIds(callback) {
  4755. var _this6 = this;
  4756. return this.walk(function (selector) {
  4757. if (selector.type === types.ID) {
  4758. return callback.call(_this6, selector);
  4759. }
  4760. });
  4761. };
  4762. _proto.walkNesting = function walkNesting(callback) {
  4763. var _this7 = this;
  4764. return this.walk(function (selector) {
  4765. if (selector.type === types.NESTING) {
  4766. return callback.call(_this7, selector);
  4767. }
  4768. });
  4769. };
  4770. _proto.walkPseudos = function walkPseudos(callback) {
  4771. var _this8 = this;
  4772. return this.walk(function (selector) {
  4773. if (selector.type === types.PSEUDO) {
  4774. return callback.call(_this8, selector);
  4775. }
  4776. });
  4777. };
  4778. _proto.walkTags = function walkTags(callback) {
  4779. var _this9 = this;
  4780. return this.walk(function (selector) {
  4781. if (selector.type === types.TAG) {
  4782. return callback.call(_this9, selector);
  4783. }
  4784. });
  4785. };
  4786. _proto.walkUniversals = function walkUniversals(callback) {
  4787. var _this0 = this;
  4788. return this.walk(function (selector) {
  4789. if (selector.type === types.UNIVERSAL) {
  4790. return callback.call(_this0, selector);
  4791. }
  4792. });
  4793. };
  4794. _proto.split = function split(callback) {
  4795. var _this1 = this;
  4796. var current = [];
  4797. return this.reduce(function (memo, node, index) {
  4798. var split = callback.call(_this1, node);
  4799. current.push(node);
  4800. if (split) {
  4801. memo.push(current);
  4802. current = [];
  4803. } else if (index === _this1.length - 1) {
  4804. memo.push(current);
  4805. }
  4806. return memo;
  4807. }, []);
  4808. };
  4809. _proto.map = function map(callback) {
  4810. return this.nodes.map(callback);
  4811. };
  4812. _proto.reduce = function reduce(callback, memo) {
  4813. return this.nodes.reduce(callback, memo);
  4814. };
  4815. _proto.every = function every(callback) {
  4816. return this.nodes.every(callback);
  4817. };
  4818. _proto.some = function some(callback) {
  4819. return this.nodes.some(callback);
  4820. };
  4821. _proto.filter = function filter(callback) {
  4822. return this.nodes.filter(callback);
  4823. };
  4824. _proto.sort = function sort(callback) {
  4825. return this.nodes.sort(callback);
  4826. };
  4827. _proto.toString = function toString(options) {
  4828. if (options === void 0) {
  4829. options = {};
  4830. }
  4831. return this._stringify(options, 0, (0, _util.resolveMaxNestingDepth)(options.maxNestingDepth));
  4832. };
  4833. _proto._stringify = function _stringify(options, depth, max) {
  4834. return this.map(function (child) {
  4835. return child._stringify(options, depth, max);
  4836. }).join('');
  4837. };
  4838. _createClass(Container, [{
  4839. key: "first",
  4840. get: function get() {
  4841. return this.at(0);
  4842. }
  4843. }, {
  4844. key: "last",
  4845. get: function get() {
  4846. return this.at(this.length - 1);
  4847. }
  4848. }, {
  4849. key: "length",
  4850. get: function get() {
  4851. return this.nodes.length;
  4852. }
  4853. }]);
  4854. return Container;
  4855. }(_node["default"]);
  4856. module.exports = exports.default;
  4857. } (container$1, container$1.exports));
  4858. return container$1.exports;
  4859. }
  4860. var hasRequiredRoot$1;
  4861. function requireRoot$1 () {
  4862. if (hasRequiredRoot$1) return root$1.exports;
  4863. hasRequiredRoot$1 = 1;
  4864. (function (module, exports) {
  4865. exports.__esModule = true;
  4866. exports["default"] = void 0;
  4867. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4868. var _types = /*@__PURE__*/ requireTypes$1();
  4869. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  4870. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  4871. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  4872. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  4873. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  4874. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  4875. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  4876. exports["default"] = /*#__PURE__*/function (_Container) {
  4877. _inheritsLoose(Root, _Container);
  4878. function Root(opts) {
  4879. var _this;
  4880. _this = _Container.call(this, opts) || this;
  4881. _this.type = _types.ROOT;
  4882. return _this;
  4883. }
  4884. var _proto = Root.prototype;
  4885. _proto._stringify = function _stringify(options, depth, max) {
  4886. var str = this.reduce(function (memo, selector) {
  4887. memo.push(selector._stringify(options, depth, max));
  4888. return memo;
  4889. }, []).join(',');
  4890. return this.trailingComma ? str + ',' : str;
  4891. };
  4892. _proto.error = function error(message, options) {
  4893. if (this._error) {
  4894. return this._error(message, options);
  4895. } else {
  4896. return new Error(message);
  4897. }
  4898. };
  4899. _createClass(Root, [{
  4900. key: "errorGenerator",
  4901. set: function set(handler) {
  4902. this._error = handler;
  4903. }
  4904. }]);
  4905. return Root;
  4906. }(_container["default"]);
  4907. module.exports = exports.default;
  4908. } (root$1, root$1.exports));
  4909. return root$1.exports;
  4910. }
  4911. var selector$1 = {exports: {}};
  4912. var hasRequiredSelector$1;
  4913. function requireSelector$1 () {
  4914. if (hasRequiredSelector$1) return selector$1.exports;
  4915. hasRequiredSelector$1 = 1;
  4916. (function (module, exports) {
  4917. exports.__esModule = true;
  4918. exports["default"] = void 0;
  4919. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4920. var _types = /*@__PURE__*/ requireTypes$1();
  4921. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  4922. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  4923. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  4924. exports["default"] = /*#__PURE__*/function (_Container) {
  4925. _inheritsLoose(Selector, _Container);
  4926. function Selector(opts) {
  4927. var _this;
  4928. _this = _Container.call(this, opts) || this;
  4929. _this.type = _types.SELECTOR;
  4930. return _this;
  4931. }
  4932. return Selector;
  4933. }(_container["default"]);
  4934. module.exports = exports.default;
  4935. } (selector$1, selector$1.exports));
  4936. return selector$1.exports;
  4937. }
  4938. var className$1 = {exports: {}};
  4939. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4940. var cssesc_1;
  4941. var hasRequiredCssesc;
  4942. function requireCssesc () {
  4943. if (hasRequiredCssesc) return cssesc_1;
  4944. hasRequiredCssesc = 1;
  4945. var object = {};
  4946. var hasOwnProperty = object.hasOwnProperty;
  4947. var merge = function merge(options, defaults) {
  4948. if (!options) {
  4949. return defaults;
  4950. }
  4951. var result = {};
  4952. for (var key in defaults) {
  4953. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4954. // only recognized option names are used.
  4955. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  4956. }
  4957. return result;
  4958. };
  4959. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4960. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4961. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4962. // https://mathiasbynens.be/notes/css-escapes#css
  4963. var cssesc = function cssesc(string, options) {
  4964. options = merge(options, cssesc.options);
  4965. if (options.quotes != 'single' && options.quotes != 'double') {
  4966. options.quotes = 'single';
  4967. }
  4968. var quote = options.quotes == 'double' ? '"' : '\'';
  4969. var isIdentifier = options.isIdentifier;
  4970. var firstChar = string.charAt(0);
  4971. var output = '';
  4972. var counter = 0;
  4973. var length = string.length;
  4974. while (counter < length) {
  4975. var character = string.charAt(counter++);
  4976. var codePoint = character.charCodeAt();
  4977. var value = void 0;
  4978. // If it’s not a printable ASCII character…
  4979. if (codePoint < 0x20 || codePoint > 0x7E) {
  4980. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4981. // It’s a high surrogate, and there is a next character.
  4982. var extra = string.charCodeAt(counter++);
  4983. if ((extra & 0xFC00) == 0xDC00) {
  4984. // next character is low surrogate
  4985. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4986. } else {
  4987. // It’s an unmatched surrogate; only append this code unit, in case
  4988. // the next code unit is the high surrogate of a surrogate pair.
  4989. counter--;
  4990. }
  4991. }
  4992. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4993. } else {
  4994. if (options.escapeEverything) {
  4995. if (regexAnySingleEscape.test(character)) {
  4996. value = '\\' + character;
  4997. } else {
  4998. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4999. }
  5000. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  5001. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  5002. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  5003. value = '\\' + character;
  5004. } else {
  5005. value = character;
  5006. }
  5007. }
  5008. output += value;
  5009. }
  5010. if (isIdentifier) {
  5011. if (/^-[-\d]/.test(output)) {
  5012. output = '\\-' + output.slice(1);
  5013. } else if (/\d/.test(firstChar)) {
  5014. output = '\\3' + firstChar + ' ' + output.slice(1);
  5015. }
  5016. }
  5017. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  5018. // since they’re redundant. Note that this is only possible if the escape
  5019. // sequence isn’t preceded by an odd number of backslashes.
  5020. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  5021. if ($1 && $1.length % 2) {
  5022. // It’s not safe to remove the space, so don’t.
  5023. return $0;
  5024. }
  5025. // Strip the space.
  5026. return ($1 || '') + $2;
  5027. });
  5028. if (!isIdentifier && options.wrap) {
  5029. return quote + output + quote;
  5030. }
  5031. return output;
  5032. };
  5033. // Expose default options (so they can be overridden globally).
  5034. cssesc.options = {
  5035. 'escapeEverything': false,
  5036. 'isIdentifier': false,
  5037. 'quotes': 'single',
  5038. 'wrap': false
  5039. };
  5040. cssesc.version = '3.0.0';
  5041. cssesc_1 = cssesc;
  5042. return cssesc_1;
  5043. }
  5044. var hasRequiredClassName$1;
  5045. function requireClassName$1 () {
  5046. if (hasRequiredClassName$1) return className$1.exports;
  5047. hasRequiredClassName$1 = 1;
  5048. (function (module, exports) {
  5049. exports.__esModule = true;
  5050. exports["default"] = void 0;
  5051. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5052. var _util = /*@__PURE__*/ requireUtil$2();
  5053. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5054. var _types = /*@__PURE__*/ requireTypes$1();
  5055. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5056. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  5057. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  5058. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  5059. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  5060. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5061. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5062. exports["default"] = /*#__PURE__*/function (_Node) {
  5063. _inheritsLoose(ClassName, _Node);
  5064. function ClassName(opts) {
  5065. var _this;
  5066. _this = _Node.call(this, opts) || this;
  5067. _this.type = _types.CLASS;
  5068. _this._constructed = true;
  5069. return _this;
  5070. }
  5071. var _proto = ClassName.prototype;
  5072. _proto.valueToString = function valueToString() {
  5073. return '.' + _Node.prototype.valueToString.call(this);
  5074. };
  5075. _createClass(ClassName, [{
  5076. key: "value",
  5077. get: function get() {
  5078. return this._value;
  5079. },
  5080. set: function set(v) {
  5081. if (this._constructed) {
  5082. var escaped = (0, _cssesc["default"])(v, {
  5083. isIdentifier: true
  5084. });
  5085. if (escaped !== v) {
  5086. (0, _util.ensureObject)(this, "raws");
  5087. this.raws.value = escaped;
  5088. } else if (this.raws) {
  5089. delete this.raws.value;
  5090. }
  5091. }
  5092. this._value = v;
  5093. }
  5094. }]);
  5095. return ClassName;
  5096. }(_node["default"]);
  5097. module.exports = exports.default;
  5098. } (className$1, className$1.exports));
  5099. return className$1.exports;
  5100. }
  5101. var comment$1 = {exports: {}};
  5102. var hasRequiredComment$1;
  5103. function requireComment$1 () {
  5104. if (hasRequiredComment$1) return comment$1.exports;
  5105. hasRequiredComment$1 = 1;
  5106. (function (module, exports) {
  5107. exports.__esModule = true;
  5108. exports["default"] = void 0;
  5109. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5110. var _types = /*@__PURE__*/ requireTypes$1();
  5111. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5112. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5113. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5114. exports["default"] = /*#__PURE__*/function (_Node) {
  5115. _inheritsLoose(Comment, _Node);
  5116. function Comment(opts) {
  5117. var _this;
  5118. _this = _Node.call(this, opts) || this;
  5119. _this.type = _types.COMMENT;
  5120. return _this;
  5121. }
  5122. return Comment;
  5123. }(_node["default"]);
  5124. module.exports = exports.default;
  5125. } (comment$1, comment$1.exports));
  5126. return comment$1.exports;
  5127. }
  5128. var id$1 = {exports: {}};
  5129. var hasRequiredId$1;
  5130. function requireId$1 () {
  5131. if (hasRequiredId$1) return id$1.exports;
  5132. hasRequiredId$1 = 1;
  5133. (function (module, exports) {
  5134. exports.__esModule = true;
  5135. exports["default"] = void 0;
  5136. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5137. var _types = /*@__PURE__*/ requireTypes$1();
  5138. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5139. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5140. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5141. exports["default"] = /*#__PURE__*/function (_Node) {
  5142. _inheritsLoose(ID, _Node);
  5143. function ID(opts) {
  5144. var _this;
  5145. _this = _Node.call(this, opts) || this;
  5146. _this.type = _types.ID;
  5147. return _this;
  5148. }
  5149. var _proto = ID.prototype;
  5150. _proto.valueToString = function valueToString() {
  5151. return '#' + _Node.prototype.valueToString.call(this);
  5152. };
  5153. return ID;
  5154. }(_node["default"]);
  5155. module.exports = exports.default;
  5156. } (id$1, id$1.exports));
  5157. return id$1.exports;
  5158. }
  5159. var tag$1 = {exports: {}};
  5160. var namespace$1 = {exports: {}};
  5161. var hasRequiredNamespace$1;
  5162. function requireNamespace$1 () {
  5163. if (hasRequiredNamespace$1) return namespace$1.exports;
  5164. hasRequiredNamespace$1 = 1;
  5165. (function (module, exports) {
  5166. exports.__esModule = true;
  5167. exports["default"] = void 0;
  5168. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5169. var _util = /*@__PURE__*/ requireUtil$2();
  5170. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5171. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5172. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  5173. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  5174. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  5175. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  5176. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5177. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5178. exports["default"] = /*#__PURE__*/function (_Node) {
  5179. _inheritsLoose(Namespace, _Node);
  5180. function Namespace() {
  5181. return _Node.apply(this, arguments) || this;
  5182. }
  5183. var _proto = Namespace.prototype;
  5184. _proto.qualifiedName = function qualifiedName(value) {
  5185. if (this.namespace) {
  5186. return this.namespaceString + "|" + value;
  5187. } else {
  5188. return value;
  5189. }
  5190. };
  5191. _proto.valueToString = function valueToString() {
  5192. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5193. };
  5194. _createClass(Namespace, [{
  5195. key: "namespace",
  5196. get: function get() {
  5197. return this._namespace;
  5198. },
  5199. set: function set(namespace) {
  5200. if (namespace === true || namespace === "*" || namespace === "&") {
  5201. this._namespace = namespace;
  5202. if (this.raws) {
  5203. delete this.raws.namespace;
  5204. }
  5205. return;
  5206. }
  5207. var escaped = (0, _cssesc["default"])(namespace, {
  5208. isIdentifier: true
  5209. });
  5210. this._namespace = namespace;
  5211. if (escaped !== namespace) {
  5212. (0, _util.ensureObject)(this, "raws");
  5213. this.raws.namespace = escaped;
  5214. } else if (this.raws) {
  5215. delete this.raws.namespace;
  5216. }
  5217. }
  5218. }, {
  5219. key: "ns",
  5220. get: function get() {
  5221. return this._namespace;
  5222. },
  5223. set: function set(namespace) {
  5224. this.namespace = namespace;
  5225. }
  5226. }, {
  5227. key: "namespaceString",
  5228. get: function get() {
  5229. if (this.namespace) {
  5230. var ns = this.stringifyProperty("namespace");
  5231. if (ns === true) {
  5232. return '';
  5233. } else {
  5234. return ns;
  5235. }
  5236. } else {
  5237. return '';
  5238. }
  5239. }
  5240. }]);
  5241. return Namespace;
  5242. }(_node["default"]);
  5243. module.exports = exports.default;
  5244. } (namespace$1, namespace$1.exports));
  5245. return namespace$1.exports;
  5246. }
  5247. var hasRequiredTag$1;
  5248. function requireTag$1 () {
  5249. if (hasRequiredTag$1) return tag$1.exports;
  5250. hasRequiredTag$1 = 1;
  5251. (function (module, exports) {
  5252. exports.__esModule = true;
  5253. exports["default"] = void 0;
  5254. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5255. var _types = /*@__PURE__*/ requireTypes$1();
  5256. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5257. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5258. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5259. exports["default"] = /*#__PURE__*/function (_Namespace) {
  5260. _inheritsLoose(Tag, _Namespace);
  5261. function Tag(opts) {
  5262. var _this;
  5263. _this = _Namespace.call(this, opts) || this;
  5264. _this.type = _types.TAG;
  5265. return _this;
  5266. }
  5267. return Tag;
  5268. }(_namespace["default"]);
  5269. module.exports = exports.default;
  5270. } (tag$1, tag$1.exports));
  5271. return tag$1.exports;
  5272. }
  5273. var string$1 = {exports: {}};
  5274. var hasRequiredString$1;
  5275. function requireString$1 () {
  5276. if (hasRequiredString$1) return string$1.exports;
  5277. hasRequiredString$1 = 1;
  5278. (function (module, exports) {
  5279. exports.__esModule = true;
  5280. exports["default"] = void 0;
  5281. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5282. var _types = /*@__PURE__*/ requireTypes$1();
  5283. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5284. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5285. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5286. exports["default"] = /*#__PURE__*/function (_Node) {
  5287. _inheritsLoose(String, _Node);
  5288. function String(opts) {
  5289. var _this;
  5290. _this = _Node.call(this, opts) || this;
  5291. _this.type = _types.STRING;
  5292. return _this;
  5293. }
  5294. return String;
  5295. }(_node["default"]);
  5296. module.exports = exports.default;
  5297. } (string$1, string$1.exports));
  5298. return string$1.exports;
  5299. }
  5300. var pseudo$1 = {exports: {}};
  5301. var hasRequiredPseudo$1;
  5302. function requirePseudo$1 () {
  5303. if (hasRequiredPseudo$1) return pseudo$1.exports;
  5304. hasRequiredPseudo$1 = 1;
  5305. (function (module, exports) {
  5306. exports.__esModule = true;
  5307. exports["default"] = void 0;
  5308. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  5309. var _types = /*@__PURE__*/ requireTypes$1();
  5310. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5311. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5312. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5313. exports["default"] = /*#__PURE__*/function (_Container) {
  5314. _inheritsLoose(Pseudo, _Container);
  5315. function Pseudo(opts) {
  5316. var _this;
  5317. _this = _Container.call(this, opts) || this;
  5318. _this.type = _types.PSEUDO;
  5319. return _this;
  5320. }
  5321. var _proto = Pseudo.prototype;
  5322. _proto._stringify = function _stringify(options, depth, max) {
  5323. if (depth >= max) {
  5324. throw new Error("Cannot serialize selector: nesting depth exceeds the maximum of " + max + ".");
  5325. }
  5326. var params = this.length ? '(' + this.map(function (child) {
  5327. return child._stringify(options, depth + 1, max);
  5328. }).join(',') + ')' : '';
  5329. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5330. };
  5331. return Pseudo;
  5332. }(_container["default"]);
  5333. module.exports = exports.default;
  5334. } (pseudo$1, pseudo$1.exports));
  5335. return pseudo$1.exports;
  5336. }
  5337. var attribute$1 = {};
  5338. var node$1;
  5339. var hasRequiredNode$1;
  5340. function requireNode$1 () {
  5341. if (hasRequiredNode$1) return node$1;
  5342. hasRequiredNode$1 = 1;
  5343. /**
  5344. * For Node.js, simply re-export the core `util.deprecate` function.
  5345. */
  5346. node$1 = require$$2.deprecate;
  5347. return node$1;
  5348. }
  5349. var hasRequiredAttribute$1;
  5350. function requireAttribute$1 () {
  5351. if (hasRequiredAttribute$1) return attribute$1;
  5352. hasRequiredAttribute$1 = 1;
  5353. (function (exports) {
  5354. exports.__esModule = true;
  5355. exports["default"] = void 0;
  5356. exports.unescapeValue = unescapeValue;
  5357. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5358. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  5359. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5360. var _types = /*@__PURE__*/ requireTypes$1();
  5361. var _CSSESC_QUOTE_OPTIONS;
  5362. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5363. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  5364. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  5365. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  5366. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  5367. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5368. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5369. var deprecate = /*@__PURE__*/ requireNode$1();
  5370. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5371. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5372. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5373. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5374. function unescapeValue(value) {
  5375. var deprecatedUsage = false;
  5376. var quoteMark = null;
  5377. var unescaped = value;
  5378. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5379. if (m) {
  5380. quoteMark = m[1];
  5381. unescaped = m[2];
  5382. }
  5383. unescaped = (0, _unesc["default"])(unescaped);
  5384. if (unescaped !== value) {
  5385. deprecatedUsage = true;
  5386. }
  5387. return {
  5388. deprecatedUsage: deprecatedUsage,
  5389. unescaped: unescaped,
  5390. quoteMark: quoteMark
  5391. };
  5392. }
  5393. function handleDeprecatedContructorOpts(opts) {
  5394. if (opts.quoteMark !== undefined) {
  5395. return opts;
  5396. }
  5397. if (opts.value === undefined) {
  5398. return opts;
  5399. }
  5400. warnOfDeprecatedConstructor();
  5401. var _unescapeValue = unescapeValue(opts.value),
  5402. quoteMark = _unescapeValue.quoteMark,
  5403. unescaped = _unescapeValue.unescaped;
  5404. if (!opts.raws) {
  5405. opts.raws = {};
  5406. }
  5407. if (opts.raws.value === undefined) {
  5408. opts.raws.value = opts.value;
  5409. }
  5410. opts.value = unescaped;
  5411. opts.quoteMark = quoteMark;
  5412. return opts;
  5413. }
  5414. var Attribute = exports["default"] = /*#__PURE__*/function (_Namespace) {
  5415. _inheritsLoose(Attribute, _Namespace);
  5416. function Attribute(opts) {
  5417. var _this;
  5418. if (opts === void 0) {
  5419. opts = {};
  5420. }
  5421. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5422. _this.type = _types.ATTRIBUTE;
  5423. _this.raws = _this.raws || {};
  5424. Object.defineProperty(_this.raws, 'unquoted', {
  5425. get: deprecate(function () {
  5426. return _this.value;
  5427. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5428. set: deprecate(function () {
  5429. return _this.value;
  5430. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5431. });
  5432. _this._constructed = true;
  5433. return _this;
  5434. }
  5435. /**
  5436. * Returns the Attribute's value quoted such that it would be legal to use
  5437. * in the value of a css file. The original value's quotation setting
  5438. * used for stringification is left unchanged. See `setValue(value, options)`
  5439. * if you want to control the quote settings of a new value for the attribute.
  5440. *
  5441. * You can also change the quotation used for the current value by setting quoteMark.
  5442. *
  5443. * Options:
  5444. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5445. * option is not set, the original value for quoteMark will be used. If
  5446. * indeterminate, a double quote is used. The legal values are:
  5447. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5448. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5449. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5450. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5451. * over the quoteMark option value.
  5452. * * smart {boolean} - if true, will select a quote mark based on the value
  5453. * and the other options specified here. See the `smartQuoteMark()`
  5454. * method.
  5455. **/
  5456. var _proto = Attribute.prototype;
  5457. _proto.getQuotedValue = function getQuotedValue(options) {
  5458. if (options === void 0) {
  5459. options = {};
  5460. }
  5461. var quoteMark = this._determineQuoteMark(options);
  5462. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5463. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5464. return escaped;
  5465. };
  5466. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5467. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5468. }
  5469. /**
  5470. * Set the unescaped value with the specified quotation options. The value
  5471. * provided must not include any wrapping quote marks -- those quotes will
  5472. * be interpreted as part of the value and escaped accordingly.
  5473. */;
  5474. _proto.setValue = function setValue(value, options) {
  5475. if (options === void 0) {
  5476. options = {};
  5477. }
  5478. this._value = value;
  5479. this._quoteMark = this._determineQuoteMark(options);
  5480. this._syncRawValue();
  5481. }
  5482. /**
  5483. * Intelligently select a quoteMark value based on the value's contents. If
  5484. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5485. * mark will be picked that minimizes the number of escapes.
  5486. *
  5487. * If there's no clear winner, the quote mark from these options is used,
  5488. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5489. * true). If the quoteMark is unspecified, a double quote is used.
  5490. *
  5491. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5492. * from the quoteValue method.
  5493. */;
  5494. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5495. var v = this.value;
  5496. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5497. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5498. if (numSingleQuotes + numDoubleQuotes === 0) {
  5499. var escaped = (0, _cssesc["default"])(v, {
  5500. isIdentifier: true
  5501. });
  5502. if (escaped === v) {
  5503. return Attribute.NO_QUOTE;
  5504. } else {
  5505. var pref = this.preferredQuoteMark(options);
  5506. if (pref === Attribute.NO_QUOTE) {
  5507. // pick a quote mark that isn't none and see if it's smaller
  5508. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5509. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5510. var quoteValue = (0, _cssesc["default"])(v, opts);
  5511. if (quoteValue.length < escaped.length) {
  5512. return quote;
  5513. }
  5514. }
  5515. return pref;
  5516. }
  5517. } else if (numDoubleQuotes === numSingleQuotes) {
  5518. return this.preferredQuoteMark(options);
  5519. } else if (numDoubleQuotes < numSingleQuotes) {
  5520. return Attribute.DOUBLE_QUOTE;
  5521. } else {
  5522. return Attribute.SINGLE_QUOTE;
  5523. }
  5524. }
  5525. /**
  5526. * Selects the preferred quote mark based on the options and the current quote mark value.
  5527. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5528. * instead.
  5529. */;
  5530. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5531. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5532. if (quoteMark === undefined) {
  5533. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5534. }
  5535. if (quoteMark === undefined) {
  5536. quoteMark = Attribute.DOUBLE_QUOTE;
  5537. }
  5538. return quoteMark;
  5539. };
  5540. _proto._syncRawValue = function _syncRawValue() {
  5541. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5542. if (rawValue === this._value) {
  5543. if (this.raws) {
  5544. delete this.raws.value;
  5545. }
  5546. } else {
  5547. this.raws.value = rawValue;
  5548. }
  5549. };
  5550. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5551. if (this._constructed) {
  5552. var escaped = (0, _cssesc["default"])(value, {
  5553. isIdentifier: true
  5554. });
  5555. if (escaped !== value) {
  5556. this.raws[prop] = escaped;
  5557. } else {
  5558. delete this.raws[prop];
  5559. }
  5560. }
  5561. };
  5562. _proto._spacesFor = function _spacesFor(name) {
  5563. var attrSpaces = {
  5564. before: '',
  5565. after: ''
  5566. };
  5567. var spaces = this.spaces[name] || {};
  5568. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5569. return Object.assign(attrSpaces, spaces, rawSpaces);
  5570. };
  5571. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5572. if (spaceName === void 0) {
  5573. spaceName = name;
  5574. }
  5575. if (concat === void 0) {
  5576. concat = defaultAttrConcat;
  5577. }
  5578. var attrSpaces = this._spacesFor(spaceName);
  5579. return concat(this.stringifyProperty(name), attrSpaces);
  5580. }
  5581. /**
  5582. * returns the offset of the attribute part specified relative to the
  5583. * start of the node of the output string.
  5584. *
  5585. * * "ns" - alias for "namespace"
  5586. * * "namespace" - the namespace if it exists.
  5587. * * "attribute" - the attribute name
  5588. * * "attributeNS" - the start of the attribute or its namespace
  5589. * * "operator" - the match operator of the attribute
  5590. * * "value" - The value (string or identifier)
  5591. * * "insensitive" - the case insensitivity flag;
  5592. * @param part One of the possible values inside an attribute.
  5593. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5594. */;
  5595. _proto.offsetOf = function offsetOf(name) {
  5596. var count = 1;
  5597. var attributeSpaces = this._spacesFor("attribute");
  5598. count += attributeSpaces.before.length;
  5599. if (name === "namespace" || name === "ns") {
  5600. return this.namespace ? count : -1;
  5601. }
  5602. if (name === "attributeNS") {
  5603. return count;
  5604. }
  5605. count += this.namespaceString.length;
  5606. if (this.namespace) {
  5607. count += 1;
  5608. }
  5609. if (name === "attribute") {
  5610. return count;
  5611. }
  5612. count += this.stringifyProperty("attribute").length;
  5613. count += attributeSpaces.after.length;
  5614. var operatorSpaces = this._spacesFor("operator");
  5615. count += operatorSpaces.before.length;
  5616. var operator = this.stringifyProperty("operator");
  5617. if (name === "operator") {
  5618. return operator ? count : -1;
  5619. }
  5620. count += operator.length;
  5621. count += operatorSpaces.after.length;
  5622. var valueSpaces = this._spacesFor("value");
  5623. count += valueSpaces.before.length;
  5624. var value = this.stringifyProperty("value");
  5625. if (name === "value") {
  5626. return value ? count : -1;
  5627. }
  5628. count += value.length;
  5629. count += valueSpaces.after.length;
  5630. var insensitiveSpaces = this._spacesFor("insensitive");
  5631. count += insensitiveSpaces.before.length;
  5632. if (name === "insensitive") {
  5633. return this.insensitive ? count : -1;
  5634. }
  5635. return -1;
  5636. };
  5637. _proto.toString = function toString() {
  5638. var _this2 = this;
  5639. var selector = [this.rawSpaceBefore, '['];
  5640. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5641. if (this.operator && (this.value || this.value === '')) {
  5642. selector.push(this._stringFor('operator'));
  5643. selector.push(this._stringFor('value'));
  5644. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5645. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5646. attrSpaces.before = " ";
  5647. }
  5648. return defaultAttrConcat(attrValue, attrSpaces);
  5649. }));
  5650. }
  5651. selector.push(']');
  5652. selector.push(this.rawSpaceAfter);
  5653. return selector.join('');
  5654. };
  5655. _createClass(Attribute, [{
  5656. key: "quoted",
  5657. get: function get() {
  5658. var qm = this.quoteMark;
  5659. return qm === "'" || qm === '"';
  5660. },
  5661. set: function set(value) {
  5662. warnOfDeprecatedQuotedAssignment();
  5663. }
  5664. /**
  5665. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5666. * returns `null` if the value is not quoted.
  5667. * returns `undefined` if the quotation state is unknown (this can happen when
  5668. * the attribute is constructed without specifying a quote mark.)
  5669. */
  5670. }, {
  5671. key: "quoteMark",
  5672. get: function get() {
  5673. return this._quoteMark;
  5674. }
  5675. /**
  5676. * Set the quote mark to be used by this attribute's value.
  5677. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5678. * value is updated accordingly.
  5679. *
  5680. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5681. */,
  5682. set: function set(quoteMark) {
  5683. if (!this._constructed) {
  5684. this._quoteMark = quoteMark;
  5685. return;
  5686. }
  5687. if (this._quoteMark !== quoteMark) {
  5688. this._quoteMark = quoteMark;
  5689. this._syncRawValue();
  5690. }
  5691. }
  5692. }, {
  5693. key: "qualifiedAttribute",
  5694. get: function get() {
  5695. return this.qualifiedName(this.raws.attribute || this.attribute);
  5696. }
  5697. }, {
  5698. key: "insensitiveFlag",
  5699. get: function get() {
  5700. return this.insensitive ? 'i' : '';
  5701. }
  5702. }, {
  5703. key: "value",
  5704. get: function get() {
  5705. return this._value;
  5706. },
  5707. set:
  5708. /**
  5709. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5710. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5711. * is unescaped during parsing and any quote marks are removed.
  5712. *
  5713. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5714. * a deprecation warning is raised when the new value contains any characters that would
  5715. * require escaping (including if it contains wrapped quotes).
  5716. *
  5717. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5718. * how the new value is quoted.
  5719. */
  5720. function set(v) {
  5721. if (this._constructed) {
  5722. var _unescapeValue2 = unescapeValue(v),
  5723. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5724. unescaped = _unescapeValue2.unescaped,
  5725. quoteMark = _unescapeValue2.quoteMark;
  5726. if (deprecatedUsage) {
  5727. warnOfDeprecatedValueAssignment();
  5728. }
  5729. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5730. return;
  5731. }
  5732. this._value = unescaped;
  5733. this._quoteMark = quoteMark;
  5734. this._syncRawValue();
  5735. } else {
  5736. this._value = v;
  5737. }
  5738. }
  5739. }, {
  5740. key: "insensitive",
  5741. get: function get() {
  5742. return this._insensitive;
  5743. }
  5744. /**
  5745. * Set the case insensitive flag.
  5746. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5747. * of the attribute is updated accordingly.
  5748. *
  5749. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5750. */,
  5751. set: function set(insensitive) {
  5752. if (!insensitive) {
  5753. this._insensitive = false;
  5754. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5755. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5756. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5757. this.raws.insensitiveFlag = undefined;
  5758. }
  5759. }
  5760. this._insensitive = insensitive;
  5761. }
  5762. }, {
  5763. key: "attribute",
  5764. get: function get() {
  5765. return this._attribute;
  5766. },
  5767. set: function set(name) {
  5768. this._handleEscapes("attribute", name);
  5769. this._attribute = name;
  5770. }
  5771. }]);
  5772. return Attribute;
  5773. }(_namespace["default"]);
  5774. Attribute.NO_QUOTE = null;
  5775. Attribute.SINGLE_QUOTE = "'";
  5776. Attribute.DOUBLE_QUOTE = '"';
  5777. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5778. "'": {
  5779. quotes: 'single',
  5780. wrap: true
  5781. },
  5782. '"': {
  5783. quotes: 'double',
  5784. wrap: true
  5785. }
  5786. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5787. isIdentifier: true
  5788. }, _CSSESC_QUOTE_OPTIONS);
  5789. function defaultAttrConcat(attrValue, attrSpaces) {
  5790. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5791. }
  5792. } (attribute$1));
  5793. return attribute$1;
  5794. }
  5795. var universal$1 = {exports: {}};
  5796. var hasRequiredUniversal$1;
  5797. function requireUniversal$1 () {
  5798. if (hasRequiredUniversal$1) return universal$1.exports;
  5799. hasRequiredUniversal$1 = 1;
  5800. (function (module, exports) {
  5801. exports.__esModule = true;
  5802. exports["default"] = void 0;
  5803. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5804. var _types = /*@__PURE__*/ requireTypes$1();
  5805. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5806. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5807. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5808. exports["default"] = /*#__PURE__*/function (_Namespace) {
  5809. _inheritsLoose(Universal, _Namespace);
  5810. function Universal(opts) {
  5811. var _this;
  5812. _this = _Namespace.call(this, opts) || this;
  5813. _this.type = _types.UNIVERSAL;
  5814. _this.value = '*';
  5815. return _this;
  5816. }
  5817. return Universal;
  5818. }(_namespace["default"]);
  5819. module.exports = exports.default;
  5820. } (universal$1, universal$1.exports));
  5821. return universal$1.exports;
  5822. }
  5823. var combinator$1 = {exports: {}};
  5824. var hasRequiredCombinator$1;
  5825. function requireCombinator$1 () {
  5826. if (hasRequiredCombinator$1) return combinator$1.exports;
  5827. hasRequiredCombinator$1 = 1;
  5828. (function (module, exports) {
  5829. exports.__esModule = true;
  5830. exports["default"] = void 0;
  5831. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5832. var _types = /*@__PURE__*/ requireTypes$1();
  5833. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5834. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5835. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5836. exports["default"] = /*#__PURE__*/function (_Node) {
  5837. _inheritsLoose(Combinator, _Node);
  5838. function Combinator(opts) {
  5839. var _this;
  5840. _this = _Node.call(this, opts) || this;
  5841. _this.type = _types.COMBINATOR;
  5842. return _this;
  5843. }
  5844. return Combinator;
  5845. }(_node["default"]);
  5846. module.exports = exports.default;
  5847. } (combinator$1, combinator$1.exports));
  5848. return combinator$1.exports;
  5849. }
  5850. var nesting$1 = {exports: {}};
  5851. var hasRequiredNesting$1;
  5852. function requireNesting$1 () {
  5853. if (hasRequiredNesting$1) return nesting$1.exports;
  5854. hasRequiredNesting$1 = 1;
  5855. (function (module, exports) {
  5856. exports.__esModule = true;
  5857. exports["default"] = void 0;
  5858. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5859. var _types = /*@__PURE__*/ requireTypes$1();
  5860. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  5861. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  5862. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  5863. exports["default"] = /*#__PURE__*/function (_Node) {
  5864. _inheritsLoose(Nesting, _Node);
  5865. function Nesting(opts) {
  5866. var _this;
  5867. _this = _Node.call(this, opts) || this;
  5868. _this.type = _types.NESTING;
  5869. _this.value = '&';
  5870. return _this;
  5871. }
  5872. return Nesting;
  5873. }(_node["default"]);
  5874. module.exports = exports.default;
  5875. } (nesting$1, nesting$1.exports));
  5876. return nesting$1.exports;
  5877. }
  5878. var sortAscending$1 = {exports: {}};
  5879. var hasRequiredSortAscending$1;
  5880. function requireSortAscending$1 () {
  5881. if (hasRequiredSortAscending$1) return sortAscending$1.exports;
  5882. hasRequiredSortAscending$1 = 1;
  5883. (function (module, exports) {
  5884. exports.__esModule = true;
  5885. exports["default"] = sortAscending;
  5886. function sortAscending(list) {
  5887. return list.sort(function (a, b) {
  5888. return a - b;
  5889. });
  5890. }
  5891. module.exports = exports.default;
  5892. } (sortAscending$1, sortAscending$1.exports));
  5893. return sortAscending$1.exports;
  5894. }
  5895. var tokenize$1 = {};
  5896. var tokenTypes$1 = {};
  5897. var hasRequiredTokenTypes$1;
  5898. function requireTokenTypes$1 () {
  5899. if (hasRequiredTokenTypes$1) return tokenTypes$1;
  5900. hasRequiredTokenTypes$1 = 1;
  5901. tokenTypes$1.__esModule = true;
  5902. tokenTypes$1.word = tokenTypes$1.tilde = tokenTypes$1.tab = tokenTypes$1.str = tokenTypes$1.space = tokenTypes$1.slash = tokenTypes$1.singleQuote = tokenTypes$1.semicolon = tokenTypes$1.plus = tokenTypes$1.pipe = tokenTypes$1.openSquare = tokenTypes$1.openParenthesis = tokenTypes$1.newline = tokenTypes$1.greaterThan = tokenTypes$1.feed = tokenTypes$1.equals = tokenTypes$1.doubleQuote = tokenTypes$1.dollar = tokenTypes$1.cr = tokenTypes$1.comment = tokenTypes$1.comma = tokenTypes$1.combinator = tokenTypes$1.colon = tokenTypes$1.closeSquare = tokenTypes$1.closeParenthesis = tokenTypes$1.caret = tokenTypes$1.bang = tokenTypes$1.backslash = tokenTypes$1.at = tokenTypes$1.asterisk = tokenTypes$1.ampersand = void 0;
  5903. tokenTypes$1.ampersand = 38; // `&`.charCodeAt(0);
  5904. tokenTypes$1.asterisk = 42; // `*`.charCodeAt(0);
  5905. tokenTypes$1.at = 64; // `@`.charCodeAt(0);
  5906. tokenTypes$1.comma = 44; // `,`.charCodeAt(0);
  5907. tokenTypes$1.colon = 58; // `:`.charCodeAt(0);
  5908. tokenTypes$1.semicolon = 59; // `;`.charCodeAt(0);
  5909. tokenTypes$1.openParenthesis = 40; // `(`.charCodeAt(0);
  5910. tokenTypes$1.closeParenthesis = 41; // `)`.charCodeAt(0);
  5911. tokenTypes$1.openSquare = 91; // `[`.charCodeAt(0);
  5912. tokenTypes$1.closeSquare = 93; // `]`.charCodeAt(0);
  5913. tokenTypes$1.dollar = 36; // `$`.charCodeAt(0);
  5914. tokenTypes$1.tilde = 126; // `~`.charCodeAt(0);
  5915. tokenTypes$1.caret = 94; // `^`.charCodeAt(0);
  5916. tokenTypes$1.plus = 43; // `+`.charCodeAt(0);
  5917. tokenTypes$1.equals = 61; // `=`.charCodeAt(0);
  5918. tokenTypes$1.pipe = 124; // `|`.charCodeAt(0);
  5919. tokenTypes$1.greaterThan = 62; // `>`.charCodeAt(0);
  5920. tokenTypes$1.space = 32; // ` `.charCodeAt(0);
  5921. var singleQuote = tokenTypes$1.singleQuote = 39; // `'`.charCodeAt(0);
  5922. tokenTypes$1.doubleQuote = 34; // `"`.charCodeAt(0);
  5923. tokenTypes$1.slash = 47; // `/`.charCodeAt(0);
  5924. tokenTypes$1.bang = 33; // `!`.charCodeAt(0);
  5925. tokenTypes$1.backslash = 92; // '\\'.charCodeAt(0);
  5926. tokenTypes$1.cr = 13; // '\r'.charCodeAt(0);
  5927. tokenTypes$1.feed = 12; // '\f'.charCodeAt(0);
  5928. tokenTypes$1.newline = 10; // '\n'.charCodeAt(0);
  5929. tokenTypes$1.tab = 9; // '\t'.charCodeAt(0);
  5930. // Expose aliases primarily for readability.
  5931. tokenTypes$1.str = singleQuote;
  5932. // No good single character representation!
  5933. tokenTypes$1.comment = -1;
  5934. tokenTypes$1.word = -2;
  5935. tokenTypes$1.combinator = -3;
  5936. return tokenTypes$1;
  5937. }
  5938. var hasRequiredTokenize$1;
  5939. function requireTokenize$1 () {
  5940. if (hasRequiredTokenize$1) return tokenize$1;
  5941. hasRequiredTokenize$1 = 1;
  5942. (function (exports) {
  5943. exports.__esModule = true;
  5944. exports.FIELDS = void 0;
  5945. exports["default"] = tokenize;
  5946. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  5947. var _unescapable, _wordDelimiters;
  5948. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  5949. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5950. var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
  5951. var hex = {};
  5952. var hexChars = "0123456789abcdefABCDEF";
  5953. for (var i = 0; i < hexChars.length; i++) {
  5954. hex[hexChars.charCodeAt(i)] = true;
  5955. }
  5956. /**
  5957. * Returns the last index of the bar css word
  5958. * @param {string} css The string in which the word begins
  5959. * @param {number} start The index into the string where word's first letter occurs
  5960. */
  5961. function consumeWord(css, start) {
  5962. var next = start;
  5963. var code;
  5964. do {
  5965. code = css.charCodeAt(next);
  5966. if (wordDelimiters[code]) {
  5967. return next - 1;
  5968. } else if (code === t.backslash) {
  5969. next = consumeEscape(css, next) + 1;
  5970. } else {
  5971. // All other characters are part of the word
  5972. next++;
  5973. }
  5974. } while (next < css.length);
  5975. return next - 1;
  5976. }
  5977. /**
  5978. * Returns the last index of the escape sequence
  5979. * @param {string} css The string in which the sequence begins
  5980. * @param {number} start The index into the string where escape character (`\`) occurs.
  5981. */
  5982. function consumeEscape(css, start) {
  5983. var next = start;
  5984. var code = css.charCodeAt(next + 1);
  5985. if (unescapable[code]) ; else if (hex[code]) {
  5986. var hexDigits = 0;
  5987. // consume up to 6 hex chars
  5988. do {
  5989. next++;
  5990. hexDigits++;
  5991. code = css.charCodeAt(next + 1);
  5992. } while (hex[code] && hexDigits < 6);
  5993. // if fewer than 6 hex chars, a trailing space ends the escape
  5994. if (hexDigits < 6 && code === t.space) {
  5995. next++;
  5996. }
  5997. } else {
  5998. // the next char is part of the current word
  5999. next++;
  6000. }
  6001. return next;
  6002. }
  6003. exports.FIELDS = {
  6004. TYPE: 0,
  6005. START_LINE: 1,
  6006. START_COL: 2,
  6007. END_LINE: 3,
  6008. END_COL: 4,
  6009. START_POS: 5,
  6010. END_POS: 6
  6011. };
  6012. function tokenize(input) {
  6013. var tokens = [];
  6014. var css = input.css.valueOf();
  6015. var _css = css,
  6016. length = _css.length;
  6017. var offset = -1;
  6018. var line = 1;
  6019. var start = 0;
  6020. var end = 0;
  6021. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  6022. function unclosed(what, fix) {
  6023. if (input.safe) {
  6024. // fyi: this is never set to true.
  6025. css += fix;
  6026. next = css.length - 1;
  6027. } else {
  6028. throw input.error('Unclosed ' + what, line, start - offset, start);
  6029. }
  6030. }
  6031. while (start < length) {
  6032. code = css.charCodeAt(start);
  6033. if (code === t.newline) {
  6034. offset = start;
  6035. line += 1;
  6036. }
  6037. switch (code) {
  6038. case t.space:
  6039. case t.tab:
  6040. case t.newline:
  6041. case t.cr:
  6042. case t.feed:
  6043. next = start;
  6044. do {
  6045. next += 1;
  6046. code = css.charCodeAt(next);
  6047. if (code === t.newline) {
  6048. offset = next;
  6049. line += 1;
  6050. }
  6051. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  6052. tokenType = t.space;
  6053. endLine = line;
  6054. endColumn = next - offset - 1;
  6055. end = next;
  6056. break;
  6057. case t.plus:
  6058. case t.greaterThan:
  6059. case t.tilde:
  6060. case t.pipe:
  6061. next = start;
  6062. do {
  6063. next += 1;
  6064. code = css.charCodeAt(next);
  6065. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  6066. tokenType = t.combinator;
  6067. endLine = line;
  6068. endColumn = start - offset;
  6069. end = next;
  6070. break;
  6071. // Consume these characters as single tokens.
  6072. case t.asterisk:
  6073. case t.ampersand:
  6074. case t.bang:
  6075. case t.comma:
  6076. case t.equals:
  6077. case t.dollar:
  6078. case t.caret:
  6079. case t.openSquare:
  6080. case t.closeSquare:
  6081. case t.colon:
  6082. case t.semicolon:
  6083. case t.openParenthesis:
  6084. case t.closeParenthesis:
  6085. next = start;
  6086. tokenType = code;
  6087. endLine = line;
  6088. endColumn = start - offset;
  6089. end = next + 1;
  6090. break;
  6091. case t.singleQuote:
  6092. case t.doubleQuote:
  6093. quote = code === t.singleQuote ? "'" : '"';
  6094. next = start;
  6095. do {
  6096. escaped = false;
  6097. next = css.indexOf(quote, next + 1);
  6098. if (next === -1) {
  6099. unclosed('quote', quote);
  6100. }
  6101. escapePos = next;
  6102. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  6103. escapePos -= 1;
  6104. escaped = !escaped;
  6105. }
  6106. } while (escaped);
  6107. tokenType = t.str;
  6108. endLine = line;
  6109. endColumn = start - offset;
  6110. end = next + 1;
  6111. break;
  6112. default:
  6113. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  6114. next = css.indexOf('*/', start + 2) + 1;
  6115. if (next === 0) {
  6116. unclosed('comment', '*/');
  6117. }
  6118. content = css.slice(start, next + 1);
  6119. lines = content.split('\n');
  6120. last = lines.length - 1;
  6121. if (last > 0) {
  6122. nextLine = line + last;
  6123. nextOffset = next - lines[last].length;
  6124. } else {
  6125. nextLine = line;
  6126. nextOffset = offset;
  6127. }
  6128. tokenType = t.comment;
  6129. line = nextLine;
  6130. endLine = nextLine;
  6131. endColumn = next - nextOffset;
  6132. } else if (code === t.slash) {
  6133. next = start;
  6134. tokenType = code;
  6135. endLine = line;
  6136. endColumn = start - offset;
  6137. end = next + 1;
  6138. } else {
  6139. next = consumeWord(css, start);
  6140. tokenType = t.word;
  6141. endLine = line;
  6142. endColumn = next - offset;
  6143. }
  6144. end = next + 1;
  6145. break;
  6146. }
  6147. // Ensure that the token structure remains consistent
  6148. tokens.push([tokenType,
  6149. // [0] Token type
  6150. line,
  6151. // [1] Starting line
  6152. start - offset,
  6153. // [2] Starting column
  6154. endLine,
  6155. // [3] Ending line
  6156. endColumn,
  6157. // [4] Ending column
  6158. start,
  6159. // [5] Start position / Source index
  6160. end // [6] End position
  6161. ]);
  6162. // Reset offset for the next token
  6163. if (nextOffset) {
  6164. offset = nextOffset;
  6165. nextOffset = null;
  6166. }
  6167. start = end;
  6168. }
  6169. return tokens;
  6170. }
  6171. } (tokenize$1));
  6172. return tokenize$1;
  6173. }
  6174. var hasRequiredParser$2;
  6175. function requireParser$2 () {
  6176. if (hasRequiredParser$2) return parser$1.exports;
  6177. hasRequiredParser$2 = 1;
  6178. (function (module, exports) {
  6179. exports.__esModule = true;
  6180. exports["default"] = void 0;
  6181. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  6182. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  6183. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  6184. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  6185. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  6186. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  6187. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  6188. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  6189. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute$1());
  6190. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  6191. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  6192. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  6193. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending$1());
  6194. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize$1());
  6195. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  6196. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  6197. var _util = /*@__PURE__*/ requireUtil$2();
  6198. var _WHITESPACE_TOKENS, _Object$assign;
  6199. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  6200. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  6201. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  6202. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  6203. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  6204. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  6205. var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  6206. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6207. function tokenStart(token) {
  6208. return {
  6209. line: token[_tokenize.FIELDS.START_LINE],
  6210. column: token[_tokenize.FIELDS.START_COL]
  6211. };
  6212. }
  6213. function tokenEnd(token) {
  6214. return {
  6215. line: token[_tokenize.FIELDS.END_LINE],
  6216. column: token[_tokenize.FIELDS.END_COL]
  6217. };
  6218. }
  6219. function getSource(startLine, startColumn, endLine, endColumn) {
  6220. return {
  6221. start: {
  6222. line: startLine,
  6223. column: startColumn
  6224. },
  6225. end: {
  6226. line: endLine,
  6227. column: endColumn
  6228. }
  6229. };
  6230. }
  6231. function getTokenSource(token) {
  6232. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6233. }
  6234. function getTokenSourceSpan(startToken, endToken) {
  6235. if (!startToken) {
  6236. return undefined;
  6237. }
  6238. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6239. }
  6240. function unescapeProp(node, prop) {
  6241. var value = node[prop];
  6242. if (typeof value !== "string") {
  6243. return;
  6244. }
  6245. if (value.indexOf("\\") !== -1) {
  6246. (0, _util.ensureObject)(node, 'raws');
  6247. node[prop] = (0, _util.unesc)(value);
  6248. if (node.raws[prop] === undefined) {
  6249. node.raws[prop] = value;
  6250. }
  6251. }
  6252. return node;
  6253. }
  6254. function indexesOf(array, item) {
  6255. var i = -1;
  6256. var indexes = [];
  6257. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6258. indexes.push(i);
  6259. }
  6260. return indexes;
  6261. }
  6262. function uniqs() {
  6263. var list = Array.prototype.concat.apply([], arguments);
  6264. return list.filter(function (item, i) {
  6265. return i === list.indexOf(item);
  6266. });
  6267. }
  6268. exports["default"] = /*#__PURE__*/function () {
  6269. function Parser(rule, options) {
  6270. if (options === void 0) {
  6271. options = {};
  6272. }
  6273. this.rule = rule;
  6274. this.options = Object.assign({
  6275. lossy: false,
  6276. safe: false
  6277. }, options);
  6278. this.position = 0;
  6279. this.nestingDepth = 0;
  6280. this.maxNestingDepth = (0, _util.resolveMaxNestingDepth)(this.options.maxNestingDepth);
  6281. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6282. this.tokens = (0, _tokenize["default"])({
  6283. css: this.css,
  6284. error: this._errorGenerator(),
  6285. safe: this.options.safe
  6286. });
  6287. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6288. this.root = new _root["default"]({
  6289. source: rootSource
  6290. });
  6291. this.root.errorGenerator = this._errorGenerator();
  6292. var selector = new _selector["default"]({
  6293. source: {
  6294. start: {
  6295. line: 1,
  6296. column: 1
  6297. }
  6298. },
  6299. sourceIndex: 0
  6300. });
  6301. this.root.append(selector);
  6302. this.current = selector;
  6303. this.loop();
  6304. }
  6305. var _proto = Parser.prototype;
  6306. _proto._errorGenerator = function _errorGenerator() {
  6307. var _this = this;
  6308. return function (message, errorOptions) {
  6309. if (typeof _this.rule === 'string') {
  6310. return new Error(message);
  6311. }
  6312. return _this.rule.error(message, errorOptions);
  6313. };
  6314. };
  6315. _proto.attribute = function attribute() {
  6316. var attr = [];
  6317. var startingToken = this.currToken;
  6318. this.position++;
  6319. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6320. attr.push(this.currToken);
  6321. this.position++;
  6322. }
  6323. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6324. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6325. }
  6326. var len = attr.length;
  6327. var node = {
  6328. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6329. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6330. };
  6331. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6332. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6333. }
  6334. var pos = 0;
  6335. var spaceBefore = '';
  6336. var commentBefore = '';
  6337. var lastAdded = null;
  6338. var spaceAfterMeaningfulToken = false;
  6339. while (pos < len) {
  6340. var token = attr[pos];
  6341. var content = this.content(token);
  6342. var next = attr[pos + 1];
  6343. switch (token[_tokenize.FIELDS.TYPE]) {
  6344. case tokens.space:
  6345. // if (
  6346. // len === 1 ||
  6347. // pos === 0 && this.content(next) === '|'
  6348. // ) {
  6349. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6350. // }
  6351. spaceAfterMeaningfulToken = true;
  6352. if (this.options.lossy) {
  6353. break;
  6354. }
  6355. if (lastAdded) {
  6356. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6357. var prevContent = node.spaces[lastAdded].after || '';
  6358. node.spaces[lastAdded].after = prevContent + content;
  6359. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6360. if (existingComment) {
  6361. node.raws.spaces[lastAdded].after = existingComment + content;
  6362. }
  6363. } else {
  6364. spaceBefore = spaceBefore + content;
  6365. commentBefore = commentBefore + content;
  6366. }
  6367. break;
  6368. case tokens.asterisk:
  6369. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6370. node.operator = content;
  6371. lastAdded = 'operator';
  6372. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6373. if (spaceBefore) {
  6374. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6375. node.spaces.attribute.before = spaceBefore;
  6376. spaceBefore = '';
  6377. }
  6378. if (commentBefore) {
  6379. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6380. node.raws.spaces.attribute.before = spaceBefore;
  6381. commentBefore = '';
  6382. }
  6383. node.namespace = (node.namespace || "") + content;
  6384. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6385. if (rawValue) {
  6386. node.raws.namespace += content;
  6387. }
  6388. lastAdded = 'namespace';
  6389. }
  6390. spaceAfterMeaningfulToken = false;
  6391. break;
  6392. case tokens.dollar:
  6393. if (lastAdded === "value") {
  6394. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6395. node.value += "$";
  6396. if (oldRawValue) {
  6397. node.raws.value = oldRawValue + "$";
  6398. }
  6399. break;
  6400. }
  6401. // Falls through
  6402. case tokens.caret:
  6403. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6404. node.operator = content;
  6405. lastAdded = 'operator';
  6406. }
  6407. spaceAfterMeaningfulToken = false;
  6408. break;
  6409. case tokens.combinator:
  6410. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6411. node.operator = content;
  6412. lastAdded = 'operator';
  6413. }
  6414. if (content !== '|') {
  6415. spaceAfterMeaningfulToken = false;
  6416. break;
  6417. }
  6418. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6419. node.operator = content;
  6420. lastAdded = 'operator';
  6421. } else if (!node.namespace && !node.attribute) {
  6422. node.namespace = true;
  6423. }
  6424. spaceAfterMeaningfulToken = false;
  6425. break;
  6426. case tokens.word:
  6427. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6428. // this look-ahead probably fails with comment nodes involved.
  6429. !node.operator && !node.namespace) {
  6430. node.namespace = content;
  6431. lastAdded = 'namespace';
  6432. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6433. if (spaceBefore) {
  6434. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6435. node.spaces.attribute.before = spaceBefore;
  6436. spaceBefore = '';
  6437. }
  6438. if (commentBefore) {
  6439. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6440. node.raws.spaces.attribute.before = commentBefore;
  6441. commentBefore = '';
  6442. }
  6443. node.attribute = (node.attribute || "") + content;
  6444. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6445. if (_rawValue) {
  6446. node.raws.attribute += content;
  6447. }
  6448. lastAdded = 'attribute';
  6449. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6450. var _unescaped = (0, _util.unesc)(content);
  6451. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6452. var oldValue = node.value || '';
  6453. node.value = oldValue + _unescaped;
  6454. node.quoteMark = null;
  6455. if (_unescaped !== content || _oldRawValue) {
  6456. (0, _util.ensureObject)(node, 'raws');
  6457. node.raws.value = (_oldRawValue || oldValue) + content;
  6458. }
  6459. lastAdded = 'value';
  6460. } else {
  6461. var insensitive = content === 'i' || content === "I";
  6462. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6463. node.insensitive = insensitive;
  6464. if (!insensitive || content === "I") {
  6465. (0, _util.ensureObject)(node, 'raws');
  6466. node.raws.insensitiveFlag = content;
  6467. }
  6468. lastAdded = 'insensitive';
  6469. if (spaceBefore) {
  6470. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6471. node.spaces.insensitive.before = spaceBefore;
  6472. spaceBefore = '';
  6473. }
  6474. if (commentBefore) {
  6475. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6476. node.raws.spaces.insensitive.before = commentBefore;
  6477. commentBefore = '';
  6478. }
  6479. } else if (node.value || node.value === '') {
  6480. lastAdded = 'value';
  6481. node.value += content;
  6482. if (node.raws.value) {
  6483. node.raws.value += content;
  6484. }
  6485. }
  6486. }
  6487. spaceAfterMeaningfulToken = false;
  6488. break;
  6489. case tokens.str:
  6490. if (!node.attribute || !node.operator) {
  6491. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6492. index: token[_tokenize.FIELDS.START_POS]
  6493. });
  6494. }
  6495. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6496. unescaped = _unescapeValue.unescaped,
  6497. quoteMark = _unescapeValue.quoteMark;
  6498. node.value = unescaped;
  6499. node.quoteMark = quoteMark;
  6500. lastAdded = 'value';
  6501. (0, _util.ensureObject)(node, 'raws');
  6502. node.raws.value = content;
  6503. spaceAfterMeaningfulToken = false;
  6504. break;
  6505. case tokens.equals:
  6506. if (!node.attribute) {
  6507. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6508. }
  6509. if (node.value) {
  6510. return this.error('Unexpected "=" found; an operator was already defined.', {
  6511. index: token[_tokenize.FIELDS.START_POS]
  6512. });
  6513. }
  6514. node.operator = node.operator ? node.operator + content : content;
  6515. lastAdded = 'operator';
  6516. spaceAfterMeaningfulToken = false;
  6517. break;
  6518. case tokens.comment:
  6519. if (lastAdded) {
  6520. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6521. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6522. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6523. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6524. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6525. } else {
  6526. var lastValue = node[lastAdded] || '';
  6527. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6528. (0, _util.ensureObject)(node, 'raws');
  6529. node.raws[lastAdded] = rawLastValue + content;
  6530. }
  6531. } else {
  6532. commentBefore = commentBefore + content;
  6533. }
  6534. break;
  6535. default:
  6536. return this.error("Unexpected \"" + content + "\" found.", {
  6537. index: token[_tokenize.FIELDS.START_POS]
  6538. });
  6539. }
  6540. pos++;
  6541. }
  6542. unescapeProp(node, "attribute");
  6543. unescapeProp(node, "namespace");
  6544. this.newNode(new _attribute["default"](node));
  6545. this.position++;
  6546. }
  6547. /**
  6548. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6549. * if the token position is negative, all remaining tokens are consumed.
  6550. *
  6551. * This returns an array containing a single string node if all whitespace,
  6552. * otherwise an array of comment nodes with space before and after.
  6553. *
  6554. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6555. * a previous node's space metadata.
  6556. *
  6557. * In lossy mode, this returns only comments.
  6558. */;
  6559. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6560. if (stopPosition < 0) {
  6561. stopPosition = this.tokens.length;
  6562. }
  6563. var startPosition = this.position;
  6564. var nodes = [];
  6565. var space = "";
  6566. var lastComment = undefined;
  6567. do {
  6568. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6569. if (!this.options.lossy) {
  6570. space += this.content();
  6571. }
  6572. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6573. var spaces = {};
  6574. if (space) {
  6575. spaces.before = space;
  6576. space = "";
  6577. }
  6578. lastComment = new _comment["default"]({
  6579. value: this.content(),
  6580. source: getTokenSource(this.currToken),
  6581. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6582. spaces: spaces
  6583. });
  6584. nodes.push(lastComment);
  6585. }
  6586. } while (++this.position < stopPosition);
  6587. if (space) {
  6588. if (lastComment) {
  6589. lastComment.spaces.after = space;
  6590. } else if (!this.options.lossy) {
  6591. var firstToken = this.tokens[startPosition];
  6592. var lastToken = this.tokens[this.position - 1];
  6593. nodes.push(new _string["default"]({
  6594. value: '',
  6595. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6596. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6597. spaces: {
  6598. before: space,
  6599. after: ''
  6600. }
  6601. }));
  6602. }
  6603. }
  6604. return nodes;
  6605. }
  6606. /**
  6607. *
  6608. * @param {*} nodes
  6609. */;
  6610. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6611. var _this2 = this;
  6612. if (requiredSpace === void 0) {
  6613. requiredSpace = false;
  6614. }
  6615. var space = "";
  6616. var rawSpace = "";
  6617. nodes.forEach(function (n) {
  6618. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6619. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6620. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6621. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6622. });
  6623. if (rawSpace === space) {
  6624. rawSpace = undefined;
  6625. }
  6626. var result = {
  6627. space: space,
  6628. rawSpace: rawSpace
  6629. };
  6630. return result;
  6631. };
  6632. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6633. if (position === void 0) {
  6634. position = this.position;
  6635. }
  6636. return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  6637. };
  6638. _proto.namedCombinator = function namedCombinator() {
  6639. if (this.isNamedCombinator()) {
  6640. var nameRaw = this.content(this.tokens[this.position + 1]);
  6641. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6642. var raws = {};
  6643. if (name !== nameRaw) {
  6644. raws.value = "/" + nameRaw + "/";
  6645. }
  6646. var node = new _combinator["default"]({
  6647. value: "/" + name + "/",
  6648. source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
  6649. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6650. raws: raws
  6651. });
  6652. this.position = this.position + 3;
  6653. return node;
  6654. } else {
  6655. this.unexpected();
  6656. }
  6657. };
  6658. _proto.combinator = function combinator() {
  6659. var _this3 = this;
  6660. if (this.content() === '|') {
  6661. return this.namespace();
  6662. }
  6663. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6664. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6665. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6666. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6667. if (nodes.length > 0) {
  6668. var last = this.current.last;
  6669. if (last) {
  6670. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6671. space = _this$convertWhitespa.space,
  6672. rawSpace = _this$convertWhitespa.rawSpace;
  6673. if (rawSpace !== undefined) {
  6674. last.rawSpaceAfter += rawSpace;
  6675. }
  6676. last.spaces.after += space;
  6677. } else {
  6678. nodes.forEach(function (n) {
  6679. return _this3.newNode(n);
  6680. });
  6681. }
  6682. }
  6683. return;
  6684. }
  6685. var firstToken = this.currToken;
  6686. var spaceOrDescendantSelectorNodes = undefined;
  6687. if (nextSigTokenPos > this.position) {
  6688. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6689. }
  6690. var node;
  6691. if (this.isNamedCombinator()) {
  6692. node = this.namedCombinator();
  6693. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6694. node = new _combinator["default"]({
  6695. value: this.content(),
  6696. source: getTokenSource(this.currToken),
  6697. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6698. });
  6699. this.position++;
  6700. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6701. this.unexpected();
  6702. }
  6703. if (node) {
  6704. if (spaceOrDescendantSelectorNodes) {
  6705. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6706. _space = _this$convertWhitespa2.space,
  6707. _rawSpace = _this$convertWhitespa2.rawSpace;
  6708. node.spaces.before = _space;
  6709. node.rawSpaceBefore = _rawSpace;
  6710. }
  6711. } else {
  6712. // descendant combinator
  6713. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6714. _space2 = _this$convertWhitespa3.space,
  6715. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6716. if (!_rawSpace2) {
  6717. _rawSpace2 = _space2;
  6718. }
  6719. var spaces = {};
  6720. var raws = {
  6721. spaces: {}
  6722. };
  6723. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6724. spaces.before = _space2.slice(0, _space2.length - 1);
  6725. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6726. } else if (_space2[0] === ' ' && _rawSpace2[0] === ' ') {
  6727. spaces.after = _space2.slice(1);
  6728. raws.spaces.after = _rawSpace2.slice(1);
  6729. } else {
  6730. raws.value = _rawSpace2;
  6731. }
  6732. node = new _combinator["default"]({
  6733. value: ' ',
  6734. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6735. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6736. spaces: spaces,
  6737. raws: raws
  6738. });
  6739. }
  6740. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6741. node.spaces.after = this.optionalSpace(this.content());
  6742. this.position++;
  6743. }
  6744. return this.newNode(node);
  6745. };
  6746. _proto.comma = function comma() {
  6747. if (this.position === this.tokens.length - 1) {
  6748. this.root.trailingComma = true;
  6749. this.position++;
  6750. return;
  6751. }
  6752. this.current._inferEndPosition();
  6753. var selector = new _selector["default"]({
  6754. source: {
  6755. start: tokenStart(this.tokens[this.position + 1])
  6756. },
  6757. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  6758. });
  6759. this.current.parent.append(selector);
  6760. this.current = selector;
  6761. this.position++;
  6762. };
  6763. _proto.comment = function comment() {
  6764. var current = this.currToken;
  6765. this.newNode(new _comment["default"]({
  6766. value: this.content(),
  6767. source: getTokenSource(current),
  6768. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6769. }));
  6770. this.position++;
  6771. };
  6772. _proto.error = function error(message, opts) {
  6773. throw this.root.error(message, opts);
  6774. };
  6775. _proto.missingBackslash = function missingBackslash() {
  6776. return this.error('Expected a backslash preceding the semicolon.', {
  6777. index: this.currToken[_tokenize.FIELDS.START_POS]
  6778. });
  6779. };
  6780. _proto.missingParenthesis = function missingParenthesis() {
  6781. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6782. };
  6783. _proto.missingSquareBracket = function missingSquareBracket() {
  6784. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6785. };
  6786. _proto.unexpected = function unexpected() {
  6787. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6788. };
  6789. _proto.unexpectedPipe = function unexpectedPipe() {
  6790. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6791. };
  6792. _proto.namespace = function namespace() {
  6793. var before = this.prevToken && this.content(this.prevToken) || true;
  6794. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6795. this.position++;
  6796. return this.word(before);
  6797. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6798. this.position++;
  6799. return this.universal(before);
  6800. }
  6801. this.unexpectedPipe();
  6802. };
  6803. _proto.nesting = function nesting() {
  6804. if (this.nextToken) {
  6805. var nextContent = this.content(this.nextToken);
  6806. if (nextContent === "|") {
  6807. this.position++;
  6808. return;
  6809. }
  6810. }
  6811. var current = this.currToken;
  6812. this.newNode(new _nesting["default"]({
  6813. value: this.content(),
  6814. source: getTokenSource(current),
  6815. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6816. }));
  6817. this.position++;
  6818. };
  6819. _proto.parentheses = function parentheses() {
  6820. var last = this.current.last;
  6821. var unbalanced = 1;
  6822. this.position++;
  6823. if (last && last.type === types.PSEUDO) {
  6824. var selector = new _selector["default"]({
  6825. source: {
  6826. start: tokenStart(this.tokens[this.position])
  6827. },
  6828. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  6829. });
  6830. var cache = this.current;
  6831. last.append(selector);
  6832. this.current = selector;
  6833. // Track nesting depth so deeply nested pseudo selectors raise a
  6834. // catchable error instead of overflowing the call stack. The
  6835. // counter is restored in `finally` so the parser is never left in
  6836. // an inconsistent state, even on the error path.
  6837. this.nestingDepth++;
  6838. try {
  6839. if (this.nestingDepth > this.maxNestingDepth) {
  6840. this.error("Cannot parse selector: nesting depth exceeds the maximum of " + this.maxNestingDepth + ".", {
  6841. index: this.currToken[_tokenize.FIELDS.START_POS]
  6842. });
  6843. }
  6844. while (this.position < this.tokens.length && unbalanced) {
  6845. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6846. unbalanced++;
  6847. }
  6848. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6849. unbalanced--;
  6850. }
  6851. if (unbalanced) {
  6852. this.parse();
  6853. } else {
  6854. this.current.source.end = tokenEnd(this.currToken);
  6855. this.current.parent.source.end = tokenEnd(this.currToken);
  6856. this.position++;
  6857. }
  6858. }
  6859. } finally {
  6860. this.nestingDepth--;
  6861. }
  6862. this.current = cache;
  6863. } else {
  6864. // I think this case should be an error. It's used to implement a basic parse of media queries
  6865. // but I don't think it's a good idea.
  6866. var parenStart = this.currToken;
  6867. var parenValue = "(";
  6868. var parenEnd;
  6869. while (this.position < this.tokens.length && unbalanced) {
  6870. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6871. unbalanced++;
  6872. }
  6873. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6874. unbalanced--;
  6875. }
  6876. parenEnd = this.currToken;
  6877. parenValue += this.parseParenthesisToken(this.currToken);
  6878. this.position++;
  6879. }
  6880. if (last) {
  6881. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6882. } else {
  6883. this.newNode(new _string["default"]({
  6884. value: parenValue,
  6885. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6886. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6887. }));
  6888. }
  6889. }
  6890. if (unbalanced) {
  6891. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6892. }
  6893. };
  6894. _proto.pseudo = function pseudo() {
  6895. var _this4 = this;
  6896. var pseudoStr = '';
  6897. var startingToken = this.currToken;
  6898. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6899. pseudoStr += this.content();
  6900. this.position++;
  6901. }
  6902. if (!this.currToken) {
  6903. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6904. }
  6905. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6906. this.splitWord(false, function (first, length) {
  6907. pseudoStr += first;
  6908. _this4.newNode(new _pseudo["default"]({
  6909. value: pseudoStr,
  6910. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6911. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6912. }));
  6913. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6914. _this4.error('Misplaced parenthesis.', {
  6915. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6916. });
  6917. }
  6918. });
  6919. } else {
  6920. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6921. }
  6922. };
  6923. _proto.space = function space() {
  6924. var content = this.content();
  6925. // Handle space before and after the selector
  6926. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6927. return node.type === 'comment';
  6928. })) {
  6929. this.spaces = this.optionalSpace(content);
  6930. this.position++;
  6931. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6932. this.current.last.spaces.after = this.optionalSpace(content);
  6933. this.position++;
  6934. } else {
  6935. this.combinator();
  6936. }
  6937. };
  6938. _proto.string = function string() {
  6939. var current = this.currToken;
  6940. this.newNode(new _string["default"]({
  6941. value: this.content(),
  6942. source: getTokenSource(current),
  6943. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6944. }));
  6945. this.position++;
  6946. };
  6947. _proto.universal = function universal(namespace) {
  6948. var nextToken = this.nextToken;
  6949. if (nextToken && this.content(nextToken) === '|') {
  6950. this.position++;
  6951. return this.namespace();
  6952. }
  6953. var current = this.currToken;
  6954. this.newNode(new _universal["default"]({
  6955. value: this.content(),
  6956. source: getTokenSource(current),
  6957. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6958. }), namespace);
  6959. this.position++;
  6960. };
  6961. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6962. var _this5 = this;
  6963. var nextToken = this.nextToken;
  6964. var word = this.content();
  6965. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6966. this.position++;
  6967. var current = this.content();
  6968. word += current;
  6969. if (current.lastIndexOf('\\') === current.length - 1) {
  6970. var next = this.nextToken;
  6971. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6972. word += this.requiredSpace(this.content(next));
  6973. this.position++;
  6974. }
  6975. }
  6976. nextToken = this.nextToken;
  6977. }
  6978. var hasClass = indexesOf(word, '.').filter(function (i) {
  6979. // Allow escaped dot within class name
  6980. var escapedDot = word[i - 1] === '\\';
  6981. // Allow decimal numbers percent in @keyframes
  6982. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6983. return !escapedDot && !isKeyframesPercent;
  6984. });
  6985. var hasId = indexesOf(word, '#').filter(function (i) {
  6986. return word[i - 1] !== '\\';
  6987. });
  6988. // Eliminate Sass interpolations from the list of id indexes
  6989. var interpolations = indexesOf(word, '#{');
  6990. if (interpolations.length) {
  6991. hasId = hasId.filter(function (hashIndex) {
  6992. return !~interpolations.indexOf(hashIndex);
  6993. });
  6994. }
  6995. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6996. indices.forEach(function (ind, i) {
  6997. var index = indices[i + 1] || word.length;
  6998. var value = word.slice(ind, index);
  6999. if (i === 0 && firstCallback) {
  7000. return firstCallback.call(_this5, value, indices.length);
  7001. }
  7002. var node;
  7003. var current = _this5.currToken;
  7004. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  7005. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  7006. if (~hasClass.indexOf(ind)) {
  7007. var classNameOpts = {
  7008. value: value.slice(1),
  7009. source: source,
  7010. sourceIndex: sourceIndex
  7011. };
  7012. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  7013. } else if (~hasId.indexOf(ind)) {
  7014. var idOpts = {
  7015. value: value.slice(1),
  7016. source: source,
  7017. sourceIndex: sourceIndex
  7018. };
  7019. node = new _id["default"](unescapeProp(idOpts, "value"));
  7020. } else {
  7021. var tagOpts = {
  7022. value: value,
  7023. source: source,
  7024. sourceIndex: sourceIndex
  7025. };
  7026. unescapeProp(tagOpts, "value");
  7027. node = new _tag["default"](tagOpts);
  7028. }
  7029. _this5.newNode(node, namespace);
  7030. // Ensure that the namespace is used only once
  7031. namespace = null;
  7032. });
  7033. this.position++;
  7034. };
  7035. _proto.word = function word(namespace) {
  7036. var nextToken = this.nextToken;
  7037. if (nextToken && this.content(nextToken) === '|') {
  7038. this.position++;
  7039. return this.namespace();
  7040. }
  7041. return this.splitWord(namespace);
  7042. };
  7043. _proto.loop = function loop() {
  7044. while (this.position < this.tokens.length) {
  7045. this.parse(true);
  7046. }
  7047. this.current._inferEndPosition();
  7048. return this.root;
  7049. };
  7050. _proto.parse = function parse(throwOnParenthesis) {
  7051. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  7052. case tokens.space:
  7053. this.space();
  7054. break;
  7055. case tokens.comment:
  7056. this.comment();
  7057. break;
  7058. case tokens.openParenthesis:
  7059. this.parentheses();
  7060. break;
  7061. case tokens.closeParenthesis:
  7062. if (throwOnParenthesis) {
  7063. this.missingParenthesis();
  7064. }
  7065. break;
  7066. case tokens.openSquare:
  7067. this.attribute();
  7068. break;
  7069. case tokens.dollar:
  7070. case tokens.caret:
  7071. case tokens.equals:
  7072. case tokens.word:
  7073. this.word();
  7074. break;
  7075. case tokens.colon:
  7076. this.pseudo();
  7077. break;
  7078. case tokens.comma:
  7079. this.comma();
  7080. break;
  7081. case tokens.asterisk:
  7082. this.universal();
  7083. break;
  7084. case tokens.ampersand:
  7085. this.nesting();
  7086. break;
  7087. case tokens.slash:
  7088. case tokens.combinator:
  7089. this.combinator();
  7090. break;
  7091. case tokens.str:
  7092. this.string();
  7093. break;
  7094. // These cases throw; no break needed.
  7095. case tokens.closeSquare:
  7096. this.missingSquareBracket();
  7097. case tokens.semicolon:
  7098. this.missingBackslash();
  7099. default:
  7100. this.unexpected();
  7101. }
  7102. }
  7103. /**
  7104. * Helpers
  7105. */;
  7106. _proto.expected = function expected(description, index, found) {
  7107. if (Array.isArray(description)) {
  7108. var last = description.pop();
  7109. description = description.join(', ') + " or " + last;
  7110. }
  7111. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  7112. if (!found) {
  7113. return this.error("Expected " + an + " " + description + ".", {
  7114. index: index
  7115. });
  7116. }
  7117. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  7118. index: index
  7119. });
  7120. };
  7121. _proto.requiredSpace = function requiredSpace(space) {
  7122. return this.options.lossy ? ' ' : space;
  7123. };
  7124. _proto.optionalSpace = function optionalSpace(space) {
  7125. return this.options.lossy ? '' : space;
  7126. };
  7127. _proto.lossySpace = function lossySpace(space, required) {
  7128. if (this.options.lossy) {
  7129. return required ? ' ' : '';
  7130. } else {
  7131. return space;
  7132. }
  7133. };
  7134. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  7135. var content = this.content(token);
  7136. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  7137. return this.requiredSpace(content);
  7138. } else {
  7139. return content;
  7140. }
  7141. };
  7142. _proto.newNode = function newNode(node, namespace) {
  7143. if (namespace) {
  7144. if (/^ +$/.test(namespace)) {
  7145. if (!this.options.lossy) {
  7146. this.spaces = (this.spaces || '') + namespace;
  7147. }
  7148. namespace = true;
  7149. }
  7150. node.namespace = namespace;
  7151. unescapeProp(node, "namespace");
  7152. }
  7153. if (this.spaces) {
  7154. node.spaces.before = this.spaces;
  7155. this.spaces = '';
  7156. }
  7157. return this.current.append(node);
  7158. };
  7159. _proto.content = function content(token) {
  7160. if (token === void 0) {
  7161. token = this.currToken;
  7162. }
  7163. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  7164. };
  7165. /**
  7166. * returns the index of the next non-whitespace, non-comment token.
  7167. * returns -1 if no meaningful token is found.
  7168. */
  7169. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  7170. if (startPosition === void 0) {
  7171. startPosition = this.position + 1;
  7172. }
  7173. var searchPosition = startPosition;
  7174. while (searchPosition < this.tokens.length) {
  7175. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  7176. searchPosition++;
  7177. continue;
  7178. } else {
  7179. return searchPosition;
  7180. }
  7181. }
  7182. return -1;
  7183. };
  7184. _createClass(Parser, [{
  7185. key: "currToken",
  7186. get: function get() {
  7187. return this.tokens[this.position];
  7188. }
  7189. }, {
  7190. key: "nextToken",
  7191. get: function get() {
  7192. return this.tokens[this.position + 1];
  7193. }
  7194. }, {
  7195. key: "prevToken",
  7196. get: function get() {
  7197. return this.tokens[this.position - 1];
  7198. }
  7199. }]);
  7200. return Parser;
  7201. }();
  7202. module.exports = exports.default;
  7203. } (parser$1, parser$1.exports));
  7204. return parser$1.exports;
  7205. }
  7206. var hasRequiredProcessor$1;
  7207. function requireProcessor$1 () {
  7208. if (hasRequiredProcessor$1) return processor$1.exports;
  7209. hasRequiredProcessor$1 = 1;
  7210. (function (module, exports) {
  7211. exports.__esModule = true;
  7212. exports["default"] = void 0;
  7213. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser$2());
  7214. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  7215. exports["default"] = /*#__PURE__*/function () {
  7216. function Processor(func, options) {
  7217. this.func = func || function noop() {};
  7218. this.funcRes = null;
  7219. this.options = options;
  7220. }
  7221. var _proto = Processor.prototype;
  7222. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7223. if (options === void 0) {
  7224. options = {};
  7225. }
  7226. var merged = Object.assign({}, this.options, options);
  7227. if (merged.updateSelector === false) {
  7228. return false;
  7229. } else {
  7230. return typeof rule !== "string";
  7231. }
  7232. };
  7233. _proto._isLossy = function _isLossy(options) {
  7234. if (options === void 0) {
  7235. options = {};
  7236. }
  7237. var merged = Object.assign({}, this.options, options);
  7238. if (merged.lossless === false) {
  7239. return true;
  7240. } else {
  7241. return false;
  7242. }
  7243. };
  7244. _proto._root = function _root(rule, options) {
  7245. if (options === void 0) {
  7246. options = {};
  7247. }
  7248. var parser = new _parser["default"](rule, this._parseOptions(options));
  7249. return parser.root;
  7250. };
  7251. _proto._parseOptions = function _parseOptions(options) {
  7252. var merged = Object.assign({}, this.options, options);
  7253. return {
  7254. lossy: this._isLossy(merged),
  7255. maxNestingDepth: merged.maxNestingDepth
  7256. };
  7257. };
  7258. _proto._stringifyOptions = function _stringifyOptions(options) {
  7259. var merged = Object.assign({}, this.options, options);
  7260. return {
  7261. maxNestingDepth: merged.maxNestingDepth
  7262. };
  7263. };
  7264. _proto._run = function _run(rule, options) {
  7265. var _this = this;
  7266. if (options === void 0) {
  7267. options = {};
  7268. }
  7269. return new Promise(function (resolve, reject) {
  7270. try {
  7271. var root = _this._root(rule, options);
  7272. Promise.resolve(_this.func(root)).then(function (transform) {
  7273. var string = undefined;
  7274. if (_this._shouldUpdateSelector(rule, options)) {
  7275. string = root.toString(_this._stringifyOptions(options));
  7276. rule.selector = string;
  7277. }
  7278. return {
  7279. transform: transform,
  7280. root: root,
  7281. string: string
  7282. };
  7283. }).then(resolve, reject);
  7284. } catch (e) {
  7285. reject(e);
  7286. return;
  7287. }
  7288. });
  7289. };
  7290. _proto._runSync = function _runSync(rule, options) {
  7291. if (options === void 0) {
  7292. options = {};
  7293. }
  7294. var root = this._root(rule, options);
  7295. var transform = this.func(root);
  7296. if (transform && typeof transform.then === "function") {
  7297. throw new Error("Selector processor returned a promise to a synchronous call.");
  7298. }
  7299. var string = undefined;
  7300. if (options.updateSelector && typeof rule !== "string") {
  7301. string = root.toString(this._stringifyOptions(options));
  7302. rule.selector = string;
  7303. }
  7304. return {
  7305. transform: transform,
  7306. root: root,
  7307. string: string
  7308. };
  7309. }
  7310. /**
  7311. * Process rule into a selector AST.
  7312. *
  7313. * @param rule {postcss.Rule | string} The css selector to be processed
  7314. * @param options The options for processing
  7315. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7316. */;
  7317. _proto.ast = function ast(rule, options) {
  7318. return this._run(rule, options).then(function (result) {
  7319. return result.root;
  7320. });
  7321. }
  7322. /**
  7323. * Process rule into a selector AST synchronously.
  7324. *
  7325. * @param rule {postcss.Rule | string} The css selector to be processed
  7326. * @param options The options for processing
  7327. * @returns {parser.Root} The AST of the selector after processing it.
  7328. */;
  7329. _proto.astSync = function astSync(rule, options) {
  7330. return this._runSync(rule, options).root;
  7331. }
  7332. /**
  7333. * Process a selector into a transformed value asynchronously
  7334. *
  7335. * @param rule {postcss.Rule | string} The css selector to be processed
  7336. * @param options The options for processing
  7337. * @returns {Promise<any>} The value returned by the processor.
  7338. */;
  7339. _proto.transform = function transform(rule, options) {
  7340. return this._run(rule, options).then(function (result) {
  7341. return result.transform;
  7342. });
  7343. }
  7344. /**
  7345. * Process a selector into a transformed value synchronously.
  7346. *
  7347. * @param rule {postcss.Rule | string} The css selector to be processed
  7348. * @param options The options for processing
  7349. * @returns {any} The value returned by the processor.
  7350. */;
  7351. _proto.transformSync = function transformSync(rule, options) {
  7352. return this._runSync(rule, options).transform;
  7353. }
  7354. /**
  7355. * Process a selector into a new selector string asynchronously.
  7356. *
  7357. * @param rule {postcss.Rule | string} The css selector to be processed
  7358. * @param options The options for processing
  7359. * @returns {string} the selector after processing.
  7360. */;
  7361. _proto.process = function process(rule, options) {
  7362. var _this2 = this;
  7363. return this._run(rule, options).then(function (result) {
  7364. return result.string || result.root.toString(_this2._stringifyOptions(options));
  7365. });
  7366. }
  7367. /**
  7368. * Process a selector into a new selector string synchronously.
  7369. *
  7370. * @param rule {postcss.Rule | string} The css selector to be processed
  7371. * @param options The options for processing
  7372. * @returns {string} the selector after processing.
  7373. */;
  7374. _proto.processSync = function processSync(rule, options) {
  7375. var result = this._runSync(rule, options);
  7376. return result.string || result.root.toString(this._stringifyOptions(options));
  7377. };
  7378. return Processor;
  7379. }();
  7380. module.exports = exports.default;
  7381. } (processor$1, processor$1.exports));
  7382. return processor$1.exports;
  7383. }
  7384. var selectors$1 = {};
  7385. var constructors$1 = {};
  7386. var hasRequiredConstructors$1;
  7387. function requireConstructors$1 () {
  7388. if (hasRequiredConstructors$1) return constructors$1;
  7389. hasRequiredConstructors$1 = 1;
  7390. constructors$1.__esModule = true;
  7391. constructors$1.universal = constructors$1.tag = constructors$1.string = constructors$1.selector = constructors$1.root = constructors$1.pseudo = constructors$1.nesting = constructors$1.id = constructors$1.comment = constructors$1.combinator = constructors$1.className = constructors$1.attribute = void 0;
  7392. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute$1());
  7393. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  7394. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  7395. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  7396. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  7397. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  7398. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  7399. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  7400. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  7401. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  7402. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  7403. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  7404. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  7405. constructors$1.attribute = function attribute(opts) {
  7406. return new _attribute["default"](opts);
  7407. };
  7408. constructors$1.className = function className(opts) {
  7409. return new _className["default"](opts);
  7410. };
  7411. constructors$1.combinator = function combinator(opts) {
  7412. return new _combinator["default"](opts);
  7413. };
  7414. constructors$1.comment = function comment(opts) {
  7415. return new _comment["default"](opts);
  7416. };
  7417. constructors$1.id = function id(opts) {
  7418. return new _id["default"](opts);
  7419. };
  7420. constructors$1.nesting = function nesting(opts) {
  7421. return new _nesting["default"](opts);
  7422. };
  7423. constructors$1.pseudo = function pseudo(opts) {
  7424. return new _pseudo["default"](opts);
  7425. };
  7426. constructors$1.root = function root(opts) {
  7427. return new _root["default"](opts);
  7428. };
  7429. constructors$1.selector = function selector(opts) {
  7430. return new _selector["default"](opts);
  7431. };
  7432. constructors$1.string = function string(opts) {
  7433. return new _string["default"](opts);
  7434. };
  7435. constructors$1.tag = function tag(opts) {
  7436. return new _tag["default"](opts);
  7437. };
  7438. constructors$1.universal = function universal(opts) {
  7439. return new _universal["default"](opts);
  7440. };
  7441. return constructors$1;
  7442. }
  7443. var guards$1 = {};
  7444. var hasRequiredGuards$1;
  7445. function requireGuards$1 () {
  7446. if (hasRequiredGuards$1) return guards$1;
  7447. hasRequiredGuards$1 = 1;
  7448. guards$1.__esModule = true;
  7449. guards$1.isComment = guards$1.isCombinator = guards$1.isClassName = guards$1.isAttribute = void 0;
  7450. guards$1.isContainer = isContainer;
  7451. guards$1.isIdentifier = void 0;
  7452. guards$1.isNamespace = isNamespace;
  7453. guards$1.isNesting = void 0;
  7454. guards$1.isNode = isNode;
  7455. guards$1.isPseudo = void 0;
  7456. guards$1.isPseudoClass = isPseudoClass;
  7457. guards$1.isPseudoElement = isPseudoElement;
  7458. guards$1.isUniversal = guards$1.isTag = guards$1.isString = guards$1.isSelector = guards$1.isRoot = void 0;
  7459. var _types = /*@__PURE__*/ requireTypes$1();
  7460. var _IS_TYPE;
  7461. var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
  7462. function isNode(node) {
  7463. return typeof node === "object" && IS_TYPE[node.type];
  7464. }
  7465. function isNodeType(type, node) {
  7466. return isNode(node) && node.type === type;
  7467. }
  7468. var isAttribute = guards$1.isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7469. guards$1.isClassName = isNodeType.bind(null, _types.CLASS);
  7470. guards$1.isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7471. guards$1.isComment = isNodeType.bind(null, _types.COMMENT);
  7472. guards$1.isIdentifier = isNodeType.bind(null, _types.ID);
  7473. guards$1.isNesting = isNodeType.bind(null, _types.NESTING);
  7474. var isPseudo = guards$1.isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7475. guards$1.isRoot = isNodeType.bind(null, _types.ROOT);
  7476. guards$1.isSelector = isNodeType.bind(null, _types.SELECTOR);
  7477. guards$1.isString = isNodeType.bind(null, _types.STRING);
  7478. var isTag = guards$1.isTag = isNodeType.bind(null, _types.TAG);
  7479. guards$1.isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7480. function isPseudoElement(node) {
  7481. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line");
  7482. }
  7483. function isPseudoClass(node) {
  7484. return isPseudo(node) && !isPseudoElement(node);
  7485. }
  7486. function isContainer(node) {
  7487. return !!(isNode(node) && node.walk);
  7488. }
  7489. function isNamespace(node) {
  7490. return isAttribute(node) || isTag(node);
  7491. }
  7492. return guards$1;
  7493. }
  7494. var hasRequiredSelectors$1;
  7495. function requireSelectors$1 () {
  7496. if (hasRequiredSelectors$1) return selectors$1;
  7497. hasRequiredSelectors$1 = 1;
  7498. (function (exports) {
  7499. exports.__esModule = true;
  7500. var _types = /*@__PURE__*/ requireTypes$1();
  7501. Object.keys(_types).forEach(function (key) {
  7502. if (key === "default" || key === "__esModule") return;
  7503. if (key in exports && exports[key] === _types[key]) return;
  7504. exports[key] = _types[key];
  7505. });
  7506. var _constructors = /*@__PURE__*/ requireConstructors$1();
  7507. Object.keys(_constructors).forEach(function (key) {
  7508. if (key === "default" || key === "__esModule") return;
  7509. if (key in exports && exports[key] === _constructors[key]) return;
  7510. exports[key] = _constructors[key];
  7511. });
  7512. var _guards = /*@__PURE__*/ requireGuards$1();
  7513. Object.keys(_guards).forEach(function (key) {
  7514. if (key === "default" || key === "__esModule") return;
  7515. if (key in exports && exports[key] === _guards[key]) return;
  7516. exports[key] = _guards[key];
  7517. });
  7518. } (selectors$1));
  7519. return selectors$1;
  7520. }
  7521. var hasRequiredDist$1;
  7522. function requireDist$1 () {
  7523. if (hasRequiredDist$1) return dist$1.exports;
  7524. hasRequiredDist$1 = 1;
  7525. (function (module, exports) {
  7526. exports.__esModule = true;
  7527. exports["default"] = void 0;
  7528. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor$1());
  7529. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors$1());
  7530. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  7531. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  7532. var parser = function parser(processor) {
  7533. return new _processor["default"](processor);
  7534. };
  7535. Object.assign(parser, selectors);
  7536. delete parser.__esModule;
  7537. exports["default"] = parser;
  7538. module.exports = exports.default;
  7539. } (dist$1, dist$1.exports));
  7540. return dist$1.exports;
  7541. }
  7542. var distExports = /*@__PURE__*/ requireDist$1();
  7543. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7544. const animationNameRE = /^(?:-\w+-)?animation-name$/;
  7545. const animationRE = /^(?:-\w+-)?animation$/;
  7546. const keyframesRE = /^(?:-\w+-)?keyframes$/;
  7547. const scopedPlugin = (id = "") => {
  7548. const keyframes = /* @__PURE__ */ Object.create(null);
  7549. const shortId = id.replace(/^data-v-/, "");
  7550. return {
  7551. postcssPlugin: "vue-sfc-scoped",
  7552. Rule(rule) {
  7553. processRule(id, rule);
  7554. },
  7555. AtRule(node) {
  7556. if (keyframesRE.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7557. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7558. }
  7559. },
  7560. OnceExit(root) {
  7561. if (Object.keys(keyframes).length) {
  7562. root.walkDecls((decl) => {
  7563. if (animationNameRE.test(decl.prop)) {
  7564. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7565. }
  7566. if (animationRE.test(decl.prop)) {
  7567. decl.value = decl.value.split(",").map((v) => {
  7568. const vals = v.trim().split(/\s+/);
  7569. const i = vals.findIndex((val) => keyframes[val]);
  7570. if (i !== -1) {
  7571. vals.splice(i, 1, keyframes[vals[i]]);
  7572. return vals.join(" ");
  7573. } else {
  7574. return v;
  7575. }
  7576. }).join(",");
  7577. }
  7578. });
  7579. }
  7580. }
  7581. };
  7582. };
  7583. const processedRules = /* @__PURE__ */ new WeakSet();
  7584. function processRule(id, rule) {
  7585. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && keyframesRE.test(rule.parent.name)) {
  7586. return;
  7587. }
  7588. processedRules.add(rule);
  7589. let deep = false;
  7590. let parent = rule.parent;
  7591. while (parent && parent.type !== "root") {
  7592. if (parent.__deep) {
  7593. deep = true;
  7594. break;
  7595. }
  7596. parent = parent.parent;
  7597. }
  7598. rule.selector = selectorParser((selectorRoot) => {
  7599. selectorRoot.each((selector) => {
  7600. rewriteSelector(id, rule, selector, selectorRoot, deep);
  7601. });
  7602. }).processSync(rule.selector);
  7603. }
  7604. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  7605. let node = null;
  7606. let shouldInject = !deep;
  7607. let hasNestedDeep = false;
  7608. let splitForNestedDeep = false;
  7609. selector.each((n) => {
  7610. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7611. n.value = " ";
  7612. n.spaces.before = n.spaces.after = "";
  7613. warn(
  7614. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7615. );
  7616. return false;
  7617. }
  7618. if (n.type === "pseudo") {
  7619. const { value } = n;
  7620. if (isDeepContainerPseudo(n)) {
  7621. const hasDeepSelectors = n.nodes.some(
  7622. (selector2) => selector2.some(isDeepSelector)
  7623. );
  7624. if (hasDeepSelectors) {
  7625. const hasScopeAnchor = !!node;
  7626. const hasMixedSelectors = n.nodes.some(
  7627. (selector2) => !selector2.some(isDeepSelector)
  7628. );
  7629. const hasTrailingNodes = selector.index(n) < selector.length - 1;
  7630. if (canSplitDeepContainerPseudo(n) && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  7631. splitSelectorForNestedDeep(
  7632. id,
  7633. rule,
  7634. selector,
  7635. selectorRoot,
  7636. n,
  7637. deep,
  7638. slotted
  7639. );
  7640. splitForNestedDeep = true;
  7641. return false;
  7642. }
  7643. if (value === ":not" && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  7644. return;
  7645. }
  7646. n.nodes.forEach(
  7647. (selector2) => rewriteSelector(
  7648. id,
  7649. rule,
  7650. selector2,
  7651. selectorRoot,
  7652. deep || hasScopeAnchor,
  7653. slotted
  7654. )
  7655. );
  7656. if (!hasScopeAnchor) {
  7657. node = n;
  7658. shouldInject = false;
  7659. }
  7660. hasNestedDeep = true;
  7661. }
  7662. }
  7663. if (value === ":deep" || value === "::v-deep") {
  7664. rule.__deep = true;
  7665. if (n.nodes.length) {
  7666. let last = n;
  7667. n.nodes[0].each((ss) => {
  7668. selector.insertAfter(last, ss);
  7669. last = ss;
  7670. });
  7671. const prev = selector.at(selector.index(n) - 1);
  7672. if (!prev || !isSpaceCombinator(prev)) {
  7673. selector.insertAfter(
  7674. n,
  7675. selectorParser.combinator({
  7676. value: " "
  7677. })
  7678. );
  7679. }
  7680. selector.removeChild(n);
  7681. } else {
  7682. warn(
  7683. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7684. );
  7685. const prev = selector.at(selector.index(n) - 1);
  7686. if (prev && isSpaceCombinator(prev)) {
  7687. selector.removeChild(prev);
  7688. }
  7689. selector.removeChild(n);
  7690. }
  7691. return false;
  7692. }
  7693. if (value === ":slotted" || value === "::v-slotted") {
  7694. rewriteSelector(
  7695. id,
  7696. rule,
  7697. n.nodes[0],
  7698. selectorRoot,
  7699. deep,
  7700. true
  7701. );
  7702. let last = n;
  7703. n.nodes[0].each((ss) => {
  7704. selector.insertAfter(last, ss);
  7705. last = ss;
  7706. });
  7707. selector.removeChild(n);
  7708. shouldInject = false;
  7709. return false;
  7710. }
  7711. if (value === ":global" || value === "::v-global") {
  7712. selector.replaceWith(n.nodes[0]);
  7713. return false;
  7714. }
  7715. }
  7716. if (n.type === "universal") {
  7717. const prev = selector.at(selector.index(n) - 1);
  7718. const next = selector.at(selector.index(n) + 1);
  7719. if (!prev) {
  7720. if (next) {
  7721. if (next.type === "combinator" && next.value === " ") {
  7722. selector.removeChild(next);
  7723. }
  7724. selector.removeChild(n);
  7725. return;
  7726. } else {
  7727. node = selectorParser.combinator({
  7728. value: ""
  7729. });
  7730. selector.insertBefore(n, node);
  7731. selector.removeChild(n);
  7732. return false;
  7733. }
  7734. }
  7735. if (node) return;
  7736. }
  7737. if (!hasNestedDeep && (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node)) {
  7738. node = n;
  7739. }
  7740. });
  7741. if (splitForNestedDeep) {
  7742. return;
  7743. }
  7744. if (rule.nodes.some((node2) => node2.type === "rule")) {
  7745. const deep2 = rule.__deep;
  7746. if (!deep2) {
  7747. extractAndWrapNodes(rule);
  7748. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  7749. for (const atnode of atruleNodes) {
  7750. extractAndWrapNodes(atnode);
  7751. }
  7752. }
  7753. shouldInject = deep2;
  7754. }
  7755. if (node && !hasNestedDeep) {
  7756. const { type, value } = node;
  7757. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7758. node.nodes.forEach(
  7759. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  7760. );
  7761. shouldInject = false;
  7762. }
  7763. }
  7764. if (node) {
  7765. node.spaces.after = "";
  7766. } else {
  7767. selector.first.spaces.before = "";
  7768. }
  7769. if (shouldInject) {
  7770. const idToAdd = slotted ? id + "-s" : id;
  7771. selector.insertAfter(
  7772. // If node is null it means we need to inject [id] at the start
  7773. // insertAfter can handle `null` here
  7774. node,
  7775. selectorParser.attribute({
  7776. attribute: idToAdd,
  7777. value: idToAdd,
  7778. raws: {},
  7779. quoteMark: `"`
  7780. })
  7781. );
  7782. }
  7783. }
  7784. function isSpaceCombinator(node) {
  7785. return node.type === "combinator" && /^\s+$/.test(node.value);
  7786. }
  7787. function isDeepSelector(node) {
  7788. var _a;
  7789. if (node.type === "pseudo" && (node.value === ":deep" || node.value === "::v-deep")) {
  7790. return true;
  7791. }
  7792. return !!((_a = node.nodes) == null ? void 0 : _a.some((child) => isDeepSelector(child)));
  7793. }
  7794. function isDeepContainerPseudo(node) {
  7795. return node.type === "pseudo" && (node.value === ":is" || node.value === ":where" || node.value === ":has" || node.value === ":not");
  7796. }
  7797. function canSplitDeepContainerPseudo(node) {
  7798. return node.value === ":is" || node.value === ":where" || node.value === ":has";
  7799. }
  7800. function splitSelectorForNestedDeep(id, rule, selector, selectorRoot, pseudo, deep, slotted) {
  7801. const pseudoIndex = selector.index(pseudo);
  7802. const selectors = pseudo.nodes.map((branch, index) => {
  7803. const branchSelector = selector.clone();
  7804. if (branchSelector.first) {
  7805. branchSelector.first.spaces.before = index === 0 ? selector.first.spaces.before : " ";
  7806. }
  7807. const branchPseudo = branchSelector.at(pseudoIndex);
  7808. const branchClone = branch.clone();
  7809. if (branchClone.first) {
  7810. branchClone.first.spaces.before = "";
  7811. }
  7812. branchPseudo.removeAll();
  7813. branchPseudo.append(branchClone);
  7814. rewriteSelector(id, rule, branchSelector, selectorRoot, deep, slotted);
  7815. return branchSelector;
  7816. });
  7817. selector.replaceWith(...selectors);
  7818. }
  7819. function extractAndWrapNodes(parentNode) {
  7820. if (!parentNode.nodes) return;
  7821. const nodes = parentNode.nodes.filter(
  7822. (node) => node.type === "decl" || node.type === "comment"
  7823. );
  7824. if (nodes.length) {
  7825. for (const node of nodes) {
  7826. parentNode.removeChild(node);
  7827. }
  7828. const wrappedRule = new require$$0$1.Rule({
  7829. nodes,
  7830. selector: "&"
  7831. });
  7832. parentNode.prepend(wrappedRule);
  7833. }
  7834. }
  7835. scopedPlugin.postcss = true;
  7836. var sourceMap = {};
  7837. var sourceMapGenerator = {};
  7838. var base64Vlq = {};
  7839. var base64 = {};
  7840. /* -*- Mode: js; js-indent-level: 2; -*- */
  7841. var hasRequiredBase64;
  7842. function requireBase64 () {
  7843. if (hasRequiredBase64) return base64;
  7844. hasRequiredBase64 = 1;
  7845. /*
  7846. * Copyright 2011 Mozilla Foundation and contributors
  7847. * Licensed under the New BSD license. See LICENSE or:
  7848. * http://opensource.org/licenses/BSD-3-Clause
  7849. */
  7850. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7851. /**
  7852. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7853. */
  7854. base64.encode = function (number) {
  7855. if (0 <= number && number < intToCharMap.length) {
  7856. return intToCharMap[number];
  7857. }
  7858. throw new TypeError("Must be between 0 and 63: " + number);
  7859. };
  7860. /**
  7861. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7862. * failure.
  7863. */
  7864. base64.decode = function (charCode) {
  7865. var bigA = 65; // 'A'
  7866. var bigZ = 90; // 'Z'
  7867. var littleA = 97; // 'a'
  7868. var littleZ = 122; // 'z'
  7869. var zero = 48; // '0'
  7870. var nine = 57; // '9'
  7871. var plus = 43; // '+'
  7872. var slash = 47; // '/'
  7873. var littleOffset = 26;
  7874. var numberOffset = 52;
  7875. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7876. if (bigA <= charCode && charCode <= bigZ) {
  7877. return (charCode - bigA);
  7878. }
  7879. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7880. if (littleA <= charCode && charCode <= littleZ) {
  7881. return (charCode - littleA + littleOffset);
  7882. }
  7883. // 52 - 61: 0123456789
  7884. if (zero <= charCode && charCode <= nine) {
  7885. return (charCode - zero + numberOffset);
  7886. }
  7887. // 62: +
  7888. if (charCode == plus) {
  7889. return 62;
  7890. }
  7891. // 63: /
  7892. if (charCode == slash) {
  7893. return 63;
  7894. }
  7895. // Invalid base64 digit.
  7896. return -1;
  7897. };
  7898. return base64;
  7899. }
  7900. /* -*- Mode: js; js-indent-level: 2; -*- */
  7901. var hasRequiredBase64Vlq;
  7902. function requireBase64Vlq () {
  7903. if (hasRequiredBase64Vlq) return base64Vlq;
  7904. hasRequiredBase64Vlq = 1;
  7905. /*
  7906. * Copyright 2011 Mozilla Foundation and contributors
  7907. * Licensed under the New BSD license. See LICENSE or:
  7908. * http://opensource.org/licenses/BSD-3-Clause
  7909. *
  7910. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7911. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7912. *
  7913. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7914. * Redistribution and use in source and binary forms, with or without
  7915. * modification, are permitted provided that the following conditions are
  7916. * met:
  7917. *
  7918. * * Redistributions of source code must retain the above copyright
  7919. * notice, this list of conditions and the following disclaimer.
  7920. * * Redistributions in binary form must reproduce the above
  7921. * copyright notice, this list of conditions and the following
  7922. * disclaimer in the documentation and/or other materials provided
  7923. * with the distribution.
  7924. * * Neither the name of Google Inc. nor the names of its
  7925. * contributors may be used to endorse or promote products derived
  7926. * from this software without specific prior written permission.
  7927. *
  7928. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7929. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7930. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7931. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7932. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7933. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7934. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7935. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7936. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7937. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7938. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7939. */
  7940. var base64 = /*@__PURE__*/ requireBase64();
  7941. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7942. // length quantities we use in the source map spec, the first bit is the sign,
  7943. // the next four bits are the actual value, and the 6th bit is the
  7944. // continuation bit. The continuation bit tells us whether there are more
  7945. // digits in this value following this digit.
  7946. //
  7947. // Continuation
  7948. // | Sign
  7949. // | |
  7950. // V V
  7951. // 101011
  7952. var VLQ_BASE_SHIFT = 5;
  7953. // binary: 100000
  7954. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7955. // binary: 011111
  7956. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7957. // binary: 100000
  7958. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7959. /**
  7960. * Converts from a two-complement value to a value where the sign bit is
  7961. * placed in the least significant bit. For example, as decimals:
  7962. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7963. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7964. */
  7965. function toVLQSigned(aValue) {
  7966. return aValue < 0
  7967. ? ((-aValue) << 1) + 1
  7968. : (aValue << 1) + 0;
  7969. }
  7970. /**
  7971. * Converts to a two-complement value from a value where the sign bit is
  7972. * placed in the least significant bit. For example, as decimals:
  7973. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7974. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7975. */
  7976. function fromVLQSigned(aValue) {
  7977. var isNegative = (aValue & 1) === 1;
  7978. var shifted = aValue >> 1;
  7979. return isNegative
  7980. ? -shifted
  7981. : shifted;
  7982. }
  7983. /**
  7984. * Returns the base 64 VLQ encoded value.
  7985. */
  7986. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7987. var encoded = "";
  7988. var digit;
  7989. var vlq = toVLQSigned(aValue);
  7990. do {
  7991. digit = vlq & VLQ_BASE_MASK;
  7992. vlq >>>= VLQ_BASE_SHIFT;
  7993. if (vlq > 0) {
  7994. // There are still more digits in this value, so we must make sure the
  7995. // continuation bit is marked.
  7996. digit |= VLQ_CONTINUATION_BIT;
  7997. }
  7998. encoded += base64.encode(digit);
  7999. } while (vlq > 0);
  8000. return encoded;
  8001. };
  8002. /**
  8003. * Decodes the next base 64 VLQ value from the given string and returns the
  8004. * value and the rest of the string via the out parameter.
  8005. */
  8006. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  8007. var strLen = aStr.length;
  8008. var result = 0;
  8009. var shift = 0;
  8010. var continuation, digit;
  8011. do {
  8012. if (aIndex >= strLen) {
  8013. throw new Error("Expected more digits in base 64 VLQ value.");
  8014. }
  8015. digit = base64.decode(aStr.charCodeAt(aIndex++));
  8016. if (digit === -1) {
  8017. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  8018. }
  8019. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  8020. digit &= VLQ_BASE_MASK;
  8021. result = result + (digit << shift);
  8022. shift += VLQ_BASE_SHIFT;
  8023. } while (continuation);
  8024. aOutParam.value = fromVLQSigned(result);
  8025. aOutParam.rest = aIndex;
  8026. };
  8027. return base64Vlq;
  8028. }
  8029. var util$1 = {};
  8030. /* -*- Mode: js; js-indent-level: 2; -*- */
  8031. var hasRequiredUtil$1;
  8032. function requireUtil$1 () {
  8033. if (hasRequiredUtil$1) return util$1;
  8034. hasRequiredUtil$1 = 1;
  8035. (function (exports) {
  8036. /*
  8037. * Copyright 2011 Mozilla Foundation and contributors
  8038. * Licensed under the New BSD license. See LICENSE or:
  8039. * http://opensource.org/licenses/BSD-3-Clause
  8040. */
  8041. /**
  8042. * This is a helper function for getting values from parameter/options
  8043. * objects.
  8044. *
  8045. * @param args The object we are extracting values from
  8046. * @param name The name of the property we are getting.
  8047. * @param defaultValue An optional value to return if the property is missing
  8048. * from the object. If this is not specified and the property is missing, an
  8049. * error will be thrown.
  8050. */
  8051. function getArg(aArgs, aName, aDefaultValue) {
  8052. if (aName in aArgs) {
  8053. return aArgs[aName];
  8054. } else if (arguments.length === 3) {
  8055. return aDefaultValue;
  8056. } else {
  8057. throw new Error('"' + aName + '" is a required argument.');
  8058. }
  8059. }
  8060. exports.getArg = getArg;
  8061. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  8062. var dataUrlRegexp = /^data:.+\,.+$/;
  8063. function urlParse(aUrl) {
  8064. var match = aUrl.match(urlRegexp);
  8065. if (!match) {
  8066. return null;
  8067. }
  8068. return {
  8069. scheme: match[1],
  8070. auth: match[2],
  8071. host: match[3],
  8072. port: match[4],
  8073. path: match[5]
  8074. };
  8075. }
  8076. exports.urlParse = urlParse;
  8077. function urlGenerate(aParsedUrl) {
  8078. var url = '';
  8079. if (aParsedUrl.scheme) {
  8080. url += aParsedUrl.scheme + ':';
  8081. }
  8082. url += '//';
  8083. if (aParsedUrl.auth) {
  8084. url += aParsedUrl.auth + '@';
  8085. }
  8086. if (aParsedUrl.host) {
  8087. url += aParsedUrl.host;
  8088. }
  8089. if (aParsedUrl.port) {
  8090. url += ":" + aParsedUrl.port;
  8091. }
  8092. if (aParsedUrl.path) {
  8093. url += aParsedUrl.path;
  8094. }
  8095. return url;
  8096. }
  8097. exports.urlGenerate = urlGenerate;
  8098. /**
  8099. * Normalizes a path, or the path portion of a URL:
  8100. *
  8101. * - Replaces consecutive slashes with one slash.
  8102. * - Removes unnecessary '.' parts.
  8103. * - Removes unnecessary '<dir>/..' parts.
  8104. *
  8105. * Based on code in the Node.js 'path' core module.
  8106. *
  8107. * @param aPath The path or url to normalize.
  8108. */
  8109. function normalize(aPath) {
  8110. var path = aPath;
  8111. var url = urlParse(aPath);
  8112. if (url) {
  8113. if (!url.path) {
  8114. return aPath;
  8115. }
  8116. path = url.path;
  8117. }
  8118. var isAbsolute = exports.isAbsolute(path);
  8119. var parts = path.split(/\/+/);
  8120. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  8121. part = parts[i];
  8122. if (part === '.') {
  8123. parts.splice(i, 1);
  8124. } else if (part === '..') {
  8125. up++;
  8126. } else if (up > 0) {
  8127. if (part === '') {
  8128. // The first part is blank if the path is absolute. Trying to go
  8129. // above the root is a no-op. Therefore we can remove all '..' parts
  8130. // directly after the root.
  8131. parts.splice(i + 1, up);
  8132. up = 0;
  8133. } else {
  8134. parts.splice(i, 2);
  8135. up--;
  8136. }
  8137. }
  8138. }
  8139. path = parts.join('/');
  8140. if (path === '') {
  8141. path = isAbsolute ? '/' : '.';
  8142. }
  8143. if (url) {
  8144. url.path = path;
  8145. return urlGenerate(url);
  8146. }
  8147. return path;
  8148. }
  8149. exports.normalize = normalize;
  8150. /**
  8151. * Joins two paths/URLs.
  8152. *
  8153. * @param aRoot The root path or URL.
  8154. * @param aPath The path or URL to be joined with the root.
  8155. *
  8156. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  8157. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  8158. * first.
  8159. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  8160. * is updated with the result and aRoot is returned. Otherwise the result
  8161. * is returned.
  8162. * - If aPath is absolute, the result is aPath.
  8163. * - Otherwise the two paths are joined with a slash.
  8164. * - Joining for example 'http://' and 'www.example.com' is also supported.
  8165. */
  8166. function join(aRoot, aPath) {
  8167. if (aRoot === "") {
  8168. aRoot = ".";
  8169. }
  8170. if (aPath === "") {
  8171. aPath = ".";
  8172. }
  8173. var aPathUrl = urlParse(aPath);
  8174. var aRootUrl = urlParse(aRoot);
  8175. if (aRootUrl) {
  8176. aRoot = aRootUrl.path || '/';
  8177. }
  8178. // `join(foo, '//www.example.org')`
  8179. if (aPathUrl && !aPathUrl.scheme) {
  8180. if (aRootUrl) {
  8181. aPathUrl.scheme = aRootUrl.scheme;
  8182. }
  8183. return urlGenerate(aPathUrl);
  8184. }
  8185. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8186. return aPath;
  8187. }
  8188. // `join('http://', 'www.example.com')`
  8189. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8190. aRootUrl.host = aPath;
  8191. return urlGenerate(aRootUrl);
  8192. }
  8193. var joined = aPath.charAt(0) === '/'
  8194. ? aPath
  8195. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8196. if (aRootUrl) {
  8197. aRootUrl.path = joined;
  8198. return urlGenerate(aRootUrl);
  8199. }
  8200. return joined;
  8201. }
  8202. exports.join = join;
  8203. exports.isAbsolute = function (aPath) {
  8204. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8205. };
  8206. /**
  8207. * Make a path relative to a URL or another path.
  8208. *
  8209. * @param aRoot The root path or URL.
  8210. * @param aPath The path or URL to be made relative to aRoot.
  8211. */
  8212. function relative(aRoot, aPath) {
  8213. if (aRoot === "") {
  8214. aRoot = ".";
  8215. }
  8216. aRoot = aRoot.replace(/\/$/, '');
  8217. // It is possible for the path to be above the root. In this case, simply
  8218. // checking whether the root is a prefix of the path won't work. Instead, we
  8219. // need to remove components from the root one by one, until either we find
  8220. // a prefix that fits, or we run out of components to remove.
  8221. var level = 0;
  8222. while (aPath.indexOf(aRoot + '/') !== 0) {
  8223. var index = aRoot.lastIndexOf("/");
  8224. if (index < 0) {
  8225. return aPath;
  8226. }
  8227. // If the only part of the root that is left is the scheme (i.e. http://,
  8228. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8229. // have exhausted all components, so the path is not relative to the root.
  8230. aRoot = aRoot.slice(0, index);
  8231. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8232. return aPath;
  8233. }
  8234. ++level;
  8235. }
  8236. // Make sure we add a "../" for each component we removed from the root.
  8237. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8238. }
  8239. exports.relative = relative;
  8240. var supportsNullProto = (function () {
  8241. var obj = Object.create(null);
  8242. return !('__proto__' in obj);
  8243. }());
  8244. function identity (s) {
  8245. return s;
  8246. }
  8247. /**
  8248. * Because behavior goes wacky when you set `__proto__` on objects, we
  8249. * have to prefix all the strings in our set with an arbitrary character.
  8250. *
  8251. * See https://github.com/mozilla/source-map/pull/31 and
  8252. * https://github.com/mozilla/source-map/issues/30
  8253. *
  8254. * @param String aStr
  8255. */
  8256. function toSetString(aStr) {
  8257. if (isProtoString(aStr)) {
  8258. return '$' + aStr;
  8259. }
  8260. return aStr;
  8261. }
  8262. exports.toSetString = supportsNullProto ? identity : toSetString;
  8263. function fromSetString(aStr) {
  8264. if (isProtoString(aStr)) {
  8265. return aStr.slice(1);
  8266. }
  8267. return aStr;
  8268. }
  8269. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  8270. function isProtoString(s) {
  8271. if (!s) {
  8272. return false;
  8273. }
  8274. var length = s.length;
  8275. if (length < 9 /* "__proto__".length */) {
  8276. return false;
  8277. }
  8278. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8279. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8280. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8281. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8282. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8283. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8284. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8285. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8286. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8287. return false;
  8288. }
  8289. for (var i = length - 10; i >= 0; i--) {
  8290. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8291. return false;
  8292. }
  8293. }
  8294. return true;
  8295. }
  8296. /**
  8297. * Comparator between two mappings where the original positions are compared.
  8298. *
  8299. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8300. * mappings with the same original source/line/column, but different generated
  8301. * line and column the same. Useful when searching for a mapping with a
  8302. * stubbed out mapping.
  8303. */
  8304. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8305. var cmp = strcmp(mappingA.source, mappingB.source);
  8306. if (cmp !== 0) {
  8307. return cmp;
  8308. }
  8309. cmp = mappingA.originalLine - mappingB.originalLine;
  8310. if (cmp !== 0) {
  8311. return cmp;
  8312. }
  8313. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8314. if (cmp !== 0 || onlyCompareOriginal) {
  8315. return cmp;
  8316. }
  8317. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8318. if (cmp !== 0) {
  8319. return cmp;
  8320. }
  8321. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8322. if (cmp !== 0) {
  8323. return cmp;
  8324. }
  8325. return strcmp(mappingA.name, mappingB.name);
  8326. }
  8327. exports.compareByOriginalPositions = compareByOriginalPositions;
  8328. /**
  8329. * Comparator between two mappings with deflated source and name indices where
  8330. * the generated positions are compared.
  8331. *
  8332. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8333. * mappings with the same generated line and column, but different
  8334. * source/name/original line and column the same. Useful when searching for a
  8335. * mapping with a stubbed out mapping.
  8336. */
  8337. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8338. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8339. if (cmp !== 0) {
  8340. return cmp;
  8341. }
  8342. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8343. if (cmp !== 0 || onlyCompareGenerated) {
  8344. return cmp;
  8345. }
  8346. cmp = strcmp(mappingA.source, mappingB.source);
  8347. if (cmp !== 0) {
  8348. return cmp;
  8349. }
  8350. cmp = mappingA.originalLine - mappingB.originalLine;
  8351. if (cmp !== 0) {
  8352. return cmp;
  8353. }
  8354. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8355. if (cmp !== 0) {
  8356. return cmp;
  8357. }
  8358. return strcmp(mappingA.name, mappingB.name);
  8359. }
  8360. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8361. function strcmp(aStr1, aStr2) {
  8362. if (aStr1 === aStr2) {
  8363. return 0;
  8364. }
  8365. if (aStr1 === null) {
  8366. return 1; // aStr2 !== null
  8367. }
  8368. if (aStr2 === null) {
  8369. return -1; // aStr1 !== null
  8370. }
  8371. if (aStr1 > aStr2) {
  8372. return 1;
  8373. }
  8374. return -1;
  8375. }
  8376. /**
  8377. * Comparator between two mappings with inflated source and name strings where
  8378. * the generated positions are compared.
  8379. */
  8380. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8381. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8382. if (cmp !== 0) {
  8383. return cmp;
  8384. }
  8385. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8386. if (cmp !== 0) {
  8387. return cmp;
  8388. }
  8389. cmp = strcmp(mappingA.source, mappingB.source);
  8390. if (cmp !== 0) {
  8391. return cmp;
  8392. }
  8393. cmp = mappingA.originalLine - mappingB.originalLine;
  8394. if (cmp !== 0) {
  8395. return cmp;
  8396. }
  8397. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8398. if (cmp !== 0) {
  8399. return cmp;
  8400. }
  8401. return strcmp(mappingA.name, mappingB.name);
  8402. }
  8403. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8404. /**
  8405. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8406. * in the source maps specification), and then parse the string as
  8407. * JSON.
  8408. */
  8409. function parseSourceMapInput(str) {
  8410. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8411. }
  8412. exports.parseSourceMapInput = parseSourceMapInput;
  8413. /**
  8414. * Compute the URL of a source given the the source root, the source's
  8415. * URL, and the source map's URL.
  8416. */
  8417. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8418. sourceURL = sourceURL || '';
  8419. if (sourceRoot) {
  8420. // This follows what Chrome does.
  8421. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8422. sourceRoot += '/';
  8423. }
  8424. // The spec says:
  8425. // Line 4: An optional source root, useful for relocating source
  8426. // files on a server or removing repeated values in the
  8427. // “sources” entry. This value is prepended to the individual
  8428. // entries in the “source” field.
  8429. sourceURL = sourceRoot + sourceURL;
  8430. }
  8431. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8432. // a parameter. This mode is still somewhat supported, which is why
  8433. // this code block is conditional. However, it's preferable to pass
  8434. // the source map URL to SourceMapConsumer, so that this function
  8435. // can implement the source URL resolution algorithm as outlined in
  8436. // the spec. This block is basically the equivalent of:
  8437. // new URL(sourceURL, sourceMapURL).toString()
  8438. // ... except it avoids using URL, which wasn't available in the
  8439. // older releases of node still supported by this library.
  8440. //
  8441. // The spec says:
  8442. // If the sources are not absolute URLs after prepending of the
  8443. // “sourceRoot”, the sources are resolved relative to the
  8444. // SourceMap (like resolving script src in a html document).
  8445. if (sourceMapURL) {
  8446. var parsed = urlParse(sourceMapURL);
  8447. if (!parsed) {
  8448. throw new Error("sourceMapURL could not be parsed");
  8449. }
  8450. if (parsed.path) {
  8451. // Strip the last path component, but keep the "/".
  8452. var index = parsed.path.lastIndexOf('/');
  8453. if (index >= 0) {
  8454. parsed.path = parsed.path.substring(0, index + 1);
  8455. }
  8456. }
  8457. sourceURL = join(urlGenerate(parsed), sourceURL);
  8458. }
  8459. return normalize(sourceURL);
  8460. }
  8461. exports.computeSourceURL = computeSourceURL;
  8462. } (util$1));
  8463. return util$1;
  8464. }
  8465. var arraySet = {};
  8466. /* -*- Mode: js; js-indent-level: 2; -*- */
  8467. var hasRequiredArraySet;
  8468. function requireArraySet () {
  8469. if (hasRequiredArraySet) return arraySet;
  8470. hasRequiredArraySet = 1;
  8471. /*
  8472. * Copyright 2011 Mozilla Foundation and contributors
  8473. * Licensed under the New BSD license. See LICENSE or:
  8474. * http://opensource.org/licenses/BSD-3-Clause
  8475. */
  8476. var util = /*@__PURE__*/ requireUtil$1();
  8477. var has = Object.prototype.hasOwnProperty;
  8478. var hasNativeMap = typeof Map !== "undefined";
  8479. /**
  8480. * A data structure which is a combination of an array and a set. Adding a new
  8481. * member is O(1), testing for membership is O(1), and finding the index of an
  8482. * element is O(1). Removing elements from the set is not supported. Only
  8483. * strings are supported for membership.
  8484. */
  8485. function ArraySet() {
  8486. this._array = [];
  8487. this._set = hasNativeMap ? new Map() : Object.create(null);
  8488. }
  8489. /**
  8490. * Static method for creating ArraySet instances from an existing array.
  8491. */
  8492. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8493. var set = new ArraySet();
  8494. for (var i = 0, len = aArray.length; i < len; i++) {
  8495. set.add(aArray[i], aAllowDuplicates);
  8496. }
  8497. return set;
  8498. };
  8499. /**
  8500. * Return how many unique items are in this ArraySet. If duplicates have been
  8501. * added, than those do not count towards the size.
  8502. *
  8503. * @returns Number
  8504. */
  8505. ArraySet.prototype.size = function ArraySet_size() {
  8506. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8507. };
  8508. /**
  8509. * Add the given string to this set.
  8510. *
  8511. * @param String aStr
  8512. */
  8513. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8514. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8515. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8516. var idx = this._array.length;
  8517. if (!isDuplicate || aAllowDuplicates) {
  8518. this._array.push(aStr);
  8519. }
  8520. if (!isDuplicate) {
  8521. if (hasNativeMap) {
  8522. this._set.set(aStr, idx);
  8523. } else {
  8524. this._set[sStr] = idx;
  8525. }
  8526. }
  8527. };
  8528. /**
  8529. * Is the given string a member of this set?
  8530. *
  8531. * @param String aStr
  8532. */
  8533. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8534. if (hasNativeMap) {
  8535. return this._set.has(aStr);
  8536. } else {
  8537. var sStr = util.toSetString(aStr);
  8538. return has.call(this._set, sStr);
  8539. }
  8540. };
  8541. /**
  8542. * What is the index of the given string in the array?
  8543. *
  8544. * @param String aStr
  8545. */
  8546. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8547. if (hasNativeMap) {
  8548. var idx = this._set.get(aStr);
  8549. if (idx >= 0) {
  8550. return idx;
  8551. }
  8552. } else {
  8553. var sStr = util.toSetString(aStr);
  8554. if (has.call(this._set, sStr)) {
  8555. return this._set[sStr];
  8556. }
  8557. }
  8558. throw new Error('"' + aStr + '" is not in the set.');
  8559. };
  8560. /**
  8561. * What is the element at the given index?
  8562. *
  8563. * @param Number aIdx
  8564. */
  8565. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8566. if (aIdx >= 0 && aIdx < this._array.length) {
  8567. return this._array[aIdx];
  8568. }
  8569. throw new Error('No element indexed by ' + aIdx);
  8570. };
  8571. /**
  8572. * Returns the array representation of this set (which has the proper indices
  8573. * indicated by indexOf). Note that this is a copy of the internal array used
  8574. * for storing the members so that no one can mess with internal state.
  8575. */
  8576. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8577. return this._array.slice();
  8578. };
  8579. arraySet.ArraySet = ArraySet;
  8580. return arraySet;
  8581. }
  8582. var mappingList = {};
  8583. /* -*- Mode: js; js-indent-level: 2; -*- */
  8584. var hasRequiredMappingList;
  8585. function requireMappingList () {
  8586. if (hasRequiredMappingList) return mappingList;
  8587. hasRequiredMappingList = 1;
  8588. /*
  8589. * Copyright 2014 Mozilla Foundation and contributors
  8590. * Licensed under the New BSD license. See LICENSE or:
  8591. * http://opensource.org/licenses/BSD-3-Clause
  8592. */
  8593. var util = /*@__PURE__*/ requireUtil$1();
  8594. /**
  8595. * Determine whether mappingB is after mappingA with respect to generated
  8596. * position.
  8597. */
  8598. function generatedPositionAfter(mappingA, mappingB) {
  8599. // Optimized for most common case
  8600. var lineA = mappingA.generatedLine;
  8601. var lineB = mappingB.generatedLine;
  8602. var columnA = mappingA.generatedColumn;
  8603. var columnB = mappingB.generatedColumn;
  8604. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8605. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8606. }
  8607. /**
  8608. * A data structure to provide a sorted view of accumulated mappings in a
  8609. * performance conscious manner. It trades a neglibable overhead in general
  8610. * case for a large speedup in case of mappings being added in order.
  8611. */
  8612. function MappingList() {
  8613. this._array = [];
  8614. this._sorted = true;
  8615. // Serves as infimum
  8616. this._last = {generatedLine: -1, generatedColumn: 0};
  8617. }
  8618. /**
  8619. * Iterate through internal items. This method takes the same arguments that
  8620. * `Array.prototype.forEach` takes.
  8621. *
  8622. * NOTE: The order of the mappings is NOT guaranteed.
  8623. */
  8624. MappingList.prototype.unsortedForEach =
  8625. function MappingList_forEach(aCallback, aThisArg) {
  8626. this._array.forEach(aCallback, aThisArg);
  8627. };
  8628. /**
  8629. * Add the given source mapping.
  8630. *
  8631. * @param Object aMapping
  8632. */
  8633. MappingList.prototype.add = function MappingList_add(aMapping) {
  8634. if (generatedPositionAfter(this._last, aMapping)) {
  8635. this._last = aMapping;
  8636. this._array.push(aMapping);
  8637. } else {
  8638. this._sorted = false;
  8639. this._array.push(aMapping);
  8640. }
  8641. };
  8642. /**
  8643. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8644. * generated position.
  8645. *
  8646. * WARNING: This method returns internal data without copying, for
  8647. * performance. The return value must NOT be mutated, and should be treated as
  8648. * an immutable borrow. If you want to take ownership, you must make your own
  8649. * copy.
  8650. */
  8651. MappingList.prototype.toArray = function MappingList_toArray() {
  8652. if (!this._sorted) {
  8653. this._array.sort(util.compareByGeneratedPositionsInflated);
  8654. this._sorted = true;
  8655. }
  8656. return this._array;
  8657. };
  8658. mappingList.MappingList = MappingList;
  8659. return mappingList;
  8660. }
  8661. /* -*- Mode: js; js-indent-level: 2; -*- */
  8662. var hasRequiredSourceMapGenerator;
  8663. function requireSourceMapGenerator () {
  8664. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  8665. hasRequiredSourceMapGenerator = 1;
  8666. /*
  8667. * Copyright 2011 Mozilla Foundation and contributors
  8668. * Licensed under the New BSD license. See LICENSE or:
  8669. * http://opensource.org/licenses/BSD-3-Clause
  8670. */
  8671. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  8672. var util = /*@__PURE__*/ requireUtil$1();
  8673. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  8674. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  8675. /**
  8676. * An instance of the SourceMapGenerator represents a source map which is
  8677. * being built incrementally. You may pass an object with the following
  8678. * properties:
  8679. *
  8680. * - file: The filename of the generated source.
  8681. * - sourceRoot: A root for all relative URLs in this source map.
  8682. */
  8683. function SourceMapGenerator(aArgs) {
  8684. if (!aArgs) {
  8685. aArgs = {};
  8686. }
  8687. this._file = util.getArg(aArgs, 'file', null);
  8688. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8689. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8690. this._sources = new ArraySet();
  8691. this._names = new ArraySet();
  8692. this._mappings = new MappingList();
  8693. this._sourcesContents = null;
  8694. }
  8695. SourceMapGenerator.prototype._version = 3;
  8696. /**
  8697. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8698. *
  8699. * @param aSourceMapConsumer The SourceMap.
  8700. */
  8701. SourceMapGenerator.fromSourceMap =
  8702. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8703. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8704. var generator = new SourceMapGenerator({
  8705. file: aSourceMapConsumer.file,
  8706. sourceRoot: sourceRoot
  8707. });
  8708. aSourceMapConsumer.eachMapping(function (mapping) {
  8709. var newMapping = {
  8710. generated: {
  8711. line: mapping.generatedLine,
  8712. column: mapping.generatedColumn
  8713. }
  8714. };
  8715. if (mapping.source != null) {
  8716. newMapping.source = mapping.source;
  8717. if (sourceRoot != null) {
  8718. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8719. }
  8720. newMapping.original = {
  8721. line: mapping.originalLine,
  8722. column: mapping.originalColumn
  8723. };
  8724. if (mapping.name != null) {
  8725. newMapping.name = mapping.name;
  8726. }
  8727. }
  8728. generator.addMapping(newMapping);
  8729. });
  8730. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8731. var sourceRelative = sourceFile;
  8732. if (sourceRoot !== null) {
  8733. sourceRelative = util.relative(sourceRoot, sourceFile);
  8734. }
  8735. if (!generator._sources.has(sourceRelative)) {
  8736. generator._sources.add(sourceRelative);
  8737. }
  8738. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8739. if (content != null) {
  8740. generator.setSourceContent(sourceFile, content);
  8741. }
  8742. });
  8743. return generator;
  8744. };
  8745. /**
  8746. * Add a single mapping from original source line and column to the generated
  8747. * source's line and column for this source map being created. The mapping
  8748. * object should have the following properties:
  8749. *
  8750. * - generated: An object with the generated line and column positions.
  8751. * - original: An object with the original line and column positions.
  8752. * - source: The original source file (relative to the sourceRoot).
  8753. * - name: An optional original token name for this mapping.
  8754. */
  8755. SourceMapGenerator.prototype.addMapping =
  8756. function SourceMapGenerator_addMapping(aArgs) {
  8757. var generated = util.getArg(aArgs, 'generated');
  8758. var original = util.getArg(aArgs, 'original', null);
  8759. var source = util.getArg(aArgs, 'source', null);
  8760. var name = util.getArg(aArgs, 'name', null);
  8761. if (!this._skipValidation) {
  8762. this._validateMapping(generated, original, source, name);
  8763. }
  8764. if (source != null) {
  8765. source = String(source);
  8766. if (!this._sources.has(source)) {
  8767. this._sources.add(source);
  8768. }
  8769. }
  8770. if (name != null) {
  8771. name = String(name);
  8772. if (!this._names.has(name)) {
  8773. this._names.add(name);
  8774. }
  8775. }
  8776. this._mappings.add({
  8777. generatedLine: generated.line,
  8778. generatedColumn: generated.column,
  8779. originalLine: original != null && original.line,
  8780. originalColumn: original != null && original.column,
  8781. source: source,
  8782. name: name
  8783. });
  8784. };
  8785. /**
  8786. * Set the source content for a source file.
  8787. */
  8788. SourceMapGenerator.prototype.setSourceContent =
  8789. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8790. var source = aSourceFile;
  8791. if (this._sourceRoot != null) {
  8792. source = util.relative(this._sourceRoot, source);
  8793. }
  8794. if (aSourceContent != null) {
  8795. // Add the source content to the _sourcesContents map.
  8796. // Create a new _sourcesContents map if the property is null.
  8797. if (!this._sourcesContents) {
  8798. this._sourcesContents = Object.create(null);
  8799. }
  8800. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8801. } else if (this._sourcesContents) {
  8802. // Remove the source file from the _sourcesContents map.
  8803. // If the _sourcesContents map is empty, set the property to null.
  8804. delete this._sourcesContents[util.toSetString(source)];
  8805. if (Object.keys(this._sourcesContents).length === 0) {
  8806. this._sourcesContents = null;
  8807. }
  8808. }
  8809. };
  8810. /**
  8811. * Applies the mappings of a sub-source-map for a specific source file to the
  8812. * source map being generated. Each mapping to the supplied source file is
  8813. * rewritten using the supplied source map. Note: The resolution for the
  8814. * resulting mappings is the minimium of this map and the supplied map.
  8815. *
  8816. * @param aSourceMapConsumer The source map to be applied.
  8817. * @param aSourceFile Optional. The filename of the source file.
  8818. * If omitted, SourceMapConsumer's file property will be used.
  8819. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8820. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8821. * This parameter is needed when the two source maps aren't in the same
  8822. * directory, and the source map to be applied contains relative source
  8823. * paths. If so, those relative source paths need to be rewritten
  8824. * relative to the SourceMapGenerator.
  8825. */
  8826. SourceMapGenerator.prototype.applySourceMap =
  8827. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8828. var sourceFile = aSourceFile;
  8829. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8830. if (aSourceFile == null) {
  8831. if (aSourceMapConsumer.file == null) {
  8832. throw new Error(
  8833. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8834. 'or the source map\'s "file" property. Both were omitted.'
  8835. );
  8836. }
  8837. sourceFile = aSourceMapConsumer.file;
  8838. }
  8839. var sourceRoot = this._sourceRoot;
  8840. // Make "sourceFile" relative if an absolute Url is passed.
  8841. if (sourceRoot != null) {
  8842. sourceFile = util.relative(sourceRoot, sourceFile);
  8843. }
  8844. // Applying the SourceMap can add and remove items from the sources and
  8845. // the names array.
  8846. var newSources = new ArraySet();
  8847. var newNames = new ArraySet();
  8848. // Find mappings for the "sourceFile"
  8849. this._mappings.unsortedForEach(function (mapping) {
  8850. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8851. // Check if it can be mapped by the source map, then update the mapping.
  8852. var original = aSourceMapConsumer.originalPositionFor({
  8853. line: mapping.originalLine,
  8854. column: mapping.originalColumn
  8855. });
  8856. if (original.source != null) {
  8857. // Copy mapping
  8858. mapping.source = original.source;
  8859. if (aSourceMapPath != null) {
  8860. mapping.source = util.join(aSourceMapPath, mapping.source);
  8861. }
  8862. if (sourceRoot != null) {
  8863. mapping.source = util.relative(sourceRoot, mapping.source);
  8864. }
  8865. mapping.originalLine = original.line;
  8866. mapping.originalColumn = original.column;
  8867. if (original.name != null) {
  8868. mapping.name = original.name;
  8869. }
  8870. }
  8871. }
  8872. var source = mapping.source;
  8873. if (source != null && !newSources.has(source)) {
  8874. newSources.add(source);
  8875. }
  8876. var name = mapping.name;
  8877. if (name != null && !newNames.has(name)) {
  8878. newNames.add(name);
  8879. }
  8880. }, this);
  8881. this._sources = newSources;
  8882. this._names = newNames;
  8883. // Copy sourcesContents of applied map.
  8884. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8885. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8886. if (content != null) {
  8887. if (aSourceMapPath != null) {
  8888. sourceFile = util.join(aSourceMapPath, sourceFile);
  8889. }
  8890. if (sourceRoot != null) {
  8891. sourceFile = util.relative(sourceRoot, sourceFile);
  8892. }
  8893. this.setSourceContent(sourceFile, content);
  8894. }
  8895. }, this);
  8896. };
  8897. /**
  8898. * A mapping can have one of the three levels of data:
  8899. *
  8900. * 1. Just the generated position.
  8901. * 2. The Generated position, original position, and original source.
  8902. * 3. Generated and original position, original source, as well as a name
  8903. * token.
  8904. *
  8905. * To maintain consistency, we validate that any new mapping being added falls
  8906. * in to one of these categories.
  8907. */
  8908. SourceMapGenerator.prototype._validateMapping =
  8909. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8910. aName) {
  8911. // When aOriginal is truthy but has empty values for .line and .column,
  8912. // it is most likely a programmer error. In this case we throw a very
  8913. // specific error message to try to guide them the right way.
  8914. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8915. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8916. throw new Error(
  8917. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8918. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8919. 'null for the original mapping instead of an object with empty or null values.'
  8920. );
  8921. }
  8922. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8923. && aGenerated.line > 0 && aGenerated.column >= 0
  8924. && !aOriginal && !aSource && !aName) {
  8925. // Case 1.
  8926. return;
  8927. }
  8928. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8929. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8930. && aGenerated.line > 0 && aGenerated.column >= 0
  8931. && aOriginal.line > 0 && aOriginal.column >= 0
  8932. && aSource) {
  8933. // Cases 2 and 3.
  8934. return;
  8935. }
  8936. else {
  8937. throw new Error('Invalid mapping: ' + JSON.stringify({
  8938. generated: aGenerated,
  8939. source: aSource,
  8940. original: aOriginal,
  8941. name: aName
  8942. }));
  8943. }
  8944. };
  8945. /**
  8946. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8947. * specified by the source map format.
  8948. */
  8949. SourceMapGenerator.prototype._serializeMappings =
  8950. function SourceMapGenerator_serializeMappings() {
  8951. var previousGeneratedColumn = 0;
  8952. var previousGeneratedLine = 1;
  8953. var previousOriginalColumn = 0;
  8954. var previousOriginalLine = 0;
  8955. var previousName = 0;
  8956. var previousSource = 0;
  8957. var result = '';
  8958. var next;
  8959. var mapping;
  8960. var nameIdx;
  8961. var sourceIdx;
  8962. var mappings = this._mappings.toArray();
  8963. for (var i = 0, len = mappings.length; i < len; i++) {
  8964. mapping = mappings[i];
  8965. next = '';
  8966. if (mapping.generatedLine !== previousGeneratedLine) {
  8967. previousGeneratedColumn = 0;
  8968. while (mapping.generatedLine !== previousGeneratedLine) {
  8969. next += ';';
  8970. previousGeneratedLine++;
  8971. }
  8972. }
  8973. else {
  8974. if (i > 0) {
  8975. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8976. continue;
  8977. }
  8978. next += ',';
  8979. }
  8980. }
  8981. next += base64VLQ.encode(mapping.generatedColumn
  8982. - previousGeneratedColumn);
  8983. previousGeneratedColumn = mapping.generatedColumn;
  8984. if (mapping.source != null) {
  8985. sourceIdx = this._sources.indexOf(mapping.source);
  8986. next += base64VLQ.encode(sourceIdx - previousSource);
  8987. previousSource = sourceIdx;
  8988. // lines are stored 0-based in SourceMap spec version 3
  8989. next += base64VLQ.encode(mapping.originalLine - 1
  8990. - previousOriginalLine);
  8991. previousOriginalLine = mapping.originalLine - 1;
  8992. next += base64VLQ.encode(mapping.originalColumn
  8993. - previousOriginalColumn);
  8994. previousOriginalColumn = mapping.originalColumn;
  8995. if (mapping.name != null) {
  8996. nameIdx = this._names.indexOf(mapping.name);
  8997. next += base64VLQ.encode(nameIdx - previousName);
  8998. previousName = nameIdx;
  8999. }
  9000. }
  9001. result += next;
  9002. }
  9003. return result;
  9004. };
  9005. SourceMapGenerator.prototype._generateSourcesContent =
  9006. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  9007. return aSources.map(function (source) {
  9008. if (!this._sourcesContents) {
  9009. return null;
  9010. }
  9011. if (aSourceRoot != null) {
  9012. source = util.relative(aSourceRoot, source);
  9013. }
  9014. var key = util.toSetString(source);
  9015. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  9016. ? this._sourcesContents[key]
  9017. : null;
  9018. }, this);
  9019. };
  9020. /**
  9021. * Externalize the source map.
  9022. */
  9023. SourceMapGenerator.prototype.toJSON =
  9024. function SourceMapGenerator_toJSON() {
  9025. var map = {
  9026. version: this._version,
  9027. sources: this._sources.toArray(),
  9028. names: this._names.toArray(),
  9029. mappings: this._serializeMappings()
  9030. };
  9031. if (this._file != null) {
  9032. map.file = this._file;
  9033. }
  9034. if (this._sourceRoot != null) {
  9035. map.sourceRoot = this._sourceRoot;
  9036. }
  9037. if (this._sourcesContents) {
  9038. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  9039. }
  9040. return map;
  9041. };
  9042. /**
  9043. * Render the source map being generated to a string.
  9044. */
  9045. SourceMapGenerator.prototype.toString =
  9046. function SourceMapGenerator_toString() {
  9047. return JSON.stringify(this.toJSON());
  9048. };
  9049. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  9050. return sourceMapGenerator;
  9051. }
  9052. var sourceMapConsumer = {};
  9053. var binarySearch = {};
  9054. /* -*- Mode: js; js-indent-level: 2; -*- */
  9055. var hasRequiredBinarySearch;
  9056. function requireBinarySearch () {
  9057. if (hasRequiredBinarySearch) return binarySearch;
  9058. hasRequiredBinarySearch = 1;
  9059. (function (exports) {
  9060. /*
  9061. * Copyright 2011 Mozilla Foundation and contributors
  9062. * Licensed under the New BSD license. See LICENSE or:
  9063. * http://opensource.org/licenses/BSD-3-Clause
  9064. */
  9065. exports.GREATEST_LOWER_BOUND = 1;
  9066. exports.LEAST_UPPER_BOUND = 2;
  9067. /**
  9068. * Recursive implementation of binary search.
  9069. *
  9070. * @param aLow Indices here and lower do not contain the needle.
  9071. * @param aHigh Indices here and higher do not contain the needle.
  9072. * @param aNeedle The element being searched for.
  9073. * @param aHaystack The non-empty array being searched.
  9074. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  9075. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9076. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9077. * closest element that is smaller than or greater than the one we are
  9078. * searching for, respectively, if the exact element cannot be found.
  9079. */
  9080. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  9081. // This function terminates when one of the following is true:
  9082. //
  9083. // 1. We find the exact element we are looking for.
  9084. //
  9085. // 2. We did not find the exact element, but we can return the index of
  9086. // the next-closest element.
  9087. //
  9088. // 3. We did not find the exact element, and there is no next-closest
  9089. // element than the one we are searching for, so we return -1.
  9090. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  9091. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  9092. if (cmp === 0) {
  9093. // Found the element we are looking for.
  9094. return mid;
  9095. }
  9096. else if (cmp > 0) {
  9097. // Our needle is greater than aHaystack[mid].
  9098. if (aHigh - mid > 1) {
  9099. // The element is in the upper half.
  9100. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  9101. }
  9102. // The exact needle element was not found in this haystack. Determine if
  9103. // we are in termination case (3) or (2) and return the appropriate thing.
  9104. if (aBias == exports.LEAST_UPPER_BOUND) {
  9105. return aHigh < aHaystack.length ? aHigh : -1;
  9106. } else {
  9107. return mid;
  9108. }
  9109. }
  9110. else {
  9111. // Our needle is less than aHaystack[mid].
  9112. if (mid - aLow > 1) {
  9113. // The element is in the lower half.
  9114. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  9115. }
  9116. // we are in termination case (3) or (2) and return the appropriate thing.
  9117. if (aBias == exports.LEAST_UPPER_BOUND) {
  9118. return mid;
  9119. } else {
  9120. return aLow < 0 ? -1 : aLow;
  9121. }
  9122. }
  9123. }
  9124. /**
  9125. * This is an implementation of binary search which will always try and return
  9126. * the index of the closest element if there is no exact hit. This is because
  9127. * mappings between original and generated line/col pairs are single points,
  9128. * and there is an implicit region between each of them, so a miss just means
  9129. * that you aren't on the very start of a region.
  9130. *
  9131. * @param aNeedle The element you are looking for.
  9132. * @param aHaystack The array that is being searched.
  9133. * @param aCompare A function which takes the needle and an element in the
  9134. * array and returns -1, 0, or 1 depending on whether the needle is less
  9135. * than, equal to, or greater than the element, respectively.
  9136. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9137. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9138. * closest element that is smaller than or greater than the one we are
  9139. * searching for, respectively, if the exact element cannot be found.
  9140. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  9141. */
  9142. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  9143. if (aHaystack.length === 0) {
  9144. return -1;
  9145. }
  9146. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  9147. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  9148. if (index < 0) {
  9149. return -1;
  9150. }
  9151. // We have found either the exact element, or the next-closest element than
  9152. // the one we are searching for. However, there may be more than one such
  9153. // element. Make sure we always return the smallest of these.
  9154. while (index - 1 >= 0) {
  9155. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  9156. break;
  9157. }
  9158. --index;
  9159. }
  9160. return index;
  9161. };
  9162. } (binarySearch));
  9163. return binarySearch;
  9164. }
  9165. var quickSort = {};
  9166. /* -*- Mode: js; js-indent-level: 2; -*- */
  9167. var hasRequiredQuickSort;
  9168. function requireQuickSort () {
  9169. if (hasRequiredQuickSort) return quickSort;
  9170. hasRequiredQuickSort = 1;
  9171. /*
  9172. * Copyright 2011 Mozilla Foundation and contributors
  9173. * Licensed under the New BSD license. See LICENSE or:
  9174. * http://opensource.org/licenses/BSD-3-Clause
  9175. */
  9176. // It turns out that some (most?) JavaScript engines don't self-host
  9177. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9178. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9179. // custom comparator function, calling back and forth between the VM's C++ and
  9180. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9181. // worse generated code for the comparator function than would be optimal. In
  9182. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9183. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9184. // a ~3500ms mean speed-up in `bench/bench.html`.
  9185. /**
  9186. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9187. *
  9188. * @param {Array} ary
  9189. * The array.
  9190. * @param {Number} x
  9191. * The index of the first item.
  9192. * @param {Number} y
  9193. * The index of the second item.
  9194. */
  9195. function swap(ary, x, y) {
  9196. var temp = ary[x];
  9197. ary[x] = ary[y];
  9198. ary[y] = temp;
  9199. }
  9200. /**
  9201. * Returns a random integer within the range `low .. high` inclusive.
  9202. *
  9203. * @param {Number} low
  9204. * The lower bound on the range.
  9205. * @param {Number} high
  9206. * The upper bound on the range.
  9207. */
  9208. function randomIntInRange(low, high) {
  9209. return Math.round(low + (Math.random() * (high - low)));
  9210. }
  9211. /**
  9212. * The Quick Sort algorithm.
  9213. *
  9214. * @param {Array} ary
  9215. * An array to sort.
  9216. * @param {function} comparator
  9217. * Function to use to compare two items.
  9218. * @param {Number} p
  9219. * Start index of the array
  9220. * @param {Number} r
  9221. * End index of the array
  9222. */
  9223. function doQuickSort(ary, comparator, p, r) {
  9224. // If our lower bound is less than our upper bound, we (1) partition the
  9225. // array into two pieces and (2) recurse on each half. If it is not, this is
  9226. // the empty array and our base case.
  9227. if (p < r) {
  9228. // (1) Partitioning.
  9229. //
  9230. // The partitioning chooses a pivot between `p` and `r` and moves all
  9231. // elements that are less than or equal to the pivot to the before it, and
  9232. // all the elements that are greater than it after it. The effect is that
  9233. // once partition is done, the pivot is in the exact place it will be when
  9234. // the array is put in sorted order, and it will not need to be moved
  9235. // again. This runs in O(n) time.
  9236. // Always choose a random pivot so that an input array which is reverse
  9237. // sorted does not cause O(n^2) running time.
  9238. var pivotIndex = randomIntInRange(p, r);
  9239. var i = p - 1;
  9240. swap(ary, pivotIndex, r);
  9241. var pivot = ary[r];
  9242. // Immediately after `j` is incremented in this loop, the following hold
  9243. // true:
  9244. //
  9245. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9246. //
  9247. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9248. for (var j = p; j < r; j++) {
  9249. if (comparator(ary[j], pivot) <= 0) {
  9250. i += 1;
  9251. swap(ary, i, j);
  9252. }
  9253. }
  9254. swap(ary, i + 1, j);
  9255. var q = i + 1;
  9256. // (2) Recurse on each half.
  9257. doQuickSort(ary, comparator, p, q - 1);
  9258. doQuickSort(ary, comparator, q + 1, r);
  9259. }
  9260. }
  9261. /**
  9262. * Sort the given array in-place with the given comparator function.
  9263. *
  9264. * @param {Array} ary
  9265. * An array to sort.
  9266. * @param {function} comparator
  9267. * Function to use to compare two items.
  9268. */
  9269. quickSort.quickSort = function (ary, comparator) {
  9270. doQuickSort(ary, comparator, 0, ary.length - 1);
  9271. };
  9272. return quickSort;
  9273. }
  9274. /* -*- Mode: js; js-indent-level: 2; -*- */
  9275. var hasRequiredSourceMapConsumer;
  9276. function requireSourceMapConsumer () {
  9277. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9278. hasRequiredSourceMapConsumer = 1;
  9279. /*
  9280. * Copyright 2011 Mozilla Foundation and contributors
  9281. * Licensed under the New BSD license. See LICENSE or:
  9282. * http://opensource.org/licenses/BSD-3-Clause
  9283. */
  9284. var util = /*@__PURE__*/ requireUtil$1();
  9285. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9286. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9287. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9288. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9289. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9290. var sourceMap = aSourceMap;
  9291. if (typeof aSourceMap === 'string') {
  9292. sourceMap = util.parseSourceMapInput(aSourceMap);
  9293. }
  9294. return sourceMap.sections != null
  9295. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9296. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9297. }
  9298. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9299. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9300. };
  9301. /**
  9302. * The version of the source mapping spec that we are consuming.
  9303. */
  9304. SourceMapConsumer.prototype._version = 3;
  9305. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9306. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9307. // are lazily instantiated, accessed via the `_generatedMappings` and
  9308. // `_originalMappings` getters respectively, and we only parse the mappings
  9309. // and create these arrays once queried for a source location. We jump through
  9310. // these hoops because there can be many thousands of mappings, and parsing
  9311. // them is expensive, so we only want to do it if we must.
  9312. //
  9313. // Each object in the arrays is of the form:
  9314. //
  9315. // {
  9316. // generatedLine: The line number in the generated code,
  9317. // generatedColumn: The column number in the generated code,
  9318. // source: The path to the original source file that generated this
  9319. // chunk of code,
  9320. // originalLine: The line number in the original source that
  9321. // corresponds to this chunk of generated code,
  9322. // originalColumn: The column number in the original source that
  9323. // corresponds to this chunk of generated code,
  9324. // name: The name of the original symbol which generated this chunk of
  9325. // code.
  9326. // }
  9327. //
  9328. // All properties except for `generatedLine` and `generatedColumn` can be
  9329. // `null`.
  9330. //
  9331. // `_generatedMappings` is ordered by the generated positions.
  9332. //
  9333. // `_originalMappings` is ordered by the original positions.
  9334. SourceMapConsumer.prototype.__generatedMappings = null;
  9335. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9336. configurable: true,
  9337. enumerable: true,
  9338. get: function () {
  9339. if (!this.__generatedMappings) {
  9340. this._parseMappings(this._mappings, this.sourceRoot);
  9341. }
  9342. return this.__generatedMappings;
  9343. }
  9344. });
  9345. SourceMapConsumer.prototype.__originalMappings = null;
  9346. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9347. configurable: true,
  9348. enumerable: true,
  9349. get: function () {
  9350. if (!this.__originalMappings) {
  9351. this._parseMappings(this._mappings, this.sourceRoot);
  9352. }
  9353. return this.__originalMappings;
  9354. }
  9355. });
  9356. SourceMapConsumer.prototype._charIsMappingSeparator =
  9357. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9358. var c = aStr.charAt(index);
  9359. return c === ";" || c === ",";
  9360. };
  9361. /**
  9362. * Parse the mappings in a string in to a data structure which we can easily
  9363. * query (the ordered arrays in the `this.__generatedMappings` and
  9364. * `this.__originalMappings` properties).
  9365. */
  9366. SourceMapConsumer.prototype._parseMappings =
  9367. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9368. throw new Error("Subclasses must implement _parseMappings");
  9369. };
  9370. SourceMapConsumer.GENERATED_ORDER = 1;
  9371. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9372. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9373. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9374. /**
  9375. * Iterate over each mapping between an original source/line/column and a
  9376. * generated line/column in this source map.
  9377. *
  9378. * @param Function aCallback
  9379. * The function that is called with each mapping.
  9380. * @param Object aContext
  9381. * Optional. If specified, this object will be the value of `this` every
  9382. * time that `aCallback` is called.
  9383. * @param aOrder
  9384. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9385. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9386. * iterate over the mappings sorted by the generated file's line/column
  9387. * order or the original's source/line/column order, respectively. Defaults to
  9388. * `SourceMapConsumer.GENERATED_ORDER`.
  9389. */
  9390. SourceMapConsumer.prototype.eachMapping =
  9391. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9392. var context = aContext || null;
  9393. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9394. var mappings;
  9395. switch (order) {
  9396. case SourceMapConsumer.GENERATED_ORDER:
  9397. mappings = this._generatedMappings;
  9398. break;
  9399. case SourceMapConsumer.ORIGINAL_ORDER:
  9400. mappings = this._originalMappings;
  9401. break;
  9402. default:
  9403. throw new Error("Unknown order of iteration.");
  9404. }
  9405. var sourceRoot = this.sourceRoot;
  9406. mappings.map(function (mapping) {
  9407. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9408. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9409. return {
  9410. source: source,
  9411. generatedLine: mapping.generatedLine,
  9412. generatedColumn: mapping.generatedColumn,
  9413. originalLine: mapping.originalLine,
  9414. originalColumn: mapping.originalColumn,
  9415. name: mapping.name === null ? null : this._names.at(mapping.name)
  9416. };
  9417. }, this).forEach(aCallback, context);
  9418. };
  9419. /**
  9420. * Returns all generated line and column information for the original source,
  9421. * line, and column provided. If no column is provided, returns all mappings
  9422. * corresponding to a either the line we are searching for or the next
  9423. * closest line that has any mappings. Otherwise, returns all mappings
  9424. * corresponding to the given line and either the column we are searching for
  9425. * or the next closest column that has any offsets.
  9426. *
  9427. * The only argument is an object with the following properties:
  9428. *
  9429. * - source: The filename of the original source.
  9430. * - line: The line number in the original source. The line number is 1-based.
  9431. * - column: Optional. the column number in the original source.
  9432. * The column number is 0-based.
  9433. *
  9434. * and an array of objects is returned, each with the following properties:
  9435. *
  9436. * - line: The line number in the generated source, or null. The
  9437. * line number is 1-based.
  9438. * - column: The column number in the generated source, or null.
  9439. * The column number is 0-based.
  9440. */
  9441. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9442. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9443. var line = util.getArg(aArgs, 'line');
  9444. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9445. // returns the index of the closest mapping less than the needle. By
  9446. // setting needle.originalColumn to 0, we thus find the last mapping for
  9447. // the given line, provided such a mapping exists.
  9448. var needle = {
  9449. source: util.getArg(aArgs, 'source'),
  9450. originalLine: line,
  9451. originalColumn: util.getArg(aArgs, 'column', 0)
  9452. };
  9453. needle.source = this._findSourceIndex(needle.source);
  9454. if (needle.source < 0) {
  9455. return [];
  9456. }
  9457. var mappings = [];
  9458. var index = this._findMapping(needle,
  9459. this._originalMappings,
  9460. "originalLine",
  9461. "originalColumn",
  9462. util.compareByOriginalPositions,
  9463. binarySearch.LEAST_UPPER_BOUND);
  9464. if (index >= 0) {
  9465. var mapping = this._originalMappings[index];
  9466. if (aArgs.column === undefined) {
  9467. var originalLine = mapping.originalLine;
  9468. // Iterate until either we run out of mappings, or we run into
  9469. // a mapping for a different line than the one we found. Since
  9470. // mappings are sorted, this is guaranteed to find all mappings for
  9471. // the line we found.
  9472. while (mapping && mapping.originalLine === originalLine) {
  9473. mappings.push({
  9474. line: util.getArg(mapping, 'generatedLine', null),
  9475. column: util.getArg(mapping, 'generatedColumn', null),
  9476. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9477. });
  9478. mapping = this._originalMappings[++index];
  9479. }
  9480. } else {
  9481. var originalColumn = mapping.originalColumn;
  9482. // Iterate until either we run out of mappings, or we run into
  9483. // a mapping for a different line than the one we were searching for.
  9484. // Since mappings are sorted, this is guaranteed to find all mappings for
  9485. // the line we are searching for.
  9486. while (mapping &&
  9487. mapping.originalLine === line &&
  9488. mapping.originalColumn == originalColumn) {
  9489. mappings.push({
  9490. line: util.getArg(mapping, 'generatedLine', null),
  9491. column: util.getArg(mapping, 'generatedColumn', null),
  9492. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9493. });
  9494. mapping = this._originalMappings[++index];
  9495. }
  9496. }
  9497. }
  9498. return mappings;
  9499. };
  9500. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9501. /**
  9502. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9503. * query for information about the original file positions by giving it a file
  9504. * position in the generated source.
  9505. *
  9506. * The first parameter is the raw source map (either as a JSON string, or
  9507. * already parsed to an object). According to the spec, source maps have the
  9508. * following attributes:
  9509. *
  9510. * - version: Which version of the source map spec this map is following.
  9511. * - sources: An array of URLs to the original source files.
  9512. * - names: An array of identifiers which can be referrenced by individual mappings.
  9513. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9514. * - sourcesContent: Optional. An array of contents of the original source files.
  9515. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9516. * - file: Optional. The generated file this source map is associated with.
  9517. *
  9518. * Here is an example source map, taken from the source map spec[0]:
  9519. *
  9520. * {
  9521. * version : 3,
  9522. * file: "out.js",
  9523. * sourceRoot : "",
  9524. * sources: ["foo.js", "bar.js"],
  9525. * names: ["src", "maps", "are", "fun"],
  9526. * mappings: "AA,AB;;ABCDE;"
  9527. * }
  9528. *
  9529. * The second parameter, if given, is a string whose value is the URL
  9530. * at which the source map was found. This URL is used to compute the
  9531. * sources array.
  9532. *
  9533. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9534. */
  9535. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9536. var sourceMap = aSourceMap;
  9537. if (typeof aSourceMap === 'string') {
  9538. sourceMap = util.parseSourceMapInput(aSourceMap);
  9539. }
  9540. var version = util.getArg(sourceMap, 'version');
  9541. var sources = util.getArg(sourceMap, 'sources');
  9542. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9543. // requires the array) to play nice here.
  9544. var names = util.getArg(sourceMap, 'names', []);
  9545. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9546. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9547. var mappings = util.getArg(sourceMap, 'mappings');
  9548. var file = util.getArg(sourceMap, 'file', null);
  9549. // Once again, Sass deviates from the spec and supplies the version as a
  9550. // string rather than a number, so we use loose equality checking here.
  9551. if (version != this._version) {
  9552. throw new Error('Unsupported version: ' + version);
  9553. }
  9554. if (sourceRoot) {
  9555. sourceRoot = util.normalize(sourceRoot);
  9556. }
  9557. sources = sources
  9558. .map(String)
  9559. // Some source maps produce relative source paths like "./foo.js" instead of
  9560. // "foo.js". Normalize these first so that future comparisons will succeed.
  9561. // See bugzil.la/1090768.
  9562. .map(util.normalize)
  9563. // Always ensure that absolute sources are internally stored relative to
  9564. // the source root, if the source root is absolute. Not doing this would
  9565. // be particularly problematic when the source root is a prefix of the
  9566. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9567. .map(function (source) {
  9568. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9569. ? util.relative(sourceRoot, source)
  9570. : source;
  9571. });
  9572. // Pass `true` below to allow duplicate names and sources. While source maps
  9573. // are intended to be compressed and deduplicated, the TypeScript compiler
  9574. // sometimes generates source maps with duplicates in them. See Github issue
  9575. // #72 and bugzil.la/889492.
  9576. this._names = ArraySet.fromArray(names.map(String), true);
  9577. this._sources = ArraySet.fromArray(sources, true);
  9578. this._absoluteSources = this._sources.toArray().map(function (s) {
  9579. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9580. });
  9581. this.sourceRoot = sourceRoot;
  9582. this.sourcesContent = sourcesContent;
  9583. this._mappings = mappings;
  9584. this._sourceMapURL = aSourceMapURL;
  9585. this.file = file;
  9586. }
  9587. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9588. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9589. /**
  9590. * Utility function to find the index of a source. Returns -1 if not
  9591. * found.
  9592. */
  9593. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9594. var relativeSource = aSource;
  9595. if (this.sourceRoot != null) {
  9596. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9597. }
  9598. if (this._sources.has(relativeSource)) {
  9599. return this._sources.indexOf(relativeSource);
  9600. }
  9601. // Maybe aSource is an absolute URL as returned by |sources|. In
  9602. // this case we can't simply undo the transform.
  9603. var i;
  9604. for (i = 0; i < this._absoluteSources.length; ++i) {
  9605. if (this._absoluteSources[i] == aSource) {
  9606. return i;
  9607. }
  9608. }
  9609. return -1;
  9610. };
  9611. /**
  9612. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9613. *
  9614. * @param SourceMapGenerator aSourceMap
  9615. * The source map that will be consumed.
  9616. * @param String aSourceMapURL
  9617. * The URL at which the source map can be found (optional)
  9618. * @returns BasicSourceMapConsumer
  9619. */
  9620. BasicSourceMapConsumer.fromSourceMap =
  9621. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9622. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9623. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9624. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9625. smc.sourceRoot = aSourceMap._sourceRoot;
  9626. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9627. smc.sourceRoot);
  9628. smc.file = aSourceMap._file;
  9629. smc._sourceMapURL = aSourceMapURL;
  9630. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9631. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9632. });
  9633. // Because we are modifying the entries (by converting string sources and
  9634. // names to indices into the sources and names ArraySets), we have to make
  9635. // a copy of the entry or else bad things happen. Shared mutable state
  9636. // strikes again! See github issue #191.
  9637. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9638. var destGeneratedMappings = smc.__generatedMappings = [];
  9639. var destOriginalMappings = smc.__originalMappings = [];
  9640. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9641. var srcMapping = generatedMappings[i];
  9642. var destMapping = new Mapping;
  9643. destMapping.generatedLine = srcMapping.generatedLine;
  9644. destMapping.generatedColumn = srcMapping.generatedColumn;
  9645. if (srcMapping.source) {
  9646. destMapping.source = sources.indexOf(srcMapping.source);
  9647. destMapping.originalLine = srcMapping.originalLine;
  9648. destMapping.originalColumn = srcMapping.originalColumn;
  9649. if (srcMapping.name) {
  9650. destMapping.name = names.indexOf(srcMapping.name);
  9651. }
  9652. destOriginalMappings.push(destMapping);
  9653. }
  9654. destGeneratedMappings.push(destMapping);
  9655. }
  9656. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  9657. return smc;
  9658. };
  9659. /**
  9660. * The version of the source mapping spec that we are consuming.
  9661. */
  9662. BasicSourceMapConsumer.prototype._version = 3;
  9663. /**
  9664. * The list of original sources.
  9665. */
  9666. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9667. get: function () {
  9668. return this._absoluteSources.slice();
  9669. }
  9670. });
  9671. /**
  9672. * Provide the JIT with a nice shape / hidden class.
  9673. */
  9674. function Mapping() {
  9675. this.generatedLine = 0;
  9676. this.generatedColumn = 0;
  9677. this.source = null;
  9678. this.originalLine = null;
  9679. this.originalColumn = null;
  9680. this.name = null;
  9681. }
  9682. /**
  9683. * Parse the mappings in a string in to a data structure which we can easily
  9684. * query (the ordered arrays in the `this.__generatedMappings` and
  9685. * `this.__originalMappings` properties).
  9686. */
  9687. BasicSourceMapConsumer.prototype._parseMappings =
  9688. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9689. var generatedLine = 1;
  9690. var previousGeneratedColumn = 0;
  9691. var previousOriginalLine = 0;
  9692. var previousOriginalColumn = 0;
  9693. var previousSource = 0;
  9694. var previousName = 0;
  9695. var length = aStr.length;
  9696. var index = 0;
  9697. var cachedSegments = {};
  9698. var temp = {};
  9699. var originalMappings = [];
  9700. var generatedMappings = [];
  9701. var mapping, str, segment, end, value;
  9702. while (index < length) {
  9703. if (aStr.charAt(index) === ';') {
  9704. generatedLine++;
  9705. index++;
  9706. previousGeneratedColumn = 0;
  9707. }
  9708. else if (aStr.charAt(index) === ',') {
  9709. index++;
  9710. }
  9711. else {
  9712. mapping = new Mapping();
  9713. mapping.generatedLine = generatedLine;
  9714. // Because each offset is encoded relative to the previous one,
  9715. // many segments often have the same encoding. We can exploit this
  9716. // fact by caching the parsed variable length fields of each segment,
  9717. // allowing us to avoid a second parse if we encounter the same
  9718. // segment again.
  9719. for (end = index; end < length; end++) {
  9720. if (this._charIsMappingSeparator(aStr, end)) {
  9721. break;
  9722. }
  9723. }
  9724. str = aStr.slice(index, end);
  9725. segment = cachedSegments[str];
  9726. if (segment) {
  9727. index += str.length;
  9728. } else {
  9729. segment = [];
  9730. while (index < end) {
  9731. base64VLQ.decode(aStr, index, temp);
  9732. value = temp.value;
  9733. index = temp.rest;
  9734. segment.push(value);
  9735. }
  9736. if (segment.length === 2) {
  9737. throw new Error('Found a source, but no line and column');
  9738. }
  9739. if (segment.length === 3) {
  9740. throw new Error('Found a source and line, but no column');
  9741. }
  9742. cachedSegments[str] = segment;
  9743. }
  9744. // Generated column.
  9745. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9746. previousGeneratedColumn = mapping.generatedColumn;
  9747. if (segment.length > 1) {
  9748. // Original source.
  9749. mapping.source = previousSource + segment[1];
  9750. previousSource += segment[1];
  9751. // Original line.
  9752. mapping.originalLine = previousOriginalLine + segment[2];
  9753. previousOriginalLine = mapping.originalLine;
  9754. // Lines are stored 0-based
  9755. mapping.originalLine += 1;
  9756. // Original column.
  9757. mapping.originalColumn = previousOriginalColumn + segment[3];
  9758. previousOriginalColumn = mapping.originalColumn;
  9759. if (segment.length > 4) {
  9760. // Original name.
  9761. mapping.name = previousName + segment[4];
  9762. previousName += segment[4];
  9763. }
  9764. }
  9765. generatedMappings.push(mapping);
  9766. if (typeof mapping.originalLine === 'number') {
  9767. originalMappings.push(mapping);
  9768. }
  9769. }
  9770. }
  9771. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  9772. this.__generatedMappings = generatedMappings;
  9773. quickSort(originalMappings, util.compareByOriginalPositions);
  9774. this.__originalMappings = originalMappings;
  9775. };
  9776. /**
  9777. * Find the mapping that best matches the hypothetical "needle" mapping that
  9778. * we are searching for in the given "haystack" of mappings.
  9779. */
  9780. BasicSourceMapConsumer.prototype._findMapping =
  9781. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9782. aColumnName, aComparator, aBias) {
  9783. // To return the position we are searching for, we must first find the
  9784. // mapping for the given position and then return the opposite position it
  9785. // points to. Because the mappings are sorted, we can use binary search to
  9786. // find the best mapping.
  9787. if (aNeedle[aLineName] <= 0) {
  9788. throw new TypeError('Line must be greater than or equal to 1, got '
  9789. + aNeedle[aLineName]);
  9790. }
  9791. if (aNeedle[aColumnName] < 0) {
  9792. throw new TypeError('Column must be greater than or equal to 0, got '
  9793. + aNeedle[aColumnName]);
  9794. }
  9795. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9796. };
  9797. /**
  9798. * Compute the last column for each generated mapping. The last column is
  9799. * inclusive.
  9800. */
  9801. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9802. function SourceMapConsumer_computeColumnSpans() {
  9803. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9804. var mapping = this._generatedMappings[index];
  9805. // Mappings do not contain a field for the last generated columnt. We
  9806. // can come up with an optimistic estimate, however, by assuming that
  9807. // mappings are contiguous (i.e. given two consecutive mappings, the
  9808. // first mapping ends where the second one starts).
  9809. if (index + 1 < this._generatedMappings.length) {
  9810. var nextMapping = this._generatedMappings[index + 1];
  9811. if (mapping.generatedLine === nextMapping.generatedLine) {
  9812. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9813. continue;
  9814. }
  9815. }
  9816. // The last mapping for each line spans the entire line.
  9817. mapping.lastGeneratedColumn = Infinity;
  9818. }
  9819. };
  9820. /**
  9821. * Returns the original source, line, and column information for the generated
  9822. * source's line and column positions provided. The only argument is an object
  9823. * with the following properties:
  9824. *
  9825. * - line: The line number in the generated source. The line number
  9826. * is 1-based.
  9827. * - column: The column number in the generated source. The column
  9828. * number is 0-based.
  9829. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9830. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9831. * closest element that is smaller than or greater than the one we are
  9832. * searching for, respectively, if the exact element cannot be found.
  9833. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9834. *
  9835. * and an object is returned with the following properties:
  9836. *
  9837. * - source: The original source file, or null.
  9838. * - line: The line number in the original source, or null. The
  9839. * line number is 1-based.
  9840. * - column: The column number in the original source, or null. The
  9841. * column number is 0-based.
  9842. * - name: The original identifier, or null.
  9843. */
  9844. BasicSourceMapConsumer.prototype.originalPositionFor =
  9845. function SourceMapConsumer_originalPositionFor(aArgs) {
  9846. var needle = {
  9847. generatedLine: util.getArg(aArgs, 'line'),
  9848. generatedColumn: util.getArg(aArgs, 'column')
  9849. };
  9850. var index = this._findMapping(
  9851. needle,
  9852. this._generatedMappings,
  9853. "generatedLine",
  9854. "generatedColumn",
  9855. util.compareByGeneratedPositionsDeflated,
  9856. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9857. );
  9858. if (index >= 0) {
  9859. var mapping = this._generatedMappings[index];
  9860. if (mapping.generatedLine === needle.generatedLine) {
  9861. var source = util.getArg(mapping, 'source', null);
  9862. if (source !== null) {
  9863. source = this._sources.at(source);
  9864. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9865. }
  9866. var name = util.getArg(mapping, 'name', null);
  9867. if (name !== null) {
  9868. name = this._names.at(name);
  9869. }
  9870. return {
  9871. source: source,
  9872. line: util.getArg(mapping, 'originalLine', null),
  9873. column: util.getArg(mapping, 'originalColumn', null),
  9874. name: name
  9875. };
  9876. }
  9877. }
  9878. return {
  9879. source: null,
  9880. line: null,
  9881. column: null,
  9882. name: null
  9883. };
  9884. };
  9885. /**
  9886. * Return true if we have the source content for every source in the source
  9887. * map, false otherwise.
  9888. */
  9889. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9890. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9891. if (!this.sourcesContent) {
  9892. return false;
  9893. }
  9894. return this.sourcesContent.length >= this._sources.size() &&
  9895. !this.sourcesContent.some(function (sc) { return sc == null; });
  9896. };
  9897. /**
  9898. * Returns the original source content. The only argument is the url of the
  9899. * original source file. Returns null if no original source content is
  9900. * available.
  9901. */
  9902. BasicSourceMapConsumer.prototype.sourceContentFor =
  9903. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9904. if (!this.sourcesContent) {
  9905. return null;
  9906. }
  9907. var index = this._findSourceIndex(aSource);
  9908. if (index >= 0) {
  9909. return this.sourcesContent[index];
  9910. }
  9911. var relativeSource = aSource;
  9912. if (this.sourceRoot != null) {
  9913. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9914. }
  9915. var url;
  9916. if (this.sourceRoot != null
  9917. && (url = util.urlParse(this.sourceRoot))) {
  9918. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9919. // many users. We can help them out when they expect file:// URIs to
  9920. // behave like it would if they were running a local HTTP server. See
  9921. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9922. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9923. if (url.scheme == "file"
  9924. && this._sources.has(fileUriAbsPath)) {
  9925. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9926. }
  9927. if ((!url.path || url.path == "/")
  9928. && this._sources.has("/" + relativeSource)) {
  9929. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9930. }
  9931. }
  9932. // This function is used recursively from
  9933. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9934. // don't want to throw if we can't find the source - we just want to
  9935. // return null, so we provide a flag to exit gracefully.
  9936. if (nullOnMissing) {
  9937. return null;
  9938. }
  9939. else {
  9940. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9941. }
  9942. };
  9943. /**
  9944. * Returns the generated line and column information for the original source,
  9945. * line, and column positions provided. The only argument is an object with
  9946. * the following properties:
  9947. *
  9948. * - source: The filename of the original source.
  9949. * - line: The line number in the original source. The line number
  9950. * is 1-based.
  9951. * - column: The column number in the original source. The column
  9952. * number is 0-based.
  9953. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9954. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9955. * closest element that is smaller than or greater than the one we are
  9956. * searching for, respectively, if the exact element cannot be found.
  9957. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9958. *
  9959. * and an object is returned with the following properties:
  9960. *
  9961. * - line: The line number in the generated source, or null. The
  9962. * line number is 1-based.
  9963. * - column: The column number in the generated source, or null.
  9964. * The column number is 0-based.
  9965. */
  9966. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9967. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9968. var source = util.getArg(aArgs, 'source');
  9969. source = this._findSourceIndex(source);
  9970. if (source < 0) {
  9971. return {
  9972. line: null,
  9973. column: null,
  9974. lastColumn: null
  9975. };
  9976. }
  9977. var needle = {
  9978. source: source,
  9979. originalLine: util.getArg(aArgs, 'line'),
  9980. originalColumn: util.getArg(aArgs, 'column')
  9981. };
  9982. var index = this._findMapping(
  9983. needle,
  9984. this._originalMappings,
  9985. "originalLine",
  9986. "originalColumn",
  9987. util.compareByOriginalPositions,
  9988. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9989. );
  9990. if (index >= 0) {
  9991. var mapping = this._originalMappings[index];
  9992. if (mapping.source === needle.source) {
  9993. return {
  9994. line: util.getArg(mapping, 'generatedLine', null),
  9995. column: util.getArg(mapping, 'generatedColumn', null),
  9996. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9997. };
  9998. }
  9999. }
  10000. return {
  10001. line: null,
  10002. column: null,
  10003. lastColumn: null
  10004. };
  10005. };
  10006. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  10007. /**
  10008. * An IndexedSourceMapConsumer instance represents a parsed source map which
  10009. * we can query for information. It differs from BasicSourceMapConsumer in
  10010. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  10011. * input.
  10012. *
  10013. * The first parameter is a raw source map (either as a JSON string, or already
  10014. * parsed to an object). According to the spec for indexed source maps, they
  10015. * have the following attributes:
  10016. *
  10017. * - version: Which version of the source map spec this map is following.
  10018. * - file: Optional. The generated file this source map is associated with.
  10019. * - sections: A list of section definitions.
  10020. *
  10021. * Each value under the "sections" field has two fields:
  10022. * - offset: The offset into the original specified at which this section
  10023. * begins to apply, defined as an object with a "line" and "column"
  10024. * field.
  10025. * - map: A source map definition. This source map could also be indexed,
  10026. * but doesn't have to be.
  10027. *
  10028. * Instead of the "map" field, it's also possible to have a "url" field
  10029. * specifying a URL to retrieve a source map from, but that's currently
  10030. * unsupported.
  10031. *
  10032. * Here's an example source map, taken from the source map spec[0], but
  10033. * modified to omit a section which uses the "url" field.
  10034. *
  10035. * {
  10036. * version : 3,
  10037. * file: "app.js",
  10038. * sections: [{
  10039. * offset: {line:100, column:10},
  10040. * map: {
  10041. * version : 3,
  10042. * file: "section.js",
  10043. * sources: ["foo.js", "bar.js"],
  10044. * names: ["src", "maps", "are", "fun"],
  10045. * mappings: "AAAA,E;;ABCDE;"
  10046. * }
  10047. * }],
  10048. * }
  10049. *
  10050. * The second parameter, if given, is a string whose value is the URL
  10051. * at which the source map was found. This URL is used to compute the
  10052. * sources array.
  10053. *
  10054. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  10055. */
  10056. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  10057. var sourceMap = aSourceMap;
  10058. if (typeof aSourceMap === 'string') {
  10059. sourceMap = util.parseSourceMapInput(aSourceMap);
  10060. }
  10061. var version = util.getArg(sourceMap, 'version');
  10062. var sections = util.getArg(sourceMap, 'sections');
  10063. if (version != this._version) {
  10064. throw new Error('Unsupported version: ' + version);
  10065. }
  10066. this._sources = new ArraySet();
  10067. this._names = new ArraySet();
  10068. var lastOffset = {
  10069. line: -1,
  10070. column: 0
  10071. };
  10072. this._sections = sections.map(function (s) {
  10073. if (s.url) {
  10074. // The url field will require support for asynchronicity.
  10075. // See https://github.com/mozilla/source-map/issues/16
  10076. throw new Error('Support for url field in sections not implemented.');
  10077. }
  10078. var offset = util.getArg(s, 'offset');
  10079. var offsetLine = util.getArg(offset, 'line');
  10080. var offsetColumn = util.getArg(offset, 'column');
  10081. if (offsetLine < lastOffset.line ||
  10082. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  10083. throw new Error('Section offsets must be ordered and non-overlapping.');
  10084. }
  10085. lastOffset = offset;
  10086. return {
  10087. generatedOffset: {
  10088. // The offset fields are 0-based, but we use 1-based indices when
  10089. // encoding/decoding from VLQ.
  10090. generatedLine: offsetLine + 1,
  10091. generatedColumn: offsetColumn + 1
  10092. },
  10093. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  10094. }
  10095. });
  10096. }
  10097. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  10098. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  10099. /**
  10100. * The version of the source mapping spec that we are consuming.
  10101. */
  10102. IndexedSourceMapConsumer.prototype._version = 3;
  10103. /**
  10104. * The list of original sources.
  10105. */
  10106. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  10107. get: function () {
  10108. var sources = [];
  10109. for (var i = 0; i < this._sections.length; i++) {
  10110. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  10111. sources.push(this._sections[i].consumer.sources[j]);
  10112. }
  10113. }
  10114. return sources;
  10115. }
  10116. });
  10117. /**
  10118. * Returns the original source, line, and column information for the generated
  10119. * source's line and column positions provided. The only argument is an object
  10120. * with the following properties:
  10121. *
  10122. * - line: The line number in the generated source. The line number
  10123. * is 1-based.
  10124. * - column: The column number in the generated source. The column
  10125. * number is 0-based.
  10126. *
  10127. * and an object is returned with the following properties:
  10128. *
  10129. * - source: The original source file, or null.
  10130. * - line: The line number in the original source, or null. The
  10131. * line number is 1-based.
  10132. * - column: The column number in the original source, or null. The
  10133. * column number is 0-based.
  10134. * - name: The original identifier, or null.
  10135. */
  10136. IndexedSourceMapConsumer.prototype.originalPositionFor =
  10137. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  10138. var needle = {
  10139. generatedLine: util.getArg(aArgs, 'line'),
  10140. generatedColumn: util.getArg(aArgs, 'column')
  10141. };
  10142. // Find the section containing the generated position we're trying to map
  10143. // to an original position.
  10144. var sectionIndex = binarySearch.search(needle, this._sections,
  10145. function(needle, section) {
  10146. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  10147. if (cmp) {
  10148. return cmp;
  10149. }
  10150. return (needle.generatedColumn -
  10151. section.generatedOffset.generatedColumn);
  10152. });
  10153. var section = this._sections[sectionIndex];
  10154. if (!section) {
  10155. return {
  10156. source: null,
  10157. line: null,
  10158. column: null,
  10159. name: null
  10160. };
  10161. }
  10162. return section.consumer.originalPositionFor({
  10163. line: needle.generatedLine -
  10164. (section.generatedOffset.generatedLine - 1),
  10165. column: needle.generatedColumn -
  10166. (section.generatedOffset.generatedLine === needle.generatedLine
  10167. ? section.generatedOffset.generatedColumn - 1
  10168. : 0),
  10169. bias: aArgs.bias
  10170. });
  10171. };
  10172. /**
  10173. * Return true if we have the source content for every source in the source
  10174. * map, false otherwise.
  10175. */
  10176. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10177. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10178. return this._sections.every(function (s) {
  10179. return s.consumer.hasContentsOfAllSources();
  10180. });
  10181. };
  10182. /**
  10183. * Returns the original source content. The only argument is the url of the
  10184. * original source file. Returns null if no original source content is
  10185. * available.
  10186. */
  10187. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10188. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10189. for (var i = 0; i < this._sections.length; i++) {
  10190. var section = this._sections[i];
  10191. var content = section.consumer.sourceContentFor(aSource, true);
  10192. if (content) {
  10193. return content;
  10194. }
  10195. }
  10196. if (nullOnMissing) {
  10197. return null;
  10198. }
  10199. else {
  10200. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10201. }
  10202. };
  10203. /**
  10204. * Returns the generated line and column information for the original source,
  10205. * line, and column positions provided. The only argument is an object with
  10206. * the following properties:
  10207. *
  10208. * - source: The filename of the original source.
  10209. * - line: The line number in the original source. The line number
  10210. * is 1-based.
  10211. * - column: The column number in the original source. The column
  10212. * number is 0-based.
  10213. *
  10214. * and an object is returned with the following properties:
  10215. *
  10216. * - line: The line number in the generated source, or null. The
  10217. * line number is 1-based.
  10218. * - column: The column number in the generated source, or null.
  10219. * The column number is 0-based.
  10220. */
  10221. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10222. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10223. for (var i = 0; i < this._sections.length; i++) {
  10224. var section = this._sections[i];
  10225. // Only consider this section if the requested source is in the list of
  10226. // sources of the consumer.
  10227. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10228. continue;
  10229. }
  10230. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10231. if (generatedPosition) {
  10232. var ret = {
  10233. line: generatedPosition.line +
  10234. (section.generatedOffset.generatedLine - 1),
  10235. column: generatedPosition.column +
  10236. (section.generatedOffset.generatedLine === generatedPosition.line
  10237. ? section.generatedOffset.generatedColumn - 1
  10238. : 0)
  10239. };
  10240. return ret;
  10241. }
  10242. }
  10243. return {
  10244. line: null,
  10245. column: null
  10246. };
  10247. };
  10248. /**
  10249. * Parse the mappings in a string in to a data structure which we can easily
  10250. * query (the ordered arrays in the `this.__generatedMappings` and
  10251. * `this.__originalMappings` properties).
  10252. */
  10253. IndexedSourceMapConsumer.prototype._parseMappings =
  10254. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10255. this.__generatedMappings = [];
  10256. this.__originalMappings = [];
  10257. for (var i = 0; i < this._sections.length; i++) {
  10258. var section = this._sections[i];
  10259. var sectionMappings = section.consumer._generatedMappings;
  10260. for (var j = 0; j < sectionMappings.length; j++) {
  10261. var mapping = sectionMappings[j];
  10262. var source = section.consumer._sources.at(mapping.source);
  10263. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10264. this._sources.add(source);
  10265. source = this._sources.indexOf(source);
  10266. var name = null;
  10267. if (mapping.name) {
  10268. name = section.consumer._names.at(mapping.name);
  10269. this._names.add(name);
  10270. name = this._names.indexOf(name);
  10271. }
  10272. // The mappings coming from the consumer for the section have
  10273. // generated positions relative to the start of the section, so we
  10274. // need to offset them to be relative to the start of the concatenated
  10275. // generated file.
  10276. var adjustedMapping = {
  10277. source: source,
  10278. generatedLine: mapping.generatedLine +
  10279. (section.generatedOffset.generatedLine - 1),
  10280. generatedColumn: mapping.generatedColumn +
  10281. (section.generatedOffset.generatedLine === mapping.generatedLine
  10282. ? section.generatedOffset.generatedColumn - 1
  10283. : 0),
  10284. originalLine: mapping.originalLine,
  10285. originalColumn: mapping.originalColumn,
  10286. name: name
  10287. };
  10288. this.__generatedMappings.push(adjustedMapping);
  10289. if (typeof adjustedMapping.originalLine === 'number') {
  10290. this.__originalMappings.push(adjustedMapping);
  10291. }
  10292. }
  10293. }
  10294. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10295. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10296. };
  10297. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10298. return sourceMapConsumer;
  10299. }
  10300. var sourceNode = {};
  10301. /* -*- Mode: js; js-indent-level: 2; -*- */
  10302. var hasRequiredSourceNode;
  10303. function requireSourceNode () {
  10304. if (hasRequiredSourceNode) return sourceNode;
  10305. hasRequiredSourceNode = 1;
  10306. /*
  10307. * Copyright 2011 Mozilla Foundation and contributors
  10308. * Licensed under the New BSD license. See LICENSE or:
  10309. * http://opensource.org/licenses/BSD-3-Clause
  10310. */
  10311. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10312. var util = /*@__PURE__*/ requireUtil$1();
  10313. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10314. // operating systems these days (capturing the result).
  10315. var REGEX_NEWLINE = /(\r?\n)/;
  10316. // Newline character code for charCodeAt() comparisons
  10317. var NEWLINE_CODE = 10;
  10318. // Private symbol for identifying `SourceNode`s when multiple versions of
  10319. // the source-map library are loaded. This MUST NOT CHANGE across
  10320. // versions!
  10321. var isSourceNode = "$$$isSourceNode$$$";
  10322. /**
  10323. * SourceNodes provide a way to abstract over interpolating/concatenating
  10324. * snippets of generated JavaScript source code while maintaining the line and
  10325. * column information associated with the original source code.
  10326. *
  10327. * @param aLine The original line number.
  10328. * @param aColumn The original column number.
  10329. * @param aSource The original source's filename.
  10330. * @param aChunks Optional. An array of strings which are snippets of
  10331. * generated JS, or other SourceNodes.
  10332. * @param aName The original identifier.
  10333. */
  10334. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10335. this.children = [];
  10336. this.sourceContents = {};
  10337. this.line = aLine == null ? null : aLine;
  10338. this.column = aColumn == null ? null : aColumn;
  10339. this.source = aSource == null ? null : aSource;
  10340. this.name = aName == null ? null : aName;
  10341. this[isSourceNode] = true;
  10342. if (aChunks != null) this.add(aChunks);
  10343. }
  10344. /**
  10345. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10346. *
  10347. * @param aGeneratedCode The generated code
  10348. * @param aSourceMapConsumer The SourceMap for the generated code
  10349. * @param aRelativePath Optional. The path that relative sources in the
  10350. * SourceMapConsumer should be relative to.
  10351. */
  10352. SourceNode.fromStringWithSourceMap =
  10353. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10354. // The SourceNode we want to fill with the generated code
  10355. // and the SourceMap
  10356. var node = new SourceNode();
  10357. // All even indices of this array are one line of the generated code,
  10358. // while all odd indices are the newlines between two adjacent lines
  10359. // (since `REGEX_NEWLINE` captures its match).
  10360. // Processed fragments are accessed by calling `shiftNextLine`.
  10361. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10362. var remainingLinesIndex = 0;
  10363. var shiftNextLine = function() {
  10364. var lineContents = getNextLine();
  10365. // The last line of a file might not have a newline.
  10366. var newLine = getNextLine() || "";
  10367. return lineContents + newLine;
  10368. function getNextLine() {
  10369. return remainingLinesIndex < remainingLines.length ?
  10370. remainingLines[remainingLinesIndex++] : undefined;
  10371. }
  10372. };
  10373. // We need to remember the position of "remainingLines"
  10374. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10375. // The generate SourceNodes we need a code range.
  10376. // To extract it current and last mapping is used.
  10377. // Here we store the last mapping.
  10378. var lastMapping = null;
  10379. aSourceMapConsumer.eachMapping(function (mapping) {
  10380. if (lastMapping !== null) {
  10381. // We add the code from "lastMapping" to "mapping":
  10382. // First check if there is a new line in between.
  10383. if (lastGeneratedLine < mapping.generatedLine) {
  10384. // Associate first line with "lastMapping"
  10385. addMappingWithCode(lastMapping, shiftNextLine());
  10386. lastGeneratedLine++;
  10387. lastGeneratedColumn = 0;
  10388. // The remaining code is added without mapping
  10389. } else {
  10390. // There is no new line in between.
  10391. // Associate the code between "lastGeneratedColumn" and
  10392. // "mapping.generatedColumn" with "lastMapping"
  10393. var nextLine = remainingLines[remainingLinesIndex] || '';
  10394. var code = nextLine.substr(0, mapping.generatedColumn -
  10395. lastGeneratedColumn);
  10396. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10397. lastGeneratedColumn);
  10398. lastGeneratedColumn = mapping.generatedColumn;
  10399. addMappingWithCode(lastMapping, code);
  10400. // No more remaining code, continue
  10401. lastMapping = mapping;
  10402. return;
  10403. }
  10404. }
  10405. // We add the generated code until the first mapping
  10406. // to the SourceNode without any mapping.
  10407. // Each line is added as separate string.
  10408. while (lastGeneratedLine < mapping.generatedLine) {
  10409. node.add(shiftNextLine());
  10410. lastGeneratedLine++;
  10411. }
  10412. if (lastGeneratedColumn < mapping.generatedColumn) {
  10413. var nextLine = remainingLines[remainingLinesIndex] || '';
  10414. node.add(nextLine.substr(0, mapping.generatedColumn));
  10415. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10416. lastGeneratedColumn = mapping.generatedColumn;
  10417. }
  10418. lastMapping = mapping;
  10419. }, this);
  10420. // We have processed all mappings.
  10421. if (remainingLinesIndex < remainingLines.length) {
  10422. if (lastMapping) {
  10423. // Associate the remaining code in the current line with "lastMapping"
  10424. addMappingWithCode(lastMapping, shiftNextLine());
  10425. }
  10426. // and add the remaining lines without any mapping
  10427. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10428. }
  10429. // Copy sourcesContent into SourceNode
  10430. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10431. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10432. if (content != null) {
  10433. if (aRelativePath != null) {
  10434. sourceFile = util.join(aRelativePath, sourceFile);
  10435. }
  10436. node.setSourceContent(sourceFile, content);
  10437. }
  10438. });
  10439. return node;
  10440. function addMappingWithCode(mapping, code) {
  10441. if (mapping === null || mapping.source === undefined) {
  10442. node.add(code);
  10443. } else {
  10444. var source = aRelativePath
  10445. ? util.join(aRelativePath, mapping.source)
  10446. : mapping.source;
  10447. node.add(new SourceNode(mapping.originalLine,
  10448. mapping.originalColumn,
  10449. source,
  10450. code,
  10451. mapping.name));
  10452. }
  10453. }
  10454. };
  10455. /**
  10456. * Add a chunk of generated JS to this source node.
  10457. *
  10458. * @param aChunk A string snippet of generated JS code, another instance of
  10459. * SourceNode, or an array where each member is one of those things.
  10460. */
  10461. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10462. if (Array.isArray(aChunk)) {
  10463. aChunk.forEach(function (chunk) {
  10464. this.add(chunk);
  10465. }, this);
  10466. }
  10467. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10468. if (aChunk) {
  10469. this.children.push(aChunk);
  10470. }
  10471. }
  10472. else {
  10473. throw new TypeError(
  10474. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10475. );
  10476. }
  10477. return this;
  10478. };
  10479. /**
  10480. * Add a chunk of generated JS to the beginning of this source node.
  10481. *
  10482. * @param aChunk A string snippet of generated JS code, another instance of
  10483. * SourceNode, or an array where each member is one of those things.
  10484. */
  10485. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10486. if (Array.isArray(aChunk)) {
  10487. for (var i = aChunk.length-1; i >= 0; i--) {
  10488. this.prepend(aChunk[i]);
  10489. }
  10490. }
  10491. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10492. this.children.unshift(aChunk);
  10493. }
  10494. else {
  10495. throw new TypeError(
  10496. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10497. );
  10498. }
  10499. return this;
  10500. };
  10501. /**
  10502. * Walk over the tree of JS snippets in this node and its children. The
  10503. * walking function is called once for each snippet of JS and is passed that
  10504. * snippet and the its original associated source's line/column location.
  10505. *
  10506. * @param aFn The traversal function.
  10507. */
  10508. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10509. var chunk;
  10510. for (var i = 0, len = this.children.length; i < len; i++) {
  10511. chunk = this.children[i];
  10512. if (chunk[isSourceNode]) {
  10513. chunk.walk(aFn);
  10514. }
  10515. else {
  10516. if (chunk !== '') {
  10517. aFn(chunk, { source: this.source,
  10518. line: this.line,
  10519. column: this.column,
  10520. name: this.name });
  10521. }
  10522. }
  10523. }
  10524. };
  10525. /**
  10526. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10527. * each of `this.children`.
  10528. *
  10529. * @param aSep The separator.
  10530. */
  10531. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10532. var newChildren;
  10533. var i;
  10534. var len = this.children.length;
  10535. if (len > 0) {
  10536. newChildren = [];
  10537. for (i = 0; i < len-1; i++) {
  10538. newChildren.push(this.children[i]);
  10539. newChildren.push(aSep);
  10540. }
  10541. newChildren.push(this.children[i]);
  10542. this.children = newChildren;
  10543. }
  10544. return this;
  10545. };
  10546. /**
  10547. * Call String.prototype.replace on the very right-most source snippet. Useful
  10548. * for trimming whitespace from the end of a source node, etc.
  10549. *
  10550. * @param aPattern The pattern to replace.
  10551. * @param aReplacement The thing to replace the pattern with.
  10552. */
  10553. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10554. var lastChild = this.children[this.children.length - 1];
  10555. if (lastChild[isSourceNode]) {
  10556. lastChild.replaceRight(aPattern, aReplacement);
  10557. }
  10558. else if (typeof lastChild === 'string') {
  10559. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10560. }
  10561. else {
  10562. this.children.push(''.replace(aPattern, aReplacement));
  10563. }
  10564. return this;
  10565. };
  10566. /**
  10567. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10568. * in the sourcesContent field.
  10569. *
  10570. * @param aSourceFile The filename of the source file
  10571. * @param aSourceContent The content of the source file
  10572. */
  10573. SourceNode.prototype.setSourceContent =
  10574. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10575. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10576. };
  10577. /**
  10578. * Walk over the tree of SourceNodes. The walking function is called for each
  10579. * source file content and is passed the filename and source content.
  10580. *
  10581. * @param aFn The traversal function.
  10582. */
  10583. SourceNode.prototype.walkSourceContents =
  10584. function SourceNode_walkSourceContents(aFn) {
  10585. for (var i = 0, len = this.children.length; i < len; i++) {
  10586. if (this.children[i][isSourceNode]) {
  10587. this.children[i].walkSourceContents(aFn);
  10588. }
  10589. }
  10590. var sources = Object.keys(this.sourceContents);
  10591. for (var i = 0, len = sources.length; i < len; i++) {
  10592. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10593. }
  10594. };
  10595. /**
  10596. * Return the string representation of this source node. Walks over the tree
  10597. * and concatenates all the various snippets together to one string.
  10598. */
  10599. SourceNode.prototype.toString = function SourceNode_toString() {
  10600. var str = "";
  10601. this.walk(function (chunk) {
  10602. str += chunk;
  10603. });
  10604. return str;
  10605. };
  10606. /**
  10607. * Returns the string representation of this source node along with a source
  10608. * map.
  10609. */
  10610. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10611. var generated = {
  10612. code: "",
  10613. line: 1,
  10614. column: 0
  10615. };
  10616. var map = new SourceMapGenerator(aArgs);
  10617. var sourceMappingActive = false;
  10618. var lastOriginalSource = null;
  10619. var lastOriginalLine = null;
  10620. var lastOriginalColumn = null;
  10621. var lastOriginalName = null;
  10622. this.walk(function (chunk, original) {
  10623. generated.code += chunk;
  10624. if (original.source !== null
  10625. && original.line !== null
  10626. && original.column !== null) {
  10627. if(lastOriginalSource !== original.source
  10628. || lastOriginalLine !== original.line
  10629. || lastOriginalColumn !== original.column
  10630. || lastOriginalName !== original.name) {
  10631. map.addMapping({
  10632. source: original.source,
  10633. original: {
  10634. line: original.line,
  10635. column: original.column
  10636. },
  10637. generated: {
  10638. line: generated.line,
  10639. column: generated.column
  10640. },
  10641. name: original.name
  10642. });
  10643. }
  10644. lastOriginalSource = original.source;
  10645. lastOriginalLine = original.line;
  10646. lastOriginalColumn = original.column;
  10647. lastOriginalName = original.name;
  10648. sourceMappingActive = true;
  10649. } else if (sourceMappingActive) {
  10650. map.addMapping({
  10651. generated: {
  10652. line: generated.line,
  10653. column: generated.column
  10654. }
  10655. });
  10656. lastOriginalSource = null;
  10657. sourceMappingActive = false;
  10658. }
  10659. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10660. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10661. generated.line++;
  10662. generated.column = 0;
  10663. // Mappings end at eol
  10664. if (idx + 1 === length) {
  10665. lastOriginalSource = null;
  10666. sourceMappingActive = false;
  10667. } else if (sourceMappingActive) {
  10668. map.addMapping({
  10669. source: original.source,
  10670. original: {
  10671. line: original.line,
  10672. column: original.column
  10673. },
  10674. generated: {
  10675. line: generated.line,
  10676. column: generated.column
  10677. },
  10678. name: original.name
  10679. });
  10680. }
  10681. } else {
  10682. generated.column++;
  10683. }
  10684. }
  10685. });
  10686. this.walkSourceContents(function (sourceFile, sourceContent) {
  10687. map.setSourceContent(sourceFile, sourceContent);
  10688. });
  10689. return { code: generated.code, map: map };
  10690. };
  10691. sourceNode.SourceNode = SourceNode;
  10692. return sourceNode;
  10693. }
  10694. /*
  10695. * Copyright 2009-2011 Mozilla Foundation and contributors
  10696. * Licensed under the New BSD license. See LICENSE.txt or:
  10697. * http://opensource.org/licenses/BSD-3-Clause
  10698. */
  10699. var hasRequiredSourceMap;
  10700. function requireSourceMap () {
  10701. if (hasRequiredSourceMap) return sourceMap;
  10702. hasRequiredSourceMap = 1;
  10703. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10704. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  10705. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  10706. return sourceMap;
  10707. }
  10708. var mergeSourceMap;
  10709. var hasRequiredMergeSourceMap;
  10710. function requireMergeSourceMap () {
  10711. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  10712. hasRequiredMergeSourceMap = 1;
  10713. var sourceMap = /*@__PURE__*/ requireSourceMap();
  10714. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10715. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10716. mergeSourceMap = merge;
  10717. /**
  10718. * Merge old source map and new source map and return merged.
  10719. * If old or new source map value is falsy, return another one as it is.
  10720. *
  10721. * @param {object|string} [oldMap] old source map object
  10722. * @param {object|string} [newmap] new source map object
  10723. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10724. */
  10725. function merge(oldMap, newMap) {
  10726. if (!oldMap) return newMap
  10727. if (!newMap) return oldMap
  10728. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10729. var newMapConsumer = new SourceMapConsumer(newMap);
  10730. var mergedMapGenerator = new SourceMapGenerator();
  10731. // iterate on new map and overwrite original position of new map with one of old map
  10732. newMapConsumer.eachMapping(function(m) {
  10733. // pass when `originalLine` is null.
  10734. // It occurs in case that the node does not have origin in original code.
  10735. if (m.originalLine == null) return
  10736. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10737. line: m.originalLine,
  10738. column: m.originalColumn
  10739. });
  10740. if (origPosInOldMap.source == null) return
  10741. mergedMapGenerator.addMapping({
  10742. original: {
  10743. line: origPosInOldMap.line,
  10744. column: origPosInOldMap.column
  10745. },
  10746. generated: {
  10747. line: m.generatedLine,
  10748. column: m.generatedColumn
  10749. },
  10750. source: origPosInOldMap.source,
  10751. name: origPosInOldMap.name
  10752. });
  10753. });
  10754. var consumers = [oldMapConsumer, newMapConsumer];
  10755. consumers.forEach(function(consumer) {
  10756. consumer.sources.forEach(function(sourceFile) {
  10757. mergedMapGenerator._sources.add(sourceFile);
  10758. var sourceContent = consumer.sourceContentFor(sourceFile);
  10759. if (sourceContent != null) {
  10760. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10761. }
  10762. });
  10763. });
  10764. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10765. mergedMapGenerator._file = oldMap.file;
  10766. return JSON.parse(mergedMapGenerator.toString())
  10767. }
  10768. return mergeSourceMap;
  10769. }
  10770. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  10771. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  10772. const scss = (source, map, options, load = require) => {
  10773. const nodeSass = load("sass");
  10774. const { compileString, renderSync } = nodeSass;
  10775. const data = getSource(source, options.filename, options.additionalData);
  10776. let css;
  10777. let dependencies;
  10778. let sourceMap;
  10779. try {
  10780. if (compileString) {
  10781. const { pathToFileURL, fileURLToPath } = load("url");
  10782. const result = compileString(data, {
  10783. ...options,
  10784. url: pathToFileURL(options.filename),
  10785. sourceMap: !!map
  10786. });
  10787. css = result.css;
  10788. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  10789. sourceMap = map ? result.sourceMap : void 0;
  10790. } else {
  10791. const result = renderSync({
  10792. ...options,
  10793. data,
  10794. file: options.filename,
  10795. outFile: options.filename,
  10796. sourceMap: !!map
  10797. });
  10798. css = result.css.toString();
  10799. dependencies = result.stats.includedFiles;
  10800. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  10801. }
  10802. if (map) {
  10803. return {
  10804. code: css,
  10805. errors: [],
  10806. dependencies,
  10807. map: merge(map, sourceMap)
  10808. };
  10809. }
  10810. return { code: css, errors: [], dependencies };
  10811. } catch (e) {
  10812. return { code: "", errors: [e], dependencies: [] };
  10813. }
  10814. };
  10815. const sass = (source, map, options, load) => scss(
  10816. source,
  10817. map,
  10818. {
  10819. ...options,
  10820. indentedSyntax: true
  10821. },
  10822. load
  10823. );
  10824. const less = (source, map, options, load = require) => {
  10825. const nodeLess = load("less");
  10826. let result;
  10827. let error = null;
  10828. nodeLess.render(
  10829. getSource(source, options.filename, options.additionalData),
  10830. { ...options, syncImport: true },
  10831. (err, output) => {
  10832. error = err;
  10833. result = output;
  10834. }
  10835. );
  10836. if (error) return { code: "", errors: [error], dependencies: [] };
  10837. const dependencies = result.imports;
  10838. if (map) {
  10839. return {
  10840. code: result.css.toString(),
  10841. map: merge(map, result.map),
  10842. errors: [],
  10843. dependencies
  10844. };
  10845. }
  10846. return {
  10847. code: result.css.toString(),
  10848. errors: [],
  10849. dependencies
  10850. };
  10851. };
  10852. const styl = (source, map, options, load = require) => {
  10853. const nodeStylus = load("stylus");
  10854. try {
  10855. const ref = nodeStylus(source, options);
  10856. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10857. const result = ref.render();
  10858. const dependencies = ref.deps();
  10859. if (map) {
  10860. return {
  10861. code: result,
  10862. map: merge(map, ref.sourcemap),
  10863. errors: [],
  10864. dependencies
  10865. };
  10866. }
  10867. return { code: result, errors: [], dependencies };
  10868. } catch (e) {
  10869. return { code: "", errors: [e], dependencies: [] };
  10870. }
  10871. };
  10872. function getSource(source, filename, additionalData) {
  10873. if (!additionalData) return source;
  10874. if (shared.isFunction(additionalData)) {
  10875. return additionalData(source, filename);
  10876. }
  10877. return additionalData + source;
  10878. }
  10879. const processors = {
  10880. less,
  10881. sass,
  10882. scss,
  10883. styl,
  10884. stylus: styl
  10885. };
  10886. var build = {exports: {}};
  10887. var fs = {};
  10888. var hasRequiredFs;
  10889. function requireFs () {
  10890. if (hasRequiredFs) return fs;
  10891. hasRequiredFs = 1;
  10892. Object.defineProperty(fs, "__esModule", {
  10893. value: true
  10894. });
  10895. fs.getFileSystem = getFileSystem;
  10896. fs.setFileSystem = setFileSystem;
  10897. let fileSystem = {
  10898. readFile: () => {
  10899. throw Error("readFile not implemented");
  10900. },
  10901. writeFile: () => {
  10902. throw Error("writeFile not implemented");
  10903. }
  10904. };
  10905. function setFileSystem(fs) {
  10906. fileSystem.readFile = fs.readFile;
  10907. fileSystem.writeFile = fs.writeFile;
  10908. }
  10909. function getFileSystem() {
  10910. return fileSystem;
  10911. }
  10912. return fs;
  10913. }
  10914. var pluginFactory = {};
  10915. var unquote = {};
  10916. var hasRequiredUnquote;
  10917. function requireUnquote () {
  10918. if (hasRequiredUnquote) return unquote;
  10919. hasRequiredUnquote = 1;
  10920. Object.defineProperty(unquote, "__esModule", {
  10921. value: true
  10922. });
  10923. unquote.default = unquote$1;
  10924. // copied from https://github.com/lakenen/node-unquote
  10925. const reg = /['"]/;
  10926. function unquote$1(str) {
  10927. if (!str) {
  10928. return "";
  10929. }
  10930. if (reg.test(str.charAt(0))) {
  10931. str = str.substr(1);
  10932. }
  10933. if (reg.test(str.charAt(str.length - 1))) {
  10934. str = str.substr(0, str.length - 1);
  10935. }
  10936. return str;
  10937. }
  10938. return unquote;
  10939. }
  10940. var Parser = {};
  10941. var replaceValueSymbols_1;
  10942. var hasRequiredReplaceValueSymbols;
  10943. function requireReplaceValueSymbols () {
  10944. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  10945. hasRequiredReplaceValueSymbols = 1;
  10946. const matchValueName = /[$]?[\w-]+/g;
  10947. const replaceValueSymbols = (value, replacements) => {
  10948. let matches;
  10949. while ((matches = matchValueName.exec(value))) {
  10950. const replacement = replacements[matches[0]];
  10951. if (replacement) {
  10952. value =
  10953. value.slice(0, matches.index) +
  10954. replacement +
  10955. value.slice(matchValueName.lastIndex);
  10956. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10957. }
  10958. }
  10959. return value;
  10960. };
  10961. replaceValueSymbols_1 = replaceValueSymbols;
  10962. return replaceValueSymbols_1;
  10963. }
  10964. var replaceSymbols_1;
  10965. var hasRequiredReplaceSymbols;
  10966. function requireReplaceSymbols () {
  10967. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  10968. hasRequiredReplaceSymbols = 1;
  10969. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10970. const replaceSymbols = (css, replacements) => {
  10971. css.walk((node) => {
  10972. if (node.type === "decl" && node.value) {
  10973. node.value = replaceValueSymbols(node.value.toString(), replacements);
  10974. } else if (node.type === "rule" && node.selector) {
  10975. node.selector = replaceValueSymbols(
  10976. node.selector.toString(),
  10977. replacements
  10978. );
  10979. } else if (node.type === "atrule" && node.params) {
  10980. node.params = replaceValueSymbols(node.params.toString(), replacements);
  10981. }
  10982. });
  10983. };
  10984. replaceSymbols_1 = replaceSymbols;
  10985. return replaceSymbols_1;
  10986. }
  10987. var extractICSS_1;
  10988. var hasRequiredExtractICSS;
  10989. function requireExtractICSS () {
  10990. if (hasRequiredExtractICSS) return extractICSS_1;
  10991. hasRequiredExtractICSS = 1;
  10992. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10993. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10994. const getDeclsObject = (rule) => {
  10995. const object = {};
  10996. rule.walkDecls((decl) => {
  10997. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10998. object[before + decl.prop] = decl.value;
  10999. });
  11000. return object;
  11001. };
  11002. /**
  11003. *
  11004. * @param {string} css
  11005. * @param {boolean} removeRules
  11006. * @param {'auto' | 'rule' | 'at-rule'} mode
  11007. */
  11008. const extractICSS = (css, removeRules = true, mode = "auto") => {
  11009. const icssImports = {};
  11010. const icssExports = {};
  11011. function addImports(node, path) {
  11012. const unquoted = path.replace(/'|"/g, "");
  11013. icssImports[unquoted] = Object.assign(
  11014. icssImports[unquoted] || {},
  11015. getDeclsObject(node)
  11016. );
  11017. if (removeRules) {
  11018. node.remove();
  11019. }
  11020. }
  11021. function addExports(node) {
  11022. Object.assign(icssExports, getDeclsObject(node));
  11023. if (removeRules) {
  11024. node.remove();
  11025. }
  11026. }
  11027. css.each((node) => {
  11028. if (node.type === "rule" && mode !== "at-rule") {
  11029. if (node.selector.slice(0, 7) === ":import") {
  11030. const matches = importPattern.exec(node.selector);
  11031. if (matches) {
  11032. addImports(node, matches[1]);
  11033. }
  11034. }
  11035. if (node.selector === ":export") {
  11036. addExports(node);
  11037. }
  11038. }
  11039. if (node.type === "atrule" && mode !== "rule") {
  11040. if (node.name === "icss-import") {
  11041. const matches = balancedQuotes.exec(node.params);
  11042. if (matches) {
  11043. addImports(node, matches[1]);
  11044. }
  11045. }
  11046. if (node.name === "icss-export") {
  11047. addExports(node);
  11048. }
  11049. }
  11050. });
  11051. return { icssImports, icssExports };
  11052. };
  11053. extractICSS_1 = extractICSS;
  11054. return extractICSS_1;
  11055. }
  11056. var createICSSRules_1;
  11057. var hasRequiredCreateICSSRules;
  11058. function requireCreateICSSRules () {
  11059. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  11060. hasRequiredCreateICSSRules = 1;
  11061. const createImports = (imports, postcss, mode = "rule") => {
  11062. return Object.keys(imports).map((path) => {
  11063. const aliases = imports[path];
  11064. const declarations = Object.keys(aliases).map((key) =>
  11065. postcss.decl({
  11066. prop: key,
  11067. value: aliases[key],
  11068. raws: { before: "\n " },
  11069. })
  11070. );
  11071. const hasDeclarations = declarations.length > 0;
  11072. const rule =
  11073. mode === "rule"
  11074. ? postcss.rule({
  11075. selector: `:import('${path}')`,
  11076. raws: { after: hasDeclarations ? "\n" : "" },
  11077. })
  11078. : postcss.atRule({
  11079. name: "icss-import",
  11080. params: `'${path}'`,
  11081. raws: { after: hasDeclarations ? "\n" : "" },
  11082. });
  11083. if (hasDeclarations) {
  11084. rule.append(declarations);
  11085. }
  11086. return rule;
  11087. });
  11088. };
  11089. const createExports = (exports, postcss, mode = "rule") => {
  11090. const declarations = Object.keys(exports).map((key) =>
  11091. postcss.decl({
  11092. prop: key,
  11093. value: exports[key],
  11094. raws: { before: "\n " },
  11095. })
  11096. );
  11097. if (declarations.length === 0) {
  11098. return [];
  11099. }
  11100. const rule =
  11101. mode === "rule"
  11102. ? postcss.rule({
  11103. selector: `:export`,
  11104. raws: { after: "\n" },
  11105. })
  11106. : postcss.atRule({
  11107. name: "icss-export",
  11108. raws: { after: "\n" },
  11109. });
  11110. rule.append(declarations);
  11111. return [rule];
  11112. };
  11113. const createICSSRules = (imports, exports, postcss, mode) => [
  11114. ...createImports(imports, postcss, mode),
  11115. ...createExports(exports, postcss, mode),
  11116. ];
  11117. createICSSRules_1 = createICSSRules;
  11118. return createICSSRules_1;
  11119. }
  11120. var src$4;
  11121. var hasRequiredSrc$4;
  11122. function requireSrc$4 () {
  11123. if (hasRequiredSrc$4) return src$4;
  11124. hasRequiredSrc$4 = 1;
  11125. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  11126. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  11127. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  11128. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  11129. src$4 = {
  11130. replaceValueSymbols,
  11131. replaceSymbols,
  11132. extractICSS,
  11133. createICSSRules,
  11134. };
  11135. return src$4;
  11136. }
  11137. var hasRequiredParser$1;
  11138. function requireParser$1 () {
  11139. if (hasRequiredParser$1) return Parser;
  11140. hasRequiredParser$1 = 1;
  11141. Object.defineProperty(Parser, "__esModule", {
  11142. value: true
  11143. });
  11144. Parser.default = void 0;
  11145. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  11146. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11147. const importRegexp = /^:import\((.+)\)$/;
  11148. let Parser$1 = class Parser {
  11149. constructor(pathFetcher, trace) {
  11150. this.pathFetcher = pathFetcher;
  11151. this.plugin = this.plugin.bind(this);
  11152. this.exportTokens = {};
  11153. this.translations = {};
  11154. this.trace = trace;
  11155. }
  11156. plugin() {
  11157. const parser = this;
  11158. return {
  11159. postcssPlugin: "css-modules-parser",
  11160. async OnceExit(css) {
  11161. await Promise.all(parser.fetchAllImports(css));
  11162. parser.linkImportedSymbols(css);
  11163. return parser.extractExports(css);
  11164. }
  11165. };
  11166. }
  11167. fetchAllImports(css) {
  11168. let imports = [];
  11169. css.each(node => {
  11170. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11171. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11172. }
  11173. });
  11174. return imports;
  11175. }
  11176. linkImportedSymbols(css) {
  11177. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11178. }
  11179. extractExports(css) {
  11180. css.each(node => {
  11181. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11182. });
  11183. }
  11184. handleExport(exportNode) {
  11185. exportNode.each(decl => {
  11186. if (decl.type == "decl") {
  11187. Object.keys(this.translations).forEach(translation => {
  11188. decl.value = decl.value.replace(translation, this.translations[translation]);
  11189. });
  11190. this.exportTokens[decl.prop] = decl.value;
  11191. }
  11192. });
  11193. exportNode.remove();
  11194. }
  11195. async fetchImport(importNode, relativeTo, depNr) {
  11196. const file = importNode.selector.match(importRegexp)[1];
  11197. const depTrace = this.trace + String.fromCharCode(depNr);
  11198. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  11199. try {
  11200. importNode.each(decl => {
  11201. if (decl.type == "decl") {
  11202. this.translations[decl.prop] = exports[decl.value];
  11203. }
  11204. });
  11205. importNode.remove();
  11206. } catch (err) {
  11207. console.log(err);
  11208. }
  11209. }
  11210. };
  11211. Parser.default = Parser$1;
  11212. return Parser;
  11213. }
  11214. var saveJSON = {};
  11215. var hasRequiredSaveJSON;
  11216. function requireSaveJSON () {
  11217. if (hasRequiredSaveJSON) return saveJSON;
  11218. hasRequiredSaveJSON = 1;
  11219. Object.defineProperty(saveJSON, "__esModule", {
  11220. value: true
  11221. });
  11222. saveJSON.default = saveJSON$1;
  11223. var _fs = /*@__PURE__*/ requireFs();
  11224. function saveJSON$1(cssFile, json) {
  11225. return new Promise((resolve, reject) => {
  11226. const {
  11227. writeFile
  11228. } = (0, _fs.getFileSystem)();
  11229. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11230. });
  11231. }
  11232. return saveJSON;
  11233. }
  11234. var localsConvention = {};
  11235. /**
  11236. * lodash (Custom Build) <https://lodash.com/>
  11237. * Build: `lodash modularize exports="npm" -o ./`
  11238. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11239. * Released under MIT license <https://lodash.com/license>
  11240. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11241. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11242. */
  11243. var lodash_camelcase;
  11244. var hasRequiredLodash_camelcase;
  11245. function requireLodash_camelcase () {
  11246. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11247. hasRequiredLodash_camelcase = 1;
  11248. /** `Object#toString` result references. */
  11249. var symbolTag = '[object Symbol]';
  11250. /** Used to match words composed of alphanumeric characters. */
  11251. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11252. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11253. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11254. /** Used to compose unicode character classes. */
  11255. var rsAstralRange = '\\ud800-\\udfff',
  11256. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11257. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11258. rsDingbatRange = '\\u2700-\\u27bf',
  11259. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11260. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11261. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11262. rsPunctuationRange = '\\u2000-\\u206f',
  11263. rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
  11264. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11265. rsVarRange = '\\ufe0e\\ufe0f',
  11266. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11267. /** Used to compose unicode capture groups. */
  11268. var rsApos = "['\u2019]",
  11269. rsAstral = '[' + rsAstralRange + ']',
  11270. rsBreak = '[' + rsBreakRange + ']',
  11271. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11272. rsDigits = '\\d+',
  11273. rsDingbat = '[' + rsDingbatRange + ']',
  11274. rsLower = '[' + rsLowerRange + ']',
  11275. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11276. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11277. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11278. rsNonAstral = '[^' + rsAstralRange + ']',
  11279. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11280. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11281. rsUpper = '[' + rsUpperRange + ']',
  11282. rsZWJ = '\\u200d';
  11283. /** Used to compose unicode regexes. */
  11284. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11285. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11286. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11287. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11288. reOptMod = rsModifier + '?',
  11289. rsOptVar = '[' + rsVarRange + ']?',
  11290. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11291. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11292. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11293. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11294. /** Used to match apostrophes. */
  11295. var reApos = RegExp(rsApos, 'g');
  11296. /**
  11297. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11298. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11299. */
  11300. var reComboMark = RegExp(rsCombo, 'g');
  11301. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11302. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11303. /** Used to match complex or compound words. */
  11304. var reUnicodeWord = RegExp([
  11305. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11306. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11307. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11308. rsUpper + '+' + rsOptUpperContr,
  11309. rsDigits,
  11310. rsEmoji
  11311. ].join('|'), 'g');
  11312. /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
  11313. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11314. /** Used to detect strings that need a more robust regexp to match words. */
  11315. var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
  11316. /** Used to map Latin Unicode letters to basic Latin letters. */
  11317. var deburredLetters = {
  11318. // Latin-1 Supplement block.
  11319. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11320. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11321. '\xc7': 'C', '\xe7': 'c',
  11322. '\xd0': 'D', '\xf0': 'd',
  11323. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11324. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11325. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11326. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11327. '\xd1': 'N', '\xf1': 'n',
  11328. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11329. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11330. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11331. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11332. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11333. '\xc6': 'Ae', '\xe6': 'ae',
  11334. '\xde': 'Th', '\xfe': 'th',
  11335. '\xdf': 'ss',
  11336. // Latin Extended-A block.
  11337. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11338. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11339. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11340. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11341. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11342. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11343. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11344. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11345. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11346. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11347. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11348. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11349. '\u0134': 'J', '\u0135': 'j',
  11350. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11351. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11352. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11353. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11354. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11355. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11356. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11357. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11358. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11359. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11360. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11361. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11362. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11363. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11364. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11365. '\u0174': 'W', '\u0175': 'w',
  11366. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11367. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11368. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11369. '\u0132': 'IJ', '\u0133': 'ij',
  11370. '\u0152': 'Oe', '\u0153': 'oe',
  11371. '\u0149': "'n", '\u017f': 'ss'
  11372. };
  11373. /** Detect free variable `global` from Node.js. */
  11374. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11375. /** Detect free variable `self`. */
  11376. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11377. /** Used as a reference to the global object. */
  11378. var root = freeGlobal || freeSelf || Function('return this')();
  11379. /**
  11380. * A specialized version of `_.reduce` for arrays without support for
  11381. * iteratee shorthands.
  11382. *
  11383. * @private
  11384. * @param {Array} [array] The array to iterate over.
  11385. * @param {Function} iteratee The function invoked per iteration.
  11386. * @param {*} [accumulator] The initial value.
  11387. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11388. * the initial value.
  11389. * @returns {*} Returns the accumulated value.
  11390. */
  11391. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11392. var index = -1,
  11393. length = array ? array.length : 0;
  11394. while (++index < length) {
  11395. accumulator = iteratee(accumulator, array[index], index, array);
  11396. }
  11397. return accumulator;
  11398. }
  11399. /**
  11400. * Converts an ASCII `string` to an array.
  11401. *
  11402. * @private
  11403. * @param {string} string The string to convert.
  11404. * @returns {Array} Returns the converted array.
  11405. */
  11406. function asciiToArray(string) {
  11407. return string.split('');
  11408. }
  11409. /**
  11410. * Splits an ASCII `string` into an array of its words.
  11411. *
  11412. * @private
  11413. * @param {string} The string to inspect.
  11414. * @returns {Array} Returns the words of `string`.
  11415. */
  11416. function asciiWords(string) {
  11417. return string.match(reAsciiWord) || [];
  11418. }
  11419. /**
  11420. * The base implementation of `_.propertyOf` without support for deep paths.
  11421. *
  11422. * @private
  11423. * @param {Object} object The object to query.
  11424. * @returns {Function} Returns the new accessor function.
  11425. */
  11426. function basePropertyOf(object) {
  11427. return function(key) {
  11428. return object == null ? undefined : object[key];
  11429. };
  11430. }
  11431. /**
  11432. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11433. * letters to basic Latin letters.
  11434. *
  11435. * @private
  11436. * @param {string} letter The matched letter to deburr.
  11437. * @returns {string} Returns the deburred letter.
  11438. */
  11439. var deburrLetter = basePropertyOf(deburredLetters);
  11440. /**
  11441. * Checks if `string` contains Unicode symbols.
  11442. *
  11443. * @private
  11444. * @param {string} string The string to inspect.
  11445. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11446. */
  11447. function hasUnicode(string) {
  11448. return reHasUnicode.test(string);
  11449. }
  11450. /**
  11451. * Checks if `string` contains a word composed of Unicode symbols.
  11452. *
  11453. * @private
  11454. * @param {string} string The string to inspect.
  11455. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11456. */
  11457. function hasUnicodeWord(string) {
  11458. return reHasUnicodeWord.test(string);
  11459. }
  11460. /**
  11461. * Converts `string` to an array.
  11462. *
  11463. * @private
  11464. * @param {string} string The string to convert.
  11465. * @returns {Array} Returns the converted array.
  11466. */
  11467. function stringToArray(string) {
  11468. return hasUnicode(string)
  11469. ? unicodeToArray(string)
  11470. : asciiToArray(string);
  11471. }
  11472. /**
  11473. * Converts a Unicode `string` to an array.
  11474. *
  11475. * @private
  11476. * @param {string} string The string to convert.
  11477. * @returns {Array} Returns the converted array.
  11478. */
  11479. function unicodeToArray(string) {
  11480. return string.match(reUnicode) || [];
  11481. }
  11482. /**
  11483. * Splits a Unicode `string` into an array of its words.
  11484. *
  11485. * @private
  11486. * @param {string} The string to inspect.
  11487. * @returns {Array} Returns the words of `string`.
  11488. */
  11489. function unicodeWords(string) {
  11490. return string.match(reUnicodeWord) || [];
  11491. }
  11492. /** Used for built-in method references. */
  11493. var objectProto = Object.prototype;
  11494. /**
  11495. * Used to resolve the
  11496. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11497. * of values.
  11498. */
  11499. var objectToString = objectProto.toString;
  11500. /** Built-in value references. */
  11501. var Symbol = root.Symbol;
  11502. /** Used to convert symbols to primitives and strings. */
  11503. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11504. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11505. /**
  11506. * The base implementation of `_.slice` without an iteratee call guard.
  11507. *
  11508. * @private
  11509. * @param {Array} array The array to slice.
  11510. * @param {number} [start=0] The start position.
  11511. * @param {number} [end=array.length] The end position.
  11512. * @returns {Array} Returns the slice of `array`.
  11513. */
  11514. function baseSlice(array, start, end) {
  11515. var index = -1,
  11516. length = array.length;
  11517. if (start < 0) {
  11518. start = -start > length ? 0 : (length + start);
  11519. }
  11520. end = end > length ? length : end;
  11521. if (end < 0) {
  11522. end += length;
  11523. }
  11524. length = start > end ? 0 : ((end - start) >>> 0);
  11525. start >>>= 0;
  11526. var result = Array(length);
  11527. while (++index < length) {
  11528. result[index] = array[index + start];
  11529. }
  11530. return result;
  11531. }
  11532. /**
  11533. * The base implementation of `_.toString` which doesn't convert nullish
  11534. * values to empty strings.
  11535. *
  11536. * @private
  11537. * @param {*} value The value to process.
  11538. * @returns {string} Returns the string.
  11539. */
  11540. function baseToString(value) {
  11541. // Exit early for strings to avoid a performance hit in some environments.
  11542. if (typeof value == 'string') {
  11543. return value;
  11544. }
  11545. if (isSymbol(value)) {
  11546. return symbolToString ? symbolToString.call(value) : '';
  11547. }
  11548. var result = (value + '');
  11549. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  11550. }
  11551. /**
  11552. * Casts `array` to a slice if it's needed.
  11553. *
  11554. * @private
  11555. * @param {Array} array The array to inspect.
  11556. * @param {number} start The start position.
  11557. * @param {number} [end=array.length] The end position.
  11558. * @returns {Array} Returns the cast slice.
  11559. */
  11560. function castSlice(array, start, end) {
  11561. var length = array.length;
  11562. end = end === undefined ? length : end;
  11563. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11564. }
  11565. /**
  11566. * Creates a function like `_.lowerFirst`.
  11567. *
  11568. * @private
  11569. * @param {string} methodName The name of the `String` case method to use.
  11570. * @returns {Function} Returns the new case function.
  11571. */
  11572. function createCaseFirst(methodName) {
  11573. return function(string) {
  11574. string = toString(string);
  11575. var strSymbols = hasUnicode(string)
  11576. ? stringToArray(string)
  11577. : undefined;
  11578. var chr = strSymbols
  11579. ? strSymbols[0]
  11580. : string.charAt(0);
  11581. var trailing = strSymbols
  11582. ? castSlice(strSymbols, 1).join('')
  11583. : string.slice(1);
  11584. return chr[methodName]() + trailing;
  11585. };
  11586. }
  11587. /**
  11588. * Creates a function like `_.camelCase`.
  11589. *
  11590. * @private
  11591. * @param {Function} callback The function to combine each word.
  11592. * @returns {Function} Returns the new compounder function.
  11593. */
  11594. function createCompounder(callback) {
  11595. return function(string) {
  11596. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11597. };
  11598. }
  11599. /**
  11600. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11601. * and has a `typeof` result of "object".
  11602. *
  11603. * @static
  11604. * @memberOf _
  11605. * @since 4.0.0
  11606. * @category Lang
  11607. * @param {*} value The value to check.
  11608. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11609. * @example
  11610. *
  11611. * _.isObjectLike({});
  11612. * // => true
  11613. *
  11614. * _.isObjectLike([1, 2, 3]);
  11615. * // => true
  11616. *
  11617. * _.isObjectLike(_.noop);
  11618. * // => false
  11619. *
  11620. * _.isObjectLike(null);
  11621. * // => false
  11622. */
  11623. function isObjectLike(value) {
  11624. return !!value && typeof value == 'object';
  11625. }
  11626. /**
  11627. * Checks if `value` is classified as a `Symbol` primitive or object.
  11628. *
  11629. * @static
  11630. * @memberOf _
  11631. * @since 4.0.0
  11632. * @category Lang
  11633. * @param {*} value The value to check.
  11634. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11635. * @example
  11636. *
  11637. * _.isSymbol(Symbol.iterator);
  11638. * // => true
  11639. *
  11640. * _.isSymbol('abc');
  11641. * // => false
  11642. */
  11643. function isSymbol(value) {
  11644. return typeof value == 'symbol' ||
  11645. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11646. }
  11647. /**
  11648. * Converts `value` to a string. An empty string is returned for `null`
  11649. * and `undefined` values. The sign of `-0` is preserved.
  11650. *
  11651. * @static
  11652. * @memberOf _
  11653. * @since 4.0.0
  11654. * @category Lang
  11655. * @param {*} value The value to process.
  11656. * @returns {string} Returns the string.
  11657. * @example
  11658. *
  11659. * _.toString(null);
  11660. * // => ''
  11661. *
  11662. * _.toString(-0);
  11663. * // => '-0'
  11664. *
  11665. * _.toString([1, 2, 3]);
  11666. * // => '1,2,3'
  11667. */
  11668. function toString(value) {
  11669. return value == null ? '' : baseToString(value);
  11670. }
  11671. /**
  11672. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11673. *
  11674. * @static
  11675. * @memberOf _
  11676. * @since 3.0.0
  11677. * @category String
  11678. * @param {string} [string=''] The string to convert.
  11679. * @returns {string} Returns the camel cased string.
  11680. * @example
  11681. *
  11682. * _.camelCase('Foo Bar');
  11683. * // => 'fooBar'
  11684. *
  11685. * _.camelCase('--foo-bar--');
  11686. * // => 'fooBar'
  11687. *
  11688. * _.camelCase('__FOO_BAR__');
  11689. * // => 'fooBar'
  11690. */
  11691. var camelCase = createCompounder(function(result, word, index) {
  11692. word = word.toLowerCase();
  11693. return result + (index ? capitalize(word) : word);
  11694. });
  11695. /**
  11696. * Converts the first character of `string` to upper case and the remaining
  11697. * to lower case.
  11698. *
  11699. * @static
  11700. * @memberOf _
  11701. * @since 3.0.0
  11702. * @category String
  11703. * @param {string} [string=''] The string to capitalize.
  11704. * @returns {string} Returns the capitalized string.
  11705. * @example
  11706. *
  11707. * _.capitalize('FRED');
  11708. * // => 'Fred'
  11709. */
  11710. function capitalize(string) {
  11711. return upperFirst(toString(string).toLowerCase());
  11712. }
  11713. /**
  11714. * Deburrs `string` by converting
  11715. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11716. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11717. * letters to basic Latin letters and removing
  11718. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11719. *
  11720. * @static
  11721. * @memberOf _
  11722. * @since 3.0.0
  11723. * @category String
  11724. * @param {string} [string=''] The string to deburr.
  11725. * @returns {string} Returns the deburred string.
  11726. * @example
  11727. *
  11728. * _.deburr('déjà vu');
  11729. * // => 'deja vu'
  11730. */
  11731. function deburr(string) {
  11732. string = toString(string);
  11733. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11734. }
  11735. /**
  11736. * Converts the first character of `string` to upper case.
  11737. *
  11738. * @static
  11739. * @memberOf _
  11740. * @since 4.0.0
  11741. * @category String
  11742. * @param {string} [string=''] The string to convert.
  11743. * @returns {string} Returns the converted string.
  11744. * @example
  11745. *
  11746. * _.upperFirst('fred');
  11747. * // => 'Fred'
  11748. *
  11749. * _.upperFirst('FRED');
  11750. * // => 'FRED'
  11751. */
  11752. var upperFirst = createCaseFirst('toUpperCase');
  11753. /**
  11754. * Splits `string` into an array of its words.
  11755. *
  11756. * @static
  11757. * @memberOf _
  11758. * @since 3.0.0
  11759. * @category String
  11760. * @param {string} [string=''] The string to inspect.
  11761. * @param {RegExp|string} [pattern] The pattern to match words.
  11762. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11763. * @returns {Array} Returns the words of `string`.
  11764. * @example
  11765. *
  11766. * _.words('fred, barney, & pebbles');
  11767. * // => ['fred', 'barney', 'pebbles']
  11768. *
  11769. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11770. * // => ['fred', 'barney', '&', 'pebbles']
  11771. */
  11772. function words(string, pattern, guard) {
  11773. string = toString(string);
  11774. pattern = pattern;
  11775. if (pattern === undefined) {
  11776. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11777. }
  11778. return string.match(pattern) || [];
  11779. }
  11780. lodash_camelcase = camelCase;
  11781. return lodash_camelcase;
  11782. }
  11783. var hasRequiredLocalsConvention;
  11784. function requireLocalsConvention () {
  11785. if (hasRequiredLocalsConvention) return localsConvention;
  11786. hasRequiredLocalsConvention = 1;
  11787. Object.defineProperty(localsConvention, "__esModule", {
  11788. value: true
  11789. });
  11790. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11791. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  11792. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11793. function dashesCamelCase(string) {
  11794. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11795. }
  11796. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11797. const isFunc = typeof localsConvention === "function";
  11798. return (tokens, [className, value]) => {
  11799. if (isFunc) {
  11800. const convention = localsConvention(className, value, inputFile);
  11801. tokens[convention] = value;
  11802. return tokens;
  11803. }
  11804. switch (localsConvention) {
  11805. case "camelCase":
  11806. tokens[className] = value;
  11807. tokens[(0, _lodash.default)(className)] = value;
  11808. break;
  11809. case "camelCaseOnly":
  11810. tokens[(0, _lodash.default)(className)] = value;
  11811. break;
  11812. case "dashes":
  11813. tokens[className] = value;
  11814. tokens[dashesCamelCase(className)] = value;
  11815. break;
  11816. case "dashesOnly":
  11817. tokens[dashesCamelCase(className)] = value;
  11818. break;
  11819. }
  11820. return tokens;
  11821. };
  11822. }
  11823. return localsConvention;
  11824. }
  11825. var FileSystemLoader = {};
  11826. var hasRequiredFileSystemLoader;
  11827. function requireFileSystemLoader () {
  11828. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  11829. hasRequiredFileSystemLoader = 1;
  11830. Object.defineProperty(FileSystemLoader, "__esModule", {
  11831. value: true
  11832. });
  11833. FileSystemLoader.default = void 0;
  11834. var _postcss = _interopRequireDefault(require$$0$1);
  11835. var _path = _interopRequireDefault(path$1);
  11836. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  11837. var _fs = /*@__PURE__*/ requireFs();
  11838. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11839. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11840. class Core {
  11841. constructor(plugins) {
  11842. this.plugins = plugins || Core.defaultPlugins;
  11843. }
  11844. async load(sourceString, sourcePath, trace, pathFetcher) {
  11845. const parser = new _Parser.default(pathFetcher, trace);
  11846. const plugins = this.plugins.concat([parser.plugin()]);
  11847. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  11848. from: sourcePath
  11849. });
  11850. return {
  11851. injectableSource: result.css,
  11852. exportTokens: parser.exportTokens
  11853. };
  11854. }
  11855. } // Sorts dependencies in the following way:
  11856. // AAA comes before AA and A
  11857. // AB comes after AA and before A
  11858. // All Bs come after all As
  11859. // This ensures that the files are always returned in the following order:
  11860. // - In the order they were required, except
  11861. // - After all their dependencies
  11862. const traceKeySorter = (a, b) => {
  11863. if (a.length < b.length) {
  11864. return a < b.substring(0, a.length) ? -1 : 1;
  11865. }
  11866. if (a.length > b.length) {
  11867. return a.substring(0, b.length) <= b ? -1 : 1;
  11868. }
  11869. return a < b ? -1 : 1;
  11870. };
  11871. let FileSystemLoader$1 = class FileSystemLoader {
  11872. constructor(root, plugins, fileResolve) {
  11873. if (root === "/" && process.platform === "win32") {
  11874. const cwdDrive = process.cwd().slice(0, 3);
  11875. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11876. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11877. }
  11878. root = cwdDrive;
  11879. }
  11880. this.root = root;
  11881. this.fileResolve = fileResolve;
  11882. this.sources = {};
  11883. this.traces = {};
  11884. this.importNr = 0;
  11885. this.core = new Core(plugins);
  11886. this.tokensByFile = {};
  11887. this.fs = (0, _fs.getFileSystem)();
  11888. }
  11889. async fetch(_newPath, relativeTo, _trace) {
  11890. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11891. const trace = _trace || String.fromCharCode(this.importNr++);
  11892. const useFileResolve = typeof this.fileResolve === "function";
  11893. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11894. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11895. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11896. }
  11897. const relativeDir = _path.default.dirname(relativeTo);
  11898. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11899. let fileRelativePath = fileResolvedPath || _path.default.resolve(_path.default.resolve(this.root, relativeDir), newPath); // if the path is not relative or absolute, try to resolve it in node_modules
  11900. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11901. try {
  11902. fileRelativePath = require.resolve(newPath);
  11903. } catch (e) {// noop
  11904. }
  11905. }
  11906. const tokens = this.tokensByFile[fileRelativePath];
  11907. if (tokens) return tokens;
  11908. return new Promise((resolve, reject) => {
  11909. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11910. if (err) reject(err);
  11911. const {
  11912. injectableSource,
  11913. exportTokens
  11914. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11915. this.sources[fileRelativePath] = injectableSource;
  11916. this.traces[trace] = fileRelativePath;
  11917. this.tokensByFile[fileRelativePath] = exportTokens;
  11918. resolve(exportTokens);
  11919. });
  11920. });
  11921. }
  11922. get finalSource() {
  11923. const traces = this.traces;
  11924. const sources = this.sources;
  11925. let written = new Set();
  11926. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11927. const filename = traces[key];
  11928. if (written.has(filename)) {
  11929. return null;
  11930. }
  11931. written.add(filename);
  11932. return sources[filename];
  11933. }).join("");
  11934. }
  11935. };
  11936. FileSystemLoader.default = FileSystemLoader$1;
  11937. return FileSystemLoader;
  11938. }
  11939. var scoping = {};
  11940. var src$3 = {exports: {}};
  11941. var topologicalSort_1;
  11942. var hasRequiredTopologicalSort;
  11943. function requireTopologicalSort () {
  11944. if (hasRequiredTopologicalSort) return topologicalSort_1;
  11945. hasRequiredTopologicalSort = 1;
  11946. const PERMANENT_MARKER = 2;
  11947. const TEMPORARY_MARKER = 1;
  11948. function createError(node, graph) {
  11949. const er = new Error("Nondeterministic import's order");
  11950. const related = graph[node];
  11951. const relatedNode = related.find(
  11952. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11953. );
  11954. er.nodes = [node, relatedNode];
  11955. return er;
  11956. }
  11957. function walkGraph(node, graph, state, result, strict) {
  11958. if (state[node] === PERMANENT_MARKER) {
  11959. return;
  11960. }
  11961. if (state[node] === TEMPORARY_MARKER) {
  11962. if (strict) {
  11963. return createError(node, graph);
  11964. }
  11965. return;
  11966. }
  11967. state[node] = TEMPORARY_MARKER;
  11968. const children = graph[node];
  11969. const length = children.length;
  11970. for (let i = 0; i < length; ++i) {
  11971. const error = walkGraph(children[i], graph, state, result, strict);
  11972. if (error instanceof Error) {
  11973. return error;
  11974. }
  11975. }
  11976. state[node] = PERMANENT_MARKER;
  11977. result.push(node);
  11978. }
  11979. function topologicalSort(graph, strict) {
  11980. const result = [];
  11981. const state = {};
  11982. const nodes = Object.keys(graph);
  11983. const length = nodes.length;
  11984. for (let i = 0; i < length; ++i) {
  11985. const er = walkGraph(nodes[i], graph, state, result, strict);
  11986. if (er instanceof Error) {
  11987. return er;
  11988. }
  11989. }
  11990. return result;
  11991. }
  11992. topologicalSort_1 = topologicalSort;
  11993. return topologicalSort_1;
  11994. }
  11995. var hasRequiredSrc$3;
  11996. function requireSrc$3 () {
  11997. if (hasRequiredSrc$3) return src$3.exports;
  11998. hasRequiredSrc$3 = 1;
  11999. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  12000. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  12001. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  12002. const VISITED_MARKER = 1;
  12003. /**
  12004. * :import('G') {}
  12005. *
  12006. * Rule
  12007. * composes: ... from 'A'
  12008. * composes: ... from 'B'
  12009. * Rule
  12010. * composes: ... from 'A'
  12011. * composes: ... from 'A'
  12012. * composes: ... from 'C'
  12013. *
  12014. * Results in:
  12015. *
  12016. * graph: {
  12017. * G: [],
  12018. * A: [],
  12019. * B: ['A'],
  12020. * C: ['A'],
  12021. * }
  12022. */
  12023. function addImportToGraph(importId, parentId, graph, visited) {
  12024. const siblingsId = parentId + "_" + "siblings";
  12025. const visitedId = parentId + "_" + importId;
  12026. if (visited[visitedId] !== VISITED_MARKER) {
  12027. if (!Array.isArray(visited[siblingsId])) {
  12028. visited[siblingsId] = [];
  12029. }
  12030. const siblings = visited[siblingsId];
  12031. if (Array.isArray(graph[importId])) {
  12032. graph[importId] = graph[importId].concat(siblings);
  12033. } else {
  12034. graph[importId] = siblings.slice();
  12035. }
  12036. visited[visitedId] = VISITED_MARKER;
  12037. siblings.push(importId);
  12038. }
  12039. }
  12040. src$3.exports = (options = {}) => {
  12041. let importIndex = 0;
  12042. const createImportedName =
  12043. typeof options.createImportedName !== "function"
  12044. ? (importName /*, path*/) =>
  12045. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  12046. : options.createImportedName;
  12047. const failOnWrongOrder = options.failOnWrongOrder;
  12048. return {
  12049. postcssPlugin: "postcss-modules-extract-imports",
  12050. prepare() {
  12051. const graph = {};
  12052. const visited = {};
  12053. const existingImports = {};
  12054. const importDecls = {};
  12055. const imports = {};
  12056. return {
  12057. Once(root, postcss) {
  12058. // Check the existing imports order and save refs
  12059. root.walkRules((rule) => {
  12060. const matches = icssImport.exec(rule.selector);
  12061. if (matches) {
  12062. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  12063. const importPath = doubleQuotePath || singleQuotePath;
  12064. addImportToGraph(importPath, "root", graph, visited);
  12065. existingImports[importPath] = rule;
  12066. }
  12067. });
  12068. root.walkDecls(/^composes$/, (declaration) => {
  12069. const multiple = declaration.value.split(",");
  12070. const values = [];
  12071. multiple.forEach((value) => {
  12072. const matches = value.trim().match(matchImports);
  12073. if (!matches) {
  12074. values.push(value);
  12075. return;
  12076. }
  12077. let tmpSymbols;
  12078. let [
  12079. ,
  12080. /*match*/ symbols,
  12081. doubleQuotePath,
  12082. singleQuotePath,
  12083. global,
  12084. ] = matches;
  12085. if (global) {
  12086. // Composing globals simply means changing these classes to wrap them in global(name)
  12087. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  12088. } else {
  12089. const importPath = doubleQuotePath || singleQuotePath;
  12090. let parent = declaration.parent;
  12091. let parentIndexes = "";
  12092. while (parent.type !== "root") {
  12093. parentIndexes =
  12094. parent.parent.index(parent) + "_" + parentIndexes;
  12095. parent = parent.parent;
  12096. }
  12097. const { selector } = declaration.parent;
  12098. const parentRule = `_${parentIndexes}${selector}`;
  12099. addImportToGraph(importPath, parentRule, graph, visited);
  12100. importDecls[importPath] = declaration;
  12101. imports[importPath] = imports[importPath] || {};
  12102. tmpSymbols = symbols.split(/\s+/).map((s) => {
  12103. if (!imports[importPath][s]) {
  12104. imports[importPath][s] = createImportedName(s, importPath);
  12105. }
  12106. return imports[importPath][s];
  12107. });
  12108. }
  12109. values.push(tmpSymbols.join(" "));
  12110. });
  12111. declaration.value = values.join(", ");
  12112. });
  12113. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  12114. if (importsOrder instanceof Error) {
  12115. const importPath = importsOrder.nodes.find((importPath) =>
  12116. // eslint-disable-next-line no-prototype-builtins
  12117. importDecls.hasOwnProperty(importPath)
  12118. );
  12119. const decl = importDecls[importPath];
  12120. throw decl.error(
  12121. "Failed to resolve order of composed modules " +
  12122. importsOrder.nodes
  12123. .map((importPath) => "`" + importPath + "`")
  12124. .join(", ") +
  12125. ".",
  12126. {
  12127. plugin: "postcss-modules-extract-imports",
  12128. word: "composes",
  12129. }
  12130. );
  12131. }
  12132. let lastImportRule;
  12133. importsOrder.forEach((path) => {
  12134. const importedSymbols = imports[path];
  12135. let rule = existingImports[path];
  12136. if (!rule && importedSymbols) {
  12137. rule = postcss.rule({
  12138. selector: `:import("${path}")`,
  12139. raws: { after: "\n" },
  12140. });
  12141. if (lastImportRule) {
  12142. root.insertAfter(lastImportRule, rule);
  12143. } else {
  12144. root.prepend(rule);
  12145. }
  12146. }
  12147. lastImportRule = rule;
  12148. if (!importedSymbols) {
  12149. return;
  12150. }
  12151. Object.keys(importedSymbols).forEach((importedSymbol) => {
  12152. rule.append(
  12153. postcss.decl({
  12154. value: importedSymbol,
  12155. prop: importedSymbols[importedSymbol],
  12156. raws: { before: "\n " },
  12157. })
  12158. );
  12159. });
  12160. });
  12161. },
  12162. };
  12163. },
  12164. };
  12165. };
  12166. src$3.exports.postcss = true;
  12167. return src$3.exports;
  12168. }
  12169. var wasmHash = {exports: {}};
  12170. /*
  12171. MIT License http://www.opensource.org/licenses/mit-license.php
  12172. Author Tobias Koppers @sokra
  12173. */
  12174. var hasRequiredWasmHash;
  12175. function requireWasmHash () {
  12176. if (hasRequiredWasmHash) return wasmHash.exports;
  12177. hasRequiredWasmHash = 1;
  12178. // 65536 is the size of a wasm memory page
  12179. // 64 is the maximum chunk size for every possible wasm hash implementation
  12180. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12181. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12182. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
  12183. class WasmHash {
  12184. /**
  12185. * @param {WebAssembly.Instance} instance wasm instance
  12186. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12187. * @param {number} chunkSize size of data chunks passed to wasm
  12188. * @param {number} digestSize size of digest returned by wasm
  12189. */
  12190. constructor(instance, instancesPool, chunkSize, digestSize) {
  12191. const exports = /** @type {any} */ (instance.exports);
  12192. exports.init();
  12193. this.exports = exports;
  12194. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  12195. this.buffered = 0;
  12196. this.instancesPool = instancesPool;
  12197. this.chunkSize = chunkSize;
  12198. this.digestSize = digestSize;
  12199. }
  12200. reset() {
  12201. this.buffered = 0;
  12202. this.exports.init();
  12203. }
  12204. /**
  12205. * @param {Buffer | string} data data
  12206. * @param {BufferEncoding=} encoding encoding
  12207. * @returns {this} itself
  12208. */
  12209. update(data, encoding) {
  12210. if (typeof data === "string") {
  12211. while (data.length > MAX_SHORT_STRING) {
  12212. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12213. data = data.slice(MAX_SHORT_STRING);
  12214. }
  12215. this._updateWithShortString(data, encoding);
  12216. return this;
  12217. }
  12218. this._updateWithBuffer(data);
  12219. return this;
  12220. }
  12221. /**
  12222. * @param {string} data data
  12223. * @param {BufferEncoding=} encoding encoding
  12224. * @returns {void}
  12225. */
  12226. _updateWithShortString(data, encoding) {
  12227. const { exports, buffered, mem, chunkSize } = this;
  12228. let endPos;
  12229. if (data.length < 70) {
  12230. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12231. endPos = buffered;
  12232. for (let i = 0; i < data.length; i++) {
  12233. const cc = data.charCodeAt(i);
  12234. if (cc < 0x80) {
  12235. mem[endPos++] = cc;
  12236. } else if (cc < 0x800) {
  12237. mem[endPos] = (cc >> 6) | 0xc0;
  12238. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12239. endPos += 2;
  12240. } else {
  12241. // bail-out for weird chars
  12242. endPos += mem.write(data.slice(i), endPos, encoding);
  12243. break;
  12244. }
  12245. }
  12246. } else if (encoding === "latin1") {
  12247. endPos = buffered;
  12248. for (let i = 0; i < data.length; i++) {
  12249. const cc = data.charCodeAt(i);
  12250. mem[endPos++] = cc;
  12251. }
  12252. } else {
  12253. endPos = buffered + mem.write(data, buffered, encoding);
  12254. }
  12255. } else {
  12256. endPos = buffered + mem.write(data, buffered, encoding);
  12257. }
  12258. if (endPos < chunkSize) {
  12259. this.buffered = endPos;
  12260. } else {
  12261. const l = endPos & ~(this.chunkSize - 1);
  12262. exports.update(l);
  12263. const newBuffered = endPos - l;
  12264. this.buffered = newBuffered;
  12265. if (newBuffered > 0) {
  12266. mem.copyWithin(0, l, endPos);
  12267. }
  12268. }
  12269. }
  12270. /**
  12271. * @param {Buffer} data data
  12272. * @returns {void}
  12273. */
  12274. _updateWithBuffer(data) {
  12275. const { exports, buffered, mem } = this;
  12276. const length = data.length;
  12277. if (buffered + length < this.chunkSize) {
  12278. data.copy(mem, buffered, 0, length);
  12279. this.buffered += length;
  12280. } else {
  12281. const l = (buffered + length) & ~(this.chunkSize - 1);
  12282. if (l > 65536) {
  12283. let i = 65536 - buffered;
  12284. data.copy(mem, buffered, 0, i);
  12285. exports.update(65536);
  12286. const stop = l - buffered - 65536;
  12287. while (i < stop) {
  12288. data.copy(mem, 0, i, i + 65536);
  12289. exports.update(65536);
  12290. i += 65536;
  12291. }
  12292. data.copy(mem, 0, i, l - buffered);
  12293. exports.update(l - buffered - i);
  12294. } else {
  12295. data.copy(mem, buffered, 0, l - buffered);
  12296. exports.update(l);
  12297. }
  12298. const newBuffered = length + buffered - l;
  12299. this.buffered = newBuffered;
  12300. if (newBuffered > 0) {
  12301. data.copy(mem, 0, length - newBuffered, length);
  12302. }
  12303. }
  12304. }
  12305. digest(type) {
  12306. const { exports, buffered, mem, digestSize } = this;
  12307. exports.final(buffered);
  12308. this.instancesPool.push(this);
  12309. const hex = mem.toString("latin1", 0, digestSize);
  12310. if (type === "hex") {
  12311. return hex;
  12312. }
  12313. if (type === "binary" || !type) {
  12314. return Buffer.from(hex, "hex");
  12315. }
  12316. return Buffer.from(hex, "hex").toString(type);
  12317. }
  12318. }
  12319. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12320. if (instancesPool.length > 0) {
  12321. const old = instancesPool.pop();
  12322. old.reset();
  12323. return old;
  12324. } else {
  12325. return new WasmHash(
  12326. new WebAssembly.Instance(wasmModule),
  12327. instancesPool,
  12328. chunkSize,
  12329. digestSize
  12330. );
  12331. }
  12332. };
  12333. wasmHash.exports = create;
  12334. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12335. return wasmHash.exports;
  12336. }
  12337. /*
  12338. MIT License http://www.opensource.org/licenses/mit-license.php
  12339. Author Tobias Koppers @sokra
  12340. */
  12341. var xxhash64_1;
  12342. var hasRequiredXxhash64;
  12343. function requireXxhash64 () {
  12344. if (hasRequiredXxhash64) return xxhash64_1;
  12345. hasRequiredXxhash64 = 1;
  12346. const create = /*@__PURE__*/ requireWasmHash();
  12347. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12348. const xxhash64 = new WebAssembly.Module(
  12349. Buffer.from(
  12350. // 1173 bytes
  12351. "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrUIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqwYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEACfyACIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCECIAFBBGoLIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAiACQh2IhUL5893xmfaZqxZ+IgIgAkIgiIUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL",
  12352. "base64"
  12353. )
  12354. );
  12355. //#endregion
  12356. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12357. return xxhash64_1;
  12358. }
  12359. var BatchedHash_1;
  12360. var hasRequiredBatchedHash;
  12361. function requireBatchedHash () {
  12362. if (hasRequiredBatchedHash) return BatchedHash_1;
  12363. hasRequiredBatchedHash = 1;
  12364. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12365. class BatchedHash {
  12366. constructor(hash) {
  12367. this.string = undefined;
  12368. this.encoding = undefined;
  12369. this.hash = hash;
  12370. }
  12371. /**
  12372. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12373. * @param {string|Buffer} data data
  12374. * @param {string=} inputEncoding data encoding
  12375. * @returns {this} updated hash
  12376. */
  12377. update(data, inputEncoding) {
  12378. if (this.string !== undefined) {
  12379. if (
  12380. typeof data === "string" &&
  12381. inputEncoding === this.encoding &&
  12382. this.string.length + data.length < MAX_SHORT_STRING
  12383. ) {
  12384. this.string += data;
  12385. return this;
  12386. }
  12387. this.hash.update(this.string, this.encoding);
  12388. this.string = undefined;
  12389. }
  12390. if (typeof data === "string") {
  12391. if (
  12392. data.length < MAX_SHORT_STRING &&
  12393. // base64 encoding is not valid since it may contain padding chars
  12394. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12395. ) {
  12396. this.string = data;
  12397. this.encoding = inputEncoding;
  12398. } else {
  12399. this.hash.update(data, inputEncoding);
  12400. }
  12401. } else {
  12402. this.hash.update(data);
  12403. }
  12404. return this;
  12405. }
  12406. /**
  12407. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12408. * @param {string=} encoding encoding of the return value
  12409. * @returns {string|Buffer} digest
  12410. */
  12411. digest(encoding) {
  12412. if (this.string !== undefined) {
  12413. this.hash.update(this.string, this.encoding);
  12414. }
  12415. return this.hash.digest(encoding);
  12416. }
  12417. }
  12418. BatchedHash_1 = BatchedHash;
  12419. return BatchedHash_1;
  12420. }
  12421. /*
  12422. MIT License http://www.opensource.org/licenses/mit-license.php
  12423. Author Tobias Koppers @sokra
  12424. */
  12425. var md4_1;
  12426. var hasRequiredMd4;
  12427. function requireMd4 () {
  12428. if (hasRequiredMd4) return md4_1;
  12429. hasRequiredMd4 = 1;
  12430. const create = /*@__PURE__*/ requireWasmHash();
  12431. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12432. const md4 = new WebAssembly.Module(
  12433. Buffer.from(
  12434. // 2150 bytes
  12435. "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqFEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvMCgEYfyMBIQojAiEGIwMhByMEIQgDQCAAIAVLBEAgBSgCCCINIAcgBiAFKAIEIgsgCCAHIAUoAgAiDCAKIAggBiAHIAhzcXNqakEDdyIDIAYgB3Nxc2pqQQd3IgEgAyAGc3FzampBC3chAiAFKAIUIg8gASACIAUoAhAiCSADIAEgBSgCDCIOIAYgAyACIAEgA3Nxc2pqQRN3IgQgASACc3FzampBA3ciAyACIARzcXNqakEHdyEBIAUoAiAiEiADIAEgBSgCHCIRIAQgAyAFKAIYIhAgAiAEIAEgAyAEc3FzampBC3ciAiABIANzcXNqakETdyIEIAEgAnNxc2pqQQN3IQMgBSgCLCIVIAQgAyAFKAIoIhQgAiAEIAUoAiQiEyABIAIgAyACIARzcXNqakEHdyIBIAMgBHNxc2pqQQt3IgIgASADc3FzampBE3chBCAPIBAgCSAVIBQgEyAFKAI4IhYgAiAEIAUoAjQiFyABIAIgBSgCMCIYIAMgASAEIAEgAnNxc2pqQQN3IgEgAiAEc3FzampBB3ciAiABIARzcXNqakELdyIDIAkgAiAMIAEgBSgCPCIJIAQgASADIAEgAnNxc2pqQRN3IgEgAiADcnEgAiADcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyaiASakGZ84nUBWpBCXciAyAPIAQgCyACIBggASADIAIgBHJxIAIgBHFyampBmfOJ1AVqQQ13IgEgAyAEcnEgAyAEcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyampBmfOJ1AVqQQl3IgMgECAEIAIgFyABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmogDWpBmfOJ1AVqQQN3IgIgASADcnEgASADcXJqakGZ84nUBWpBBXciBCABIAJycSABIAJxcmpqQZnzidQFakEJdyIDIBEgBCAOIAIgFiABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmpqQZnzidQFakEDdyICIAEgA3JxIAEgA3FyampBmfOJ1AVqQQV3IgQgASACcnEgASACcXJqakGZ84nUBWpBCXciAyAMIAIgAyAJIAEgAyACIARycSACIARxcmpqQZnzidQFakENdyIBcyAEc2pqQaHX5/YGakEDdyICIAQgASACcyADc2ogEmpBodfn9gZqQQl3IgRzIAFzampBodfn9gZqQQt3IgMgAiADIBggASADIARzIAJzampBodfn9gZqQQ93IgFzIARzaiANakGh1+f2BmpBA3ciAiAUIAQgASACcyADc2pqQaHX5/YGakEJdyIEcyABc2pqQaHX5/YGakELdyIDIAsgAiADIBYgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgIgEyAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3chAyAKIA4gAiADIBcgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgJqIQogBiAJIAEgESADIAIgFSAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3ciAyAEcyACc2pqQaHX5/YGakEPd2ohBiADIAdqIQcgBCAIaiEIIAVBQGshBQwBCwsgCiQBIAYkAiAHJAMgCCQECw0AIAAQASMAIABqJAAL/wQCA38BfiMAIABqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=",
  12436. "base64"
  12437. )
  12438. );
  12439. //#endregion
  12440. md4_1 = create.bind(null, md4, [], 64, 32);
  12441. return md4_1;
  12442. }
  12443. var BulkUpdateDecorator_1;
  12444. var hasRequiredBulkUpdateDecorator;
  12445. function requireBulkUpdateDecorator () {
  12446. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12447. hasRequiredBulkUpdateDecorator = 1;
  12448. const BULK_SIZE = 2000;
  12449. // We are using an object instead of a Map as this will stay static during the runtime
  12450. // so access to it can be optimized by v8
  12451. const digestCaches = {};
  12452. class BulkUpdateDecorator {
  12453. /**
  12454. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12455. * @param {string=} hashKey key for caching
  12456. */
  12457. constructor(hashOrFactory, hashKey) {
  12458. this.hashKey = hashKey;
  12459. if (typeof hashOrFactory === "function") {
  12460. this.hashFactory = hashOrFactory;
  12461. this.hash = undefined;
  12462. } else {
  12463. this.hashFactory = undefined;
  12464. this.hash = hashOrFactory;
  12465. }
  12466. this.buffer = "";
  12467. }
  12468. /**
  12469. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12470. * @param {string|Buffer} data data
  12471. * @param {string=} inputEncoding data encoding
  12472. * @returns {this} updated hash
  12473. */
  12474. update(data, inputEncoding) {
  12475. if (
  12476. inputEncoding !== undefined ||
  12477. typeof data !== "string" ||
  12478. data.length > BULK_SIZE
  12479. ) {
  12480. if (this.hash === undefined) {
  12481. this.hash = this.hashFactory();
  12482. }
  12483. if (this.buffer.length > 0) {
  12484. this.hash.update(this.buffer);
  12485. this.buffer = "";
  12486. }
  12487. this.hash.update(data, inputEncoding);
  12488. } else {
  12489. this.buffer += data;
  12490. if (this.buffer.length > BULK_SIZE) {
  12491. if (this.hash === undefined) {
  12492. this.hash = this.hashFactory();
  12493. }
  12494. this.hash.update(this.buffer);
  12495. this.buffer = "";
  12496. }
  12497. }
  12498. return this;
  12499. }
  12500. /**
  12501. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12502. * @param {string=} encoding encoding of the return value
  12503. * @returns {string|Buffer} digest
  12504. */
  12505. digest(encoding) {
  12506. let digestCache;
  12507. const buffer = this.buffer;
  12508. if (this.hash === undefined) {
  12509. // short data for hash, we can use caching
  12510. const cacheKey = `${this.hashKey}-${encoding}`;
  12511. digestCache = digestCaches[cacheKey];
  12512. if (digestCache === undefined) {
  12513. digestCache = digestCaches[cacheKey] = new Map();
  12514. }
  12515. const cacheEntry = digestCache.get(buffer);
  12516. if (cacheEntry !== undefined) {
  12517. return cacheEntry;
  12518. }
  12519. this.hash = this.hashFactory();
  12520. }
  12521. if (buffer.length > 0) {
  12522. this.hash.update(buffer);
  12523. }
  12524. const digestResult = this.hash.digest(encoding);
  12525. if (digestCache !== undefined) {
  12526. digestCache.set(buffer, digestResult);
  12527. }
  12528. return digestResult;
  12529. }
  12530. }
  12531. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12532. return BulkUpdateDecorator_1;
  12533. }
  12534. var getHashDigest_1;
  12535. var hasRequiredGetHashDigest;
  12536. function requireGetHashDigest () {
  12537. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12538. hasRequiredGetHashDigest = 1;
  12539. const baseEncodeTables = {
  12540. 26: "abcdefghijklmnopqrstuvwxyz",
  12541. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12542. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12543. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12544. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12545. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12546. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12547. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12548. };
  12549. /**
  12550. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12551. * @param {number} divisor The divisor
  12552. * @return {number} Modulo (remainder) of the division
  12553. */
  12554. function divmod32(uint32Array, divisor) {
  12555. let carry = 0;
  12556. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12557. const value = carry * 0x100000000 + uint32Array[i];
  12558. carry = value % divisor;
  12559. uint32Array[i] = Math.floor(value / divisor);
  12560. }
  12561. return carry;
  12562. }
  12563. function encodeBufferToBase(buffer, base, length) {
  12564. const encodeTable = baseEncodeTables[base];
  12565. if (!encodeTable) {
  12566. throw new Error("Unknown encoding base" + base);
  12567. }
  12568. // Input bits are only enough to generate this many characters
  12569. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12570. length = Math.min(length, limit);
  12571. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12572. // Fewer numbers in the array means faster math.
  12573. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12574. // Make sure the input buffer data is copied and is not mutated by reference.
  12575. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12576. buffer.copy(Buffer.from(uint32Array.buffer));
  12577. let output = "";
  12578. for (let i = 0; i < length; i++) {
  12579. output = encodeTable[divmod32(uint32Array, base)] + output;
  12580. }
  12581. return output;
  12582. }
  12583. let crypto = undefined;
  12584. let createXXHash64 = undefined;
  12585. let createMd4 = undefined;
  12586. let BatchedHash = undefined;
  12587. let BulkUpdateDecorator = undefined;
  12588. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12589. algorithm = algorithm || "xxhash64";
  12590. maxLength = maxLength || 9999;
  12591. let hash;
  12592. if (algorithm === "xxhash64") {
  12593. if (createXXHash64 === undefined) {
  12594. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12595. if (BatchedHash === undefined) {
  12596. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12597. }
  12598. }
  12599. hash = new BatchedHash(createXXHash64());
  12600. } else if (algorithm === "md4") {
  12601. if (createMd4 === undefined) {
  12602. createMd4 = /*@__PURE__*/ requireMd4();
  12603. if (BatchedHash === undefined) {
  12604. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12605. }
  12606. }
  12607. hash = new BatchedHash(createMd4());
  12608. } else if (algorithm === "native-md4") {
  12609. if (typeof crypto === "undefined") {
  12610. crypto = require("crypto");
  12611. if (BulkUpdateDecorator === undefined) {
  12612. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12613. }
  12614. }
  12615. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12616. } else {
  12617. if (typeof crypto === "undefined") {
  12618. crypto = require("crypto");
  12619. if (BulkUpdateDecorator === undefined) {
  12620. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12621. }
  12622. }
  12623. hash = new BulkUpdateDecorator(
  12624. () => crypto.createHash(algorithm),
  12625. algorithm
  12626. );
  12627. }
  12628. hash.update(buffer);
  12629. if (
  12630. digestType === "base26" ||
  12631. digestType === "base32" ||
  12632. digestType === "base36" ||
  12633. digestType === "base49" ||
  12634. digestType === "base52" ||
  12635. digestType === "base58" ||
  12636. digestType === "base62" ||
  12637. digestType === "base64safe"
  12638. ) {
  12639. return encodeBufferToBase(
  12640. hash.digest(),
  12641. digestType === "base64safe" ? 64 : digestType.substr(4),
  12642. maxLength
  12643. );
  12644. }
  12645. return hash.digest(digestType || "hex").substr(0, maxLength);
  12646. }
  12647. getHashDigest_1 = getHashDigest;
  12648. return getHashDigest_1;
  12649. }
  12650. var interpolateName_1;
  12651. var hasRequiredInterpolateName;
  12652. function requireInterpolateName () {
  12653. if (hasRequiredInterpolateName) return interpolateName_1;
  12654. hasRequiredInterpolateName = 1;
  12655. const path = path$1;
  12656. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  12657. function interpolateName(loaderContext, name, options = {}) {
  12658. let filename;
  12659. const hasQuery =
  12660. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12661. if (typeof name === "function") {
  12662. filename = name(
  12663. loaderContext.resourcePath,
  12664. hasQuery ? loaderContext.resourceQuery : undefined
  12665. );
  12666. } else {
  12667. filename = name || "[hash].[ext]";
  12668. }
  12669. const context = options.context;
  12670. const content = options.content;
  12671. const regExp = options.regExp;
  12672. let ext = "bin";
  12673. let basename = "file";
  12674. let directory = "";
  12675. let folder = "";
  12676. let query = "";
  12677. if (loaderContext.resourcePath) {
  12678. const parsed = path.parse(loaderContext.resourcePath);
  12679. let resourcePath = loaderContext.resourcePath;
  12680. if (parsed.ext) {
  12681. ext = parsed.ext.substr(1);
  12682. }
  12683. if (parsed.dir) {
  12684. basename = parsed.name;
  12685. resourcePath = parsed.dir + path.sep;
  12686. }
  12687. if (typeof context !== "undefined") {
  12688. directory = path
  12689. .relative(context, resourcePath + "_")
  12690. .replace(/\\/g, "/")
  12691. .replace(/\.\.(\/)?/g, "_$1");
  12692. directory = directory.substr(0, directory.length - 1);
  12693. } else {
  12694. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12695. }
  12696. if (directory.length <= 1) {
  12697. directory = "";
  12698. } else {
  12699. // directory.length > 1
  12700. folder = path.basename(directory);
  12701. }
  12702. }
  12703. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12704. query = loaderContext.resourceQuery;
  12705. const hashIdx = query.indexOf("#");
  12706. if (hashIdx >= 0) {
  12707. query = query.substr(0, hashIdx);
  12708. }
  12709. }
  12710. let url = filename;
  12711. if (content) {
  12712. // Match hash template
  12713. url = url
  12714. // `hash` and `contenthash` are same in `loader-utils` context
  12715. // let's keep `hash` for backward compatibility
  12716. .replace(
  12717. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12718. (all, hashType, digestType, maxLength) =>
  12719. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12720. );
  12721. }
  12722. url = url
  12723. .replace(/\[ext\]/gi, () => ext)
  12724. .replace(/\[name\]/gi, () => basename)
  12725. .replace(/\[path\]/gi, () => directory)
  12726. .replace(/\[folder\]/gi, () => folder)
  12727. .replace(/\[query\]/gi, () => query);
  12728. if (regExp && loaderContext.resourcePath) {
  12729. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12730. match &&
  12731. match.forEach((matched, i) => {
  12732. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12733. });
  12734. }
  12735. if (
  12736. typeof loaderContext.options === "object" &&
  12737. typeof loaderContext.options.customInterpolateName === "function"
  12738. ) {
  12739. url = loaderContext.options.customInterpolateName.call(
  12740. loaderContext,
  12741. url,
  12742. name,
  12743. options
  12744. );
  12745. }
  12746. return url;
  12747. }
  12748. interpolateName_1 = interpolateName;
  12749. return interpolateName_1;
  12750. }
  12751. var genericNames;
  12752. var hasRequiredGenericNames;
  12753. function requireGenericNames () {
  12754. if (hasRequiredGenericNames) return genericNames;
  12755. hasRequiredGenericNames = 1;
  12756. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  12757. var path = path$1;
  12758. /**
  12759. * @param {string} pattern
  12760. * @param {object} options
  12761. * @param {string} options.context
  12762. * @param {string} options.hashPrefix
  12763. * @return {function}
  12764. */
  12765. genericNames = function createGenerator(pattern, options) {
  12766. options = options || {};
  12767. var context =
  12768. options && typeof options.context === "string"
  12769. ? options.context
  12770. : process.cwd();
  12771. var hashPrefix =
  12772. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12773. /**
  12774. * @param {string} localName Usually a class name
  12775. * @param {string} filepath Absolute path
  12776. * @return {string}
  12777. */
  12778. return function generate(localName, filepath) {
  12779. var name = pattern.replace(/\[local\]/gi, localName);
  12780. var loaderContext = {
  12781. resourcePath: filepath,
  12782. };
  12783. var loaderOptions = {
  12784. content:
  12785. hashPrefix +
  12786. path.relative(context, filepath).replace(/\\/g, "/") +
  12787. "\x00" +
  12788. localName,
  12789. context: context,
  12790. };
  12791. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12792. return genericName
  12793. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12794. .replace(/^((-?[0-9])|--)/, "_$1");
  12795. };
  12796. };
  12797. return genericNames;
  12798. }
  12799. var src$2 = {exports: {}};
  12800. var dist = {exports: {}};
  12801. var processor = {exports: {}};
  12802. var parser = {exports: {}};
  12803. var root = {exports: {}};
  12804. var container = {exports: {}};
  12805. var node = {exports: {}};
  12806. var util = {};
  12807. var unesc = {exports: {}};
  12808. var hasRequiredUnesc;
  12809. function requireUnesc () {
  12810. if (hasRequiredUnesc) return unesc.exports;
  12811. hasRequiredUnesc = 1;
  12812. (function (module, exports) {
  12813. exports.__esModule = true;
  12814. exports["default"] = unesc;
  12815. // Many thanks for this post which made this migration much easier.
  12816. // https://mathiasbynens.be/notes/css-escapes
  12817. /**
  12818. *
  12819. * @param {string} str
  12820. * @returns {[string, number]|undefined}
  12821. */
  12822. function gobbleHex(str) {
  12823. var lower = str.toLowerCase();
  12824. var hex = '';
  12825. var spaceTerminated = false;
  12826. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  12827. var code = lower.charCodeAt(i);
  12828. // check to see if we are dealing with a valid hex char [a-f|0-9]
  12829. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  12830. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  12831. spaceTerminated = code === 32;
  12832. if (!valid) {
  12833. break;
  12834. }
  12835. hex += lower[i];
  12836. }
  12837. if (hex.length === 0) {
  12838. return undefined;
  12839. }
  12840. var codePoint = parseInt(hex, 16);
  12841. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  12842. // Add special case for
  12843. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  12844. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  12845. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  12846. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  12847. }
  12848. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  12849. }
  12850. var CONTAINS_ESCAPE = /\\/;
  12851. function unesc(str) {
  12852. var needToProcess = CONTAINS_ESCAPE.test(str);
  12853. if (!needToProcess) {
  12854. return str;
  12855. }
  12856. var ret = "";
  12857. for (var i = 0; i < str.length; i++) {
  12858. if (str[i] === "\\") {
  12859. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  12860. if (gobbled !== undefined) {
  12861. ret += gobbled[0];
  12862. i += gobbled[1];
  12863. continue;
  12864. }
  12865. // Retain a pair of \\ if double escaped `\\\\`
  12866. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  12867. if (str[i + 1] === "\\") {
  12868. ret += "\\";
  12869. i++;
  12870. continue;
  12871. }
  12872. // if \\ is at the end of the string retain it
  12873. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  12874. if (str.length === i + 1) {
  12875. ret += str[i];
  12876. }
  12877. continue;
  12878. }
  12879. ret += str[i];
  12880. }
  12881. return ret;
  12882. }
  12883. module.exports = exports.default;
  12884. } (unesc, unesc.exports));
  12885. return unesc.exports;
  12886. }
  12887. var getProp = {exports: {}};
  12888. var hasRequiredGetProp;
  12889. function requireGetProp () {
  12890. if (hasRequiredGetProp) return getProp.exports;
  12891. hasRequiredGetProp = 1;
  12892. (function (module, exports) {
  12893. exports.__esModule = true;
  12894. exports["default"] = getProp;
  12895. function getProp(obj) {
  12896. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12897. props[_key - 1] = arguments[_key];
  12898. }
  12899. while (props.length > 0) {
  12900. var prop = props.shift();
  12901. if (!obj[prop]) {
  12902. return undefined;
  12903. }
  12904. obj = obj[prop];
  12905. }
  12906. return obj;
  12907. }
  12908. module.exports = exports.default;
  12909. } (getProp, getProp.exports));
  12910. return getProp.exports;
  12911. }
  12912. var ensureObject = {exports: {}};
  12913. var hasRequiredEnsureObject;
  12914. function requireEnsureObject () {
  12915. if (hasRequiredEnsureObject) return ensureObject.exports;
  12916. hasRequiredEnsureObject = 1;
  12917. (function (module, exports) {
  12918. exports.__esModule = true;
  12919. exports["default"] = ensureObject;
  12920. function ensureObject(obj) {
  12921. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12922. props[_key - 1] = arguments[_key];
  12923. }
  12924. while (props.length > 0) {
  12925. var prop = props.shift();
  12926. if (!obj[prop]) {
  12927. obj[prop] = {};
  12928. }
  12929. obj = obj[prop];
  12930. }
  12931. }
  12932. module.exports = exports.default;
  12933. } (ensureObject, ensureObject.exports));
  12934. return ensureObject.exports;
  12935. }
  12936. var stripComments = {exports: {}};
  12937. var hasRequiredStripComments;
  12938. function requireStripComments () {
  12939. if (hasRequiredStripComments) return stripComments.exports;
  12940. hasRequiredStripComments = 1;
  12941. (function (module, exports) {
  12942. exports.__esModule = true;
  12943. exports["default"] = stripComments;
  12944. function stripComments(str) {
  12945. var s = "";
  12946. var commentStart = str.indexOf("/*");
  12947. var lastEnd = 0;
  12948. while (commentStart >= 0) {
  12949. s = s + str.slice(lastEnd, commentStart);
  12950. var commentEnd = str.indexOf("*/", commentStart + 2);
  12951. if (commentEnd < 0) {
  12952. return s;
  12953. }
  12954. lastEnd = commentEnd + 2;
  12955. commentStart = str.indexOf("/*", lastEnd);
  12956. }
  12957. s = s + str.slice(lastEnd);
  12958. return s;
  12959. }
  12960. module.exports = exports.default;
  12961. } (stripComments, stripComments.exports));
  12962. return stripComments.exports;
  12963. }
  12964. var hasRequiredUtil;
  12965. function requireUtil () {
  12966. if (hasRequiredUtil) return util;
  12967. hasRequiredUtil = 1;
  12968. util.__esModule = true;
  12969. util.unesc = util.stripComments = util.getProp = util.ensureObject = void 0;
  12970. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  12971. util.unesc = _unesc["default"];
  12972. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  12973. util.getProp = _getProp["default"];
  12974. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  12975. util.ensureObject = _ensureObject["default"];
  12976. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  12977. util.stripComments = _stripComments["default"];
  12978. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  12979. return util;
  12980. }
  12981. var hasRequiredNode;
  12982. function requireNode () {
  12983. if (hasRequiredNode) return node.exports;
  12984. hasRequiredNode = 1;
  12985. (function (module, exports) {
  12986. exports.__esModule = true;
  12987. exports["default"] = void 0;
  12988. var _util = /*@__PURE__*/ requireUtil();
  12989. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  12990. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12991. var cloneNode = function cloneNode(obj, parent) {
  12992. if (typeof obj !== 'object' || obj === null) {
  12993. return obj;
  12994. }
  12995. var cloned = new obj.constructor();
  12996. for (var i in obj) {
  12997. if (!obj.hasOwnProperty(i)) {
  12998. continue;
  12999. }
  13000. var value = obj[i];
  13001. var type = typeof value;
  13002. if (i === 'parent' && type === 'object') {
  13003. if (parent) {
  13004. cloned[i] = parent;
  13005. }
  13006. } else if (value instanceof Array) {
  13007. cloned[i] = value.map(function (j) {
  13008. return cloneNode(j, cloned);
  13009. });
  13010. } else {
  13011. cloned[i] = cloneNode(value, cloned);
  13012. }
  13013. }
  13014. return cloned;
  13015. };
  13016. var Node = /*#__PURE__*/function () {
  13017. function Node(opts) {
  13018. if (opts === void 0) {
  13019. opts = {};
  13020. }
  13021. Object.assign(this, opts);
  13022. this.spaces = this.spaces || {};
  13023. this.spaces.before = this.spaces.before || '';
  13024. this.spaces.after = this.spaces.after || '';
  13025. }
  13026. var _proto = Node.prototype;
  13027. _proto.remove = function remove() {
  13028. if (this.parent) {
  13029. this.parent.removeChild(this);
  13030. }
  13031. this.parent = undefined;
  13032. return this;
  13033. };
  13034. _proto.replaceWith = function replaceWith() {
  13035. if (this.parent) {
  13036. for (var index in arguments) {
  13037. this.parent.insertBefore(this, arguments[index]);
  13038. }
  13039. this.remove();
  13040. }
  13041. return this;
  13042. };
  13043. _proto.next = function next() {
  13044. return this.parent.at(this.parent.index(this) + 1);
  13045. };
  13046. _proto.prev = function prev() {
  13047. return this.parent.at(this.parent.index(this) - 1);
  13048. };
  13049. _proto.clone = function clone(overrides) {
  13050. if (overrides === void 0) {
  13051. overrides = {};
  13052. }
  13053. var cloned = cloneNode(this);
  13054. for (var name in overrides) {
  13055. cloned[name] = overrides[name];
  13056. }
  13057. return cloned;
  13058. }
  13059. /**
  13060. * Some non-standard syntax doesn't follow normal escaping rules for css.
  13061. * This allows non standard syntax to be appended to an existing property
  13062. * by specifying the escaped value. By specifying the escaped value,
  13063. * illegal characters are allowed to be directly inserted into css output.
  13064. * @param {string} name the property to set
  13065. * @param {any} value the unescaped value of the property
  13066. * @param {string} valueEscaped optional. the escaped value of the property.
  13067. */;
  13068. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  13069. if (!this.raws) {
  13070. this.raws = {};
  13071. }
  13072. var originalValue = this[name];
  13073. var originalEscaped = this.raws[name];
  13074. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  13075. if (originalEscaped || valueEscaped !== value) {
  13076. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  13077. } else {
  13078. delete this.raws[name]; // delete any escaped value that was created by the setter.
  13079. }
  13080. }
  13081. /**
  13082. * Some non-standard syntax doesn't follow normal escaping rules for css.
  13083. * This allows the escaped value to be specified directly, allowing illegal
  13084. * characters to be directly inserted into css output.
  13085. * @param {string} name the property to set
  13086. * @param {any} value the unescaped value of the property
  13087. * @param {string} valueEscaped the escaped value of the property.
  13088. */;
  13089. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  13090. if (!this.raws) {
  13091. this.raws = {};
  13092. }
  13093. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13094. this.raws[name] = valueEscaped;
  13095. }
  13096. /**
  13097. * When you want a value to passed through to CSS directly. This method
  13098. * deletes the corresponding raw value causing the stringifier to fallback
  13099. * to the unescaped value.
  13100. * @param {string} name the property to set.
  13101. * @param {any} value The value that is both escaped and unescaped.
  13102. */;
  13103. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  13104. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13105. if (this.raws) {
  13106. delete this.raws[name];
  13107. }
  13108. }
  13109. /**
  13110. *
  13111. * @param {number} line The number (starting with 1)
  13112. * @param {number} column The column number (starting with 1)
  13113. */;
  13114. _proto.isAtPosition = function isAtPosition(line, column) {
  13115. if (this.source && this.source.start && this.source.end) {
  13116. if (this.source.start.line > line) {
  13117. return false;
  13118. }
  13119. if (this.source.end.line < line) {
  13120. return false;
  13121. }
  13122. if (this.source.start.line === line && this.source.start.column > column) {
  13123. return false;
  13124. }
  13125. if (this.source.end.line === line && this.source.end.column < column) {
  13126. return false;
  13127. }
  13128. return true;
  13129. }
  13130. return undefined;
  13131. };
  13132. _proto.stringifyProperty = function stringifyProperty(name) {
  13133. return this.raws && this.raws[name] || this[name];
  13134. };
  13135. _proto.valueToString = function valueToString() {
  13136. return String(this.stringifyProperty("value"));
  13137. };
  13138. _proto.toString = function toString() {
  13139. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  13140. };
  13141. _createClass(Node, [{
  13142. key: "rawSpaceBefore",
  13143. get: function get() {
  13144. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  13145. if (rawSpace === undefined) {
  13146. rawSpace = this.spaces && this.spaces.before;
  13147. }
  13148. return rawSpace || "";
  13149. },
  13150. set: function set(raw) {
  13151. (0, _util.ensureObject)(this, "raws", "spaces");
  13152. this.raws.spaces.before = raw;
  13153. }
  13154. }, {
  13155. key: "rawSpaceAfter",
  13156. get: function get() {
  13157. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  13158. if (rawSpace === undefined) {
  13159. rawSpace = this.spaces.after;
  13160. }
  13161. return rawSpace || "";
  13162. },
  13163. set: function set(raw) {
  13164. (0, _util.ensureObject)(this, "raws", "spaces");
  13165. this.raws.spaces.after = raw;
  13166. }
  13167. }]);
  13168. return Node;
  13169. }();
  13170. exports["default"] = Node;
  13171. module.exports = exports.default;
  13172. } (node, node.exports));
  13173. return node.exports;
  13174. }
  13175. var types$1 = {};
  13176. var hasRequiredTypes;
  13177. function requireTypes () {
  13178. if (hasRequiredTypes) return types$1;
  13179. hasRequiredTypes = 1;
  13180. types$1.__esModule = true;
  13181. types$1.UNIVERSAL = types$1.TAG = types$1.STRING = types$1.SELECTOR = types$1.ROOT = types$1.PSEUDO = types$1.NESTING = types$1.ID = types$1.COMMENT = types$1.COMBINATOR = types$1.CLASS = types$1.ATTRIBUTE = void 0;
  13182. var TAG = 'tag';
  13183. types$1.TAG = TAG;
  13184. var STRING = 'string';
  13185. types$1.STRING = STRING;
  13186. var SELECTOR = 'selector';
  13187. types$1.SELECTOR = SELECTOR;
  13188. var ROOT = 'root';
  13189. types$1.ROOT = ROOT;
  13190. var PSEUDO = 'pseudo';
  13191. types$1.PSEUDO = PSEUDO;
  13192. var NESTING = 'nesting';
  13193. types$1.NESTING = NESTING;
  13194. var ID = 'id';
  13195. types$1.ID = ID;
  13196. var COMMENT = 'comment';
  13197. types$1.COMMENT = COMMENT;
  13198. var COMBINATOR = 'combinator';
  13199. types$1.COMBINATOR = COMBINATOR;
  13200. var CLASS = 'class';
  13201. types$1.CLASS = CLASS;
  13202. var ATTRIBUTE = 'attribute';
  13203. types$1.ATTRIBUTE = ATTRIBUTE;
  13204. var UNIVERSAL = 'universal';
  13205. types$1.UNIVERSAL = UNIVERSAL;
  13206. return types$1;
  13207. }
  13208. var hasRequiredContainer;
  13209. function requireContainer () {
  13210. if (hasRequiredContainer) return container.exports;
  13211. hasRequiredContainer = 1;
  13212. (function (module, exports) {
  13213. exports.__esModule = true;
  13214. exports["default"] = void 0;
  13215. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13216. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  13217. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  13218. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  13219. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13220. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike) { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  13221. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  13222. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  13223. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  13224. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13225. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13226. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13227. var Container = /*#__PURE__*/function (_Node) {
  13228. _inheritsLoose(Container, _Node);
  13229. function Container(opts) {
  13230. var _this;
  13231. _this = _Node.call(this, opts) || this;
  13232. if (!_this.nodes) {
  13233. _this.nodes = [];
  13234. }
  13235. return _this;
  13236. }
  13237. var _proto = Container.prototype;
  13238. _proto.append = function append(selector) {
  13239. selector.parent = this;
  13240. this.nodes.push(selector);
  13241. return this;
  13242. };
  13243. _proto.prepend = function prepend(selector) {
  13244. selector.parent = this;
  13245. this.nodes.unshift(selector);
  13246. return this;
  13247. };
  13248. _proto.at = function at(index) {
  13249. return this.nodes[index];
  13250. };
  13251. _proto.index = function index(child) {
  13252. if (typeof child === 'number') {
  13253. return child;
  13254. }
  13255. return this.nodes.indexOf(child);
  13256. };
  13257. _proto.removeChild = function removeChild(child) {
  13258. child = this.index(child);
  13259. this.at(child).parent = undefined;
  13260. this.nodes.splice(child, 1);
  13261. var index;
  13262. for (var id in this.indexes) {
  13263. index = this.indexes[id];
  13264. if (index >= child) {
  13265. this.indexes[id] = index - 1;
  13266. }
  13267. }
  13268. return this;
  13269. };
  13270. _proto.removeAll = function removeAll() {
  13271. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  13272. var node = _step.value;
  13273. node.parent = undefined;
  13274. }
  13275. this.nodes = [];
  13276. return this;
  13277. };
  13278. _proto.empty = function empty() {
  13279. return this.removeAll();
  13280. };
  13281. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  13282. newNode.parent = this;
  13283. var oldIndex = this.index(oldNode);
  13284. this.nodes.splice(oldIndex + 1, 0, newNode);
  13285. newNode.parent = this;
  13286. var index;
  13287. for (var id in this.indexes) {
  13288. index = this.indexes[id];
  13289. if (oldIndex <= index) {
  13290. this.indexes[id] = index + 1;
  13291. }
  13292. }
  13293. return this;
  13294. };
  13295. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  13296. newNode.parent = this;
  13297. var oldIndex = this.index(oldNode);
  13298. this.nodes.splice(oldIndex, 0, newNode);
  13299. newNode.parent = this;
  13300. var index;
  13301. for (var id in this.indexes) {
  13302. index = this.indexes[id];
  13303. if (index <= oldIndex) {
  13304. this.indexes[id] = index + 1;
  13305. }
  13306. }
  13307. return this;
  13308. };
  13309. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  13310. var found = undefined;
  13311. this.each(function (node) {
  13312. if (node.atPosition) {
  13313. var foundChild = node.atPosition(line, col);
  13314. if (foundChild) {
  13315. found = foundChild;
  13316. return false;
  13317. }
  13318. } else if (node.isAtPosition(line, col)) {
  13319. found = node;
  13320. return false;
  13321. }
  13322. });
  13323. return found;
  13324. }
  13325. /**
  13326. * Return the most specific node at the line and column number given.
  13327. * The source location is based on the original parsed location, locations aren't
  13328. * updated as selector nodes are mutated.
  13329. *
  13330. * Note that this location is relative to the location of the first character
  13331. * of the selector, and not the location of the selector in the overall document
  13332. * when used in conjunction with postcss.
  13333. *
  13334. * If not found, returns undefined.
  13335. * @param {number} line The line number of the node to find. (1-based index)
  13336. * @param {number} col The column number of the node to find. (1-based index)
  13337. */;
  13338. _proto.atPosition = function atPosition(line, col) {
  13339. if (this.isAtPosition(line, col)) {
  13340. return this._findChildAtPosition(line, col) || this;
  13341. } else {
  13342. return undefined;
  13343. }
  13344. };
  13345. _proto._inferEndPosition = function _inferEndPosition() {
  13346. if (this.last && this.last.source && this.last.source.end) {
  13347. this.source = this.source || {};
  13348. this.source.end = this.source.end || {};
  13349. Object.assign(this.source.end, this.last.source.end);
  13350. }
  13351. };
  13352. _proto.each = function each(callback) {
  13353. if (!this.lastEach) {
  13354. this.lastEach = 0;
  13355. }
  13356. if (!this.indexes) {
  13357. this.indexes = {};
  13358. }
  13359. this.lastEach++;
  13360. var id = this.lastEach;
  13361. this.indexes[id] = 0;
  13362. if (!this.length) {
  13363. return undefined;
  13364. }
  13365. var index, result;
  13366. while (this.indexes[id] < this.length) {
  13367. index = this.indexes[id];
  13368. result = callback(this.at(index), index);
  13369. if (result === false) {
  13370. break;
  13371. }
  13372. this.indexes[id] += 1;
  13373. }
  13374. delete this.indexes[id];
  13375. if (result === false) {
  13376. return false;
  13377. }
  13378. };
  13379. _proto.walk = function walk(callback) {
  13380. return this.each(function (node, i) {
  13381. var result = callback(node, i);
  13382. if (result !== false && node.length) {
  13383. result = node.walk(callback);
  13384. }
  13385. if (result === false) {
  13386. return false;
  13387. }
  13388. });
  13389. };
  13390. _proto.walkAttributes = function walkAttributes(callback) {
  13391. var _this2 = this;
  13392. return this.walk(function (selector) {
  13393. if (selector.type === types.ATTRIBUTE) {
  13394. return callback.call(_this2, selector);
  13395. }
  13396. });
  13397. };
  13398. _proto.walkClasses = function walkClasses(callback) {
  13399. var _this3 = this;
  13400. return this.walk(function (selector) {
  13401. if (selector.type === types.CLASS) {
  13402. return callback.call(_this3, selector);
  13403. }
  13404. });
  13405. };
  13406. _proto.walkCombinators = function walkCombinators(callback) {
  13407. var _this4 = this;
  13408. return this.walk(function (selector) {
  13409. if (selector.type === types.COMBINATOR) {
  13410. return callback.call(_this4, selector);
  13411. }
  13412. });
  13413. };
  13414. _proto.walkComments = function walkComments(callback) {
  13415. var _this5 = this;
  13416. return this.walk(function (selector) {
  13417. if (selector.type === types.COMMENT) {
  13418. return callback.call(_this5, selector);
  13419. }
  13420. });
  13421. };
  13422. _proto.walkIds = function walkIds(callback) {
  13423. var _this6 = this;
  13424. return this.walk(function (selector) {
  13425. if (selector.type === types.ID) {
  13426. return callback.call(_this6, selector);
  13427. }
  13428. });
  13429. };
  13430. _proto.walkNesting = function walkNesting(callback) {
  13431. var _this7 = this;
  13432. return this.walk(function (selector) {
  13433. if (selector.type === types.NESTING) {
  13434. return callback.call(_this7, selector);
  13435. }
  13436. });
  13437. };
  13438. _proto.walkPseudos = function walkPseudos(callback) {
  13439. var _this8 = this;
  13440. return this.walk(function (selector) {
  13441. if (selector.type === types.PSEUDO) {
  13442. return callback.call(_this8, selector);
  13443. }
  13444. });
  13445. };
  13446. _proto.walkTags = function walkTags(callback) {
  13447. var _this9 = this;
  13448. return this.walk(function (selector) {
  13449. if (selector.type === types.TAG) {
  13450. return callback.call(_this9, selector);
  13451. }
  13452. });
  13453. };
  13454. _proto.walkUniversals = function walkUniversals(callback) {
  13455. var _this10 = this;
  13456. return this.walk(function (selector) {
  13457. if (selector.type === types.UNIVERSAL) {
  13458. return callback.call(_this10, selector);
  13459. }
  13460. });
  13461. };
  13462. _proto.split = function split(callback) {
  13463. var _this11 = this;
  13464. var current = [];
  13465. return this.reduce(function (memo, node, index) {
  13466. var split = callback.call(_this11, node);
  13467. current.push(node);
  13468. if (split) {
  13469. memo.push(current);
  13470. current = [];
  13471. } else if (index === _this11.length - 1) {
  13472. memo.push(current);
  13473. }
  13474. return memo;
  13475. }, []);
  13476. };
  13477. _proto.map = function map(callback) {
  13478. return this.nodes.map(callback);
  13479. };
  13480. _proto.reduce = function reduce(callback, memo) {
  13481. return this.nodes.reduce(callback, memo);
  13482. };
  13483. _proto.every = function every(callback) {
  13484. return this.nodes.every(callback);
  13485. };
  13486. _proto.some = function some(callback) {
  13487. return this.nodes.some(callback);
  13488. };
  13489. _proto.filter = function filter(callback) {
  13490. return this.nodes.filter(callback);
  13491. };
  13492. _proto.sort = function sort(callback) {
  13493. return this.nodes.sort(callback);
  13494. };
  13495. _proto.toString = function toString() {
  13496. return this.map(String).join('');
  13497. };
  13498. _createClass(Container, [{
  13499. key: "first",
  13500. get: function get() {
  13501. return this.at(0);
  13502. }
  13503. }, {
  13504. key: "last",
  13505. get: function get() {
  13506. return this.at(this.length - 1);
  13507. }
  13508. }, {
  13509. key: "length",
  13510. get: function get() {
  13511. return this.nodes.length;
  13512. }
  13513. }]);
  13514. return Container;
  13515. }(_node["default"]);
  13516. exports["default"] = Container;
  13517. module.exports = exports.default;
  13518. } (container, container.exports));
  13519. return container.exports;
  13520. }
  13521. var hasRequiredRoot;
  13522. function requireRoot () {
  13523. if (hasRequiredRoot) return root.exports;
  13524. hasRequiredRoot = 1;
  13525. (function (module, exports) {
  13526. exports.__esModule = true;
  13527. exports["default"] = void 0;
  13528. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13529. var _types = /*@__PURE__*/ requireTypes();
  13530. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13531. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  13532. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13533. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13534. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13535. var Root = /*#__PURE__*/function (_Container) {
  13536. _inheritsLoose(Root, _Container);
  13537. function Root(opts) {
  13538. var _this;
  13539. _this = _Container.call(this, opts) || this;
  13540. _this.type = _types.ROOT;
  13541. return _this;
  13542. }
  13543. var _proto = Root.prototype;
  13544. _proto.toString = function toString() {
  13545. var str = this.reduce(function (memo, selector) {
  13546. memo.push(String(selector));
  13547. return memo;
  13548. }, []).join(',');
  13549. return this.trailingComma ? str + ',' : str;
  13550. };
  13551. _proto.error = function error(message, options) {
  13552. if (this._error) {
  13553. return this._error(message, options);
  13554. } else {
  13555. return new Error(message);
  13556. }
  13557. };
  13558. _createClass(Root, [{
  13559. key: "errorGenerator",
  13560. set: function set(handler) {
  13561. this._error = handler;
  13562. }
  13563. }]);
  13564. return Root;
  13565. }(_container["default"]);
  13566. exports["default"] = Root;
  13567. module.exports = exports.default;
  13568. } (root, root.exports));
  13569. return root.exports;
  13570. }
  13571. var selector = {exports: {}};
  13572. var hasRequiredSelector;
  13573. function requireSelector () {
  13574. if (hasRequiredSelector) return selector.exports;
  13575. hasRequiredSelector = 1;
  13576. (function (module, exports) {
  13577. exports.__esModule = true;
  13578. exports["default"] = void 0;
  13579. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13580. var _types = /*@__PURE__*/ requireTypes();
  13581. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13582. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13583. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13584. var Selector = /*#__PURE__*/function (_Container) {
  13585. _inheritsLoose(Selector, _Container);
  13586. function Selector(opts) {
  13587. var _this;
  13588. _this = _Container.call(this, opts) || this;
  13589. _this.type = _types.SELECTOR;
  13590. return _this;
  13591. }
  13592. return Selector;
  13593. }(_container["default"]);
  13594. exports["default"] = Selector;
  13595. module.exports = exports.default;
  13596. } (selector, selector.exports));
  13597. return selector.exports;
  13598. }
  13599. var className = {exports: {}};
  13600. var hasRequiredClassName;
  13601. function requireClassName () {
  13602. if (hasRequiredClassName) return className.exports;
  13603. hasRequiredClassName = 1;
  13604. (function (module, exports) {
  13605. exports.__esModule = true;
  13606. exports["default"] = void 0;
  13607. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13608. var _util = /*@__PURE__*/ requireUtil();
  13609. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13610. var _types = /*@__PURE__*/ requireTypes();
  13611. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13612. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  13613. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13614. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13615. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13616. var ClassName = /*#__PURE__*/function (_Node) {
  13617. _inheritsLoose(ClassName, _Node);
  13618. function ClassName(opts) {
  13619. var _this;
  13620. _this = _Node.call(this, opts) || this;
  13621. _this.type = _types.CLASS;
  13622. _this._constructed = true;
  13623. return _this;
  13624. }
  13625. var _proto = ClassName.prototype;
  13626. _proto.valueToString = function valueToString() {
  13627. return '.' + _Node.prototype.valueToString.call(this);
  13628. };
  13629. _createClass(ClassName, [{
  13630. key: "value",
  13631. get: function get() {
  13632. return this._value;
  13633. },
  13634. set: function set(v) {
  13635. if (this._constructed) {
  13636. var escaped = (0, _cssesc["default"])(v, {
  13637. isIdentifier: true
  13638. });
  13639. if (escaped !== v) {
  13640. (0, _util.ensureObject)(this, "raws");
  13641. this.raws.value = escaped;
  13642. } else if (this.raws) {
  13643. delete this.raws.value;
  13644. }
  13645. }
  13646. this._value = v;
  13647. }
  13648. }]);
  13649. return ClassName;
  13650. }(_node["default"]);
  13651. exports["default"] = ClassName;
  13652. module.exports = exports.default;
  13653. } (className, className.exports));
  13654. return className.exports;
  13655. }
  13656. var comment = {exports: {}};
  13657. var hasRequiredComment;
  13658. function requireComment () {
  13659. if (hasRequiredComment) return comment.exports;
  13660. hasRequiredComment = 1;
  13661. (function (module, exports) {
  13662. exports.__esModule = true;
  13663. exports["default"] = void 0;
  13664. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13665. var _types = /*@__PURE__*/ requireTypes();
  13666. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13667. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13668. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13669. var Comment = /*#__PURE__*/function (_Node) {
  13670. _inheritsLoose(Comment, _Node);
  13671. function Comment(opts) {
  13672. var _this;
  13673. _this = _Node.call(this, opts) || this;
  13674. _this.type = _types.COMMENT;
  13675. return _this;
  13676. }
  13677. return Comment;
  13678. }(_node["default"]);
  13679. exports["default"] = Comment;
  13680. module.exports = exports.default;
  13681. } (comment, comment.exports));
  13682. return comment.exports;
  13683. }
  13684. var id = {exports: {}};
  13685. var hasRequiredId;
  13686. function requireId () {
  13687. if (hasRequiredId) return id.exports;
  13688. hasRequiredId = 1;
  13689. (function (module, exports) {
  13690. exports.__esModule = true;
  13691. exports["default"] = void 0;
  13692. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13693. var _types = /*@__PURE__*/ requireTypes();
  13694. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13695. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13696. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13697. var ID = /*#__PURE__*/function (_Node) {
  13698. _inheritsLoose(ID, _Node);
  13699. function ID(opts) {
  13700. var _this;
  13701. _this = _Node.call(this, opts) || this;
  13702. _this.type = _types.ID;
  13703. return _this;
  13704. }
  13705. var _proto = ID.prototype;
  13706. _proto.valueToString = function valueToString() {
  13707. return '#' + _Node.prototype.valueToString.call(this);
  13708. };
  13709. return ID;
  13710. }(_node["default"]);
  13711. exports["default"] = ID;
  13712. module.exports = exports.default;
  13713. } (id, id.exports));
  13714. return id.exports;
  13715. }
  13716. var tag = {exports: {}};
  13717. var namespace = {exports: {}};
  13718. var hasRequiredNamespace;
  13719. function requireNamespace () {
  13720. if (hasRequiredNamespace) return namespace.exports;
  13721. hasRequiredNamespace = 1;
  13722. (function (module, exports) {
  13723. exports.__esModule = true;
  13724. exports["default"] = void 0;
  13725. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13726. var _util = /*@__PURE__*/ requireUtil();
  13727. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13728. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13729. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  13730. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13731. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13732. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13733. var Namespace = /*#__PURE__*/function (_Node) {
  13734. _inheritsLoose(Namespace, _Node);
  13735. function Namespace() {
  13736. return _Node.apply(this, arguments) || this;
  13737. }
  13738. var _proto = Namespace.prototype;
  13739. _proto.qualifiedName = function qualifiedName(value) {
  13740. if (this.namespace) {
  13741. return this.namespaceString + "|" + value;
  13742. } else {
  13743. return value;
  13744. }
  13745. };
  13746. _proto.valueToString = function valueToString() {
  13747. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  13748. };
  13749. _createClass(Namespace, [{
  13750. key: "namespace",
  13751. get: function get() {
  13752. return this._namespace;
  13753. },
  13754. set: function set(namespace) {
  13755. if (namespace === true || namespace === "*" || namespace === "&") {
  13756. this._namespace = namespace;
  13757. if (this.raws) {
  13758. delete this.raws.namespace;
  13759. }
  13760. return;
  13761. }
  13762. var escaped = (0, _cssesc["default"])(namespace, {
  13763. isIdentifier: true
  13764. });
  13765. this._namespace = namespace;
  13766. if (escaped !== namespace) {
  13767. (0, _util.ensureObject)(this, "raws");
  13768. this.raws.namespace = escaped;
  13769. } else if (this.raws) {
  13770. delete this.raws.namespace;
  13771. }
  13772. }
  13773. }, {
  13774. key: "ns",
  13775. get: function get() {
  13776. return this._namespace;
  13777. },
  13778. set: function set(namespace) {
  13779. this.namespace = namespace;
  13780. }
  13781. }, {
  13782. key: "namespaceString",
  13783. get: function get() {
  13784. if (this.namespace) {
  13785. var ns = this.stringifyProperty("namespace");
  13786. if (ns === true) {
  13787. return '';
  13788. } else {
  13789. return ns;
  13790. }
  13791. } else {
  13792. return '';
  13793. }
  13794. }
  13795. }]);
  13796. return Namespace;
  13797. }(_node["default"]);
  13798. exports["default"] = Namespace;
  13799. module.exports = exports.default;
  13800. } (namespace, namespace.exports));
  13801. return namespace.exports;
  13802. }
  13803. var hasRequiredTag;
  13804. function requireTag () {
  13805. if (hasRequiredTag) return tag.exports;
  13806. hasRequiredTag = 1;
  13807. (function (module, exports) {
  13808. exports.__esModule = true;
  13809. exports["default"] = void 0;
  13810. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13811. var _types = /*@__PURE__*/ requireTypes();
  13812. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13813. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13814. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13815. var Tag = /*#__PURE__*/function (_Namespace) {
  13816. _inheritsLoose(Tag, _Namespace);
  13817. function Tag(opts) {
  13818. var _this;
  13819. _this = _Namespace.call(this, opts) || this;
  13820. _this.type = _types.TAG;
  13821. return _this;
  13822. }
  13823. return Tag;
  13824. }(_namespace["default"]);
  13825. exports["default"] = Tag;
  13826. module.exports = exports.default;
  13827. } (tag, tag.exports));
  13828. return tag.exports;
  13829. }
  13830. var string = {exports: {}};
  13831. var hasRequiredString;
  13832. function requireString () {
  13833. if (hasRequiredString) return string.exports;
  13834. hasRequiredString = 1;
  13835. (function (module, exports) {
  13836. exports.__esModule = true;
  13837. exports["default"] = void 0;
  13838. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13839. var _types = /*@__PURE__*/ requireTypes();
  13840. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13841. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13842. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13843. var String = /*#__PURE__*/function (_Node) {
  13844. _inheritsLoose(String, _Node);
  13845. function String(opts) {
  13846. var _this;
  13847. _this = _Node.call(this, opts) || this;
  13848. _this.type = _types.STRING;
  13849. return _this;
  13850. }
  13851. return String;
  13852. }(_node["default"]);
  13853. exports["default"] = String;
  13854. module.exports = exports.default;
  13855. } (string, string.exports));
  13856. return string.exports;
  13857. }
  13858. var pseudo = {exports: {}};
  13859. var hasRequiredPseudo;
  13860. function requirePseudo () {
  13861. if (hasRequiredPseudo) return pseudo.exports;
  13862. hasRequiredPseudo = 1;
  13863. (function (module, exports) {
  13864. exports.__esModule = true;
  13865. exports["default"] = void 0;
  13866. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13867. var _types = /*@__PURE__*/ requireTypes();
  13868. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13869. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13870. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13871. var Pseudo = /*#__PURE__*/function (_Container) {
  13872. _inheritsLoose(Pseudo, _Container);
  13873. function Pseudo(opts) {
  13874. var _this;
  13875. _this = _Container.call(this, opts) || this;
  13876. _this.type = _types.PSEUDO;
  13877. return _this;
  13878. }
  13879. var _proto = Pseudo.prototype;
  13880. _proto.toString = function toString() {
  13881. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  13882. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  13883. };
  13884. return Pseudo;
  13885. }(_container["default"]);
  13886. exports["default"] = Pseudo;
  13887. module.exports = exports.default;
  13888. } (pseudo, pseudo.exports));
  13889. return pseudo.exports;
  13890. }
  13891. var attribute = {};
  13892. var hasRequiredAttribute;
  13893. function requireAttribute () {
  13894. if (hasRequiredAttribute) return attribute;
  13895. hasRequiredAttribute = 1;
  13896. (function (exports) {
  13897. exports.__esModule = true;
  13898. exports["default"] = void 0;
  13899. exports.unescapeValue = unescapeValue;
  13900. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13901. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  13902. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13903. var _types = /*@__PURE__*/ requireTypes();
  13904. var _CSSESC_QUOTE_OPTIONS;
  13905. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13906. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  13907. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13908. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13909. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13910. var deprecate = /*@__PURE__*/ requireNode$1();
  13911. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  13912. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  13913. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  13914. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  13915. function unescapeValue(value) {
  13916. var deprecatedUsage = false;
  13917. var quoteMark = null;
  13918. var unescaped = value;
  13919. var m = unescaped.match(WRAPPED_IN_QUOTES);
  13920. if (m) {
  13921. quoteMark = m[1];
  13922. unescaped = m[2];
  13923. }
  13924. unescaped = (0, _unesc["default"])(unescaped);
  13925. if (unescaped !== value) {
  13926. deprecatedUsage = true;
  13927. }
  13928. return {
  13929. deprecatedUsage: deprecatedUsage,
  13930. unescaped: unescaped,
  13931. quoteMark: quoteMark
  13932. };
  13933. }
  13934. function handleDeprecatedContructorOpts(opts) {
  13935. if (opts.quoteMark !== undefined) {
  13936. return opts;
  13937. }
  13938. if (opts.value === undefined) {
  13939. return opts;
  13940. }
  13941. warnOfDeprecatedConstructor();
  13942. var _unescapeValue = unescapeValue(opts.value),
  13943. quoteMark = _unescapeValue.quoteMark,
  13944. unescaped = _unescapeValue.unescaped;
  13945. if (!opts.raws) {
  13946. opts.raws = {};
  13947. }
  13948. if (opts.raws.value === undefined) {
  13949. opts.raws.value = opts.value;
  13950. }
  13951. opts.value = unescaped;
  13952. opts.quoteMark = quoteMark;
  13953. return opts;
  13954. }
  13955. var Attribute = /*#__PURE__*/function (_Namespace) {
  13956. _inheritsLoose(Attribute, _Namespace);
  13957. function Attribute(opts) {
  13958. var _this;
  13959. if (opts === void 0) {
  13960. opts = {};
  13961. }
  13962. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  13963. _this.type = _types.ATTRIBUTE;
  13964. _this.raws = _this.raws || {};
  13965. Object.defineProperty(_this.raws, 'unquoted', {
  13966. get: deprecate(function () {
  13967. return _this.value;
  13968. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  13969. set: deprecate(function () {
  13970. return _this.value;
  13971. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  13972. });
  13973. _this._constructed = true;
  13974. return _this;
  13975. }
  13976. /**
  13977. * Returns the Attribute's value quoted such that it would be legal to use
  13978. * in the value of a css file. The original value's quotation setting
  13979. * used for stringification is left unchanged. See `setValue(value, options)`
  13980. * if you want to control the quote settings of a new value for the attribute.
  13981. *
  13982. * You can also change the quotation used for the current value by setting quoteMark.
  13983. *
  13984. * Options:
  13985. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  13986. * option is not set, the original value for quoteMark will be used. If
  13987. * indeterminate, a double quote is used. The legal values are:
  13988. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  13989. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  13990. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  13991. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  13992. * over the quoteMark option value.
  13993. * * smart {boolean} - if true, will select a quote mark based on the value
  13994. * and the other options specified here. See the `smartQuoteMark()`
  13995. * method.
  13996. **/
  13997. var _proto = Attribute.prototype;
  13998. _proto.getQuotedValue = function getQuotedValue(options) {
  13999. if (options === void 0) {
  14000. options = {};
  14001. }
  14002. var quoteMark = this._determineQuoteMark(options);
  14003. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  14004. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  14005. return escaped;
  14006. };
  14007. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  14008. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  14009. }
  14010. /**
  14011. * Set the unescaped value with the specified quotation options. The value
  14012. * provided must not include any wrapping quote marks -- those quotes will
  14013. * be interpreted as part of the value and escaped accordingly.
  14014. */;
  14015. _proto.setValue = function setValue(value, options) {
  14016. if (options === void 0) {
  14017. options = {};
  14018. }
  14019. this._value = value;
  14020. this._quoteMark = this._determineQuoteMark(options);
  14021. this._syncRawValue();
  14022. }
  14023. /**
  14024. * Intelligently select a quoteMark value based on the value's contents. If
  14025. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  14026. * mark will be picked that minimizes the number of escapes.
  14027. *
  14028. * If there's no clear winner, the quote mark from these options is used,
  14029. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  14030. * true). If the quoteMark is unspecified, a double quote is used.
  14031. *
  14032. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  14033. * from the quoteValue method.
  14034. */;
  14035. _proto.smartQuoteMark = function smartQuoteMark(options) {
  14036. var v = this.value;
  14037. var numSingleQuotes = v.replace(/[^']/g, '').length;
  14038. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  14039. if (numSingleQuotes + numDoubleQuotes === 0) {
  14040. var escaped = (0, _cssesc["default"])(v, {
  14041. isIdentifier: true
  14042. });
  14043. if (escaped === v) {
  14044. return Attribute.NO_QUOTE;
  14045. } else {
  14046. var pref = this.preferredQuoteMark(options);
  14047. if (pref === Attribute.NO_QUOTE) {
  14048. // pick a quote mark that isn't none and see if it's smaller
  14049. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  14050. var opts = CSSESC_QUOTE_OPTIONS[quote];
  14051. var quoteValue = (0, _cssesc["default"])(v, opts);
  14052. if (quoteValue.length < escaped.length) {
  14053. return quote;
  14054. }
  14055. }
  14056. return pref;
  14057. }
  14058. } else if (numDoubleQuotes === numSingleQuotes) {
  14059. return this.preferredQuoteMark(options);
  14060. } else if (numDoubleQuotes < numSingleQuotes) {
  14061. return Attribute.DOUBLE_QUOTE;
  14062. } else {
  14063. return Attribute.SINGLE_QUOTE;
  14064. }
  14065. }
  14066. /**
  14067. * Selects the preferred quote mark based on the options and the current quote mark value.
  14068. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  14069. * instead.
  14070. */;
  14071. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  14072. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  14073. if (quoteMark === undefined) {
  14074. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  14075. }
  14076. if (quoteMark === undefined) {
  14077. quoteMark = Attribute.DOUBLE_QUOTE;
  14078. }
  14079. return quoteMark;
  14080. };
  14081. _proto._syncRawValue = function _syncRawValue() {
  14082. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  14083. if (rawValue === this._value) {
  14084. if (this.raws) {
  14085. delete this.raws.value;
  14086. }
  14087. } else {
  14088. this.raws.value = rawValue;
  14089. }
  14090. };
  14091. _proto._handleEscapes = function _handleEscapes(prop, value) {
  14092. if (this._constructed) {
  14093. var escaped = (0, _cssesc["default"])(value, {
  14094. isIdentifier: true
  14095. });
  14096. if (escaped !== value) {
  14097. this.raws[prop] = escaped;
  14098. } else {
  14099. delete this.raws[prop];
  14100. }
  14101. }
  14102. };
  14103. _proto._spacesFor = function _spacesFor(name) {
  14104. var attrSpaces = {
  14105. before: '',
  14106. after: ''
  14107. };
  14108. var spaces = this.spaces[name] || {};
  14109. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  14110. return Object.assign(attrSpaces, spaces, rawSpaces);
  14111. };
  14112. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  14113. if (spaceName === void 0) {
  14114. spaceName = name;
  14115. }
  14116. if (concat === void 0) {
  14117. concat = defaultAttrConcat;
  14118. }
  14119. var attrSpaces = this._spacesFor(spaceName);
  14120. return concat(this.stringifyProperty(name), attrSpaces);
  14121. }
  14122. /**
  14123. * returns the offset of the attribute part specified relative to the
  14124. * start of the node of the output string.
  14125. *
  14126. * * "ns" - alias for "namespace"
  14127. * * "namespace" - the namespace if it exists.
  14128. * * "attribute" - the attribute name
  14129. * * "attributeNS" - the start of the attribute or its namespace
  14130. * * "operator" - the match operator of the attribute
  14131. * * "value" - The value (string or identifier)
  14132. * * "insensitive" - the case insensitivity flag;
  14133. * @param part One of the possible values inside an attribute.
  14134. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  14135. */;
  14136. _proto.offsetOf = function offsetOf(name) {
  14137. var count = 1;
  14138. var attributeSpaces = this._spacesFor("attribute");
  14139. count += attributeSpaces.before.length;
  14140. if (name === "namespace" || name === "ns") {
  14141. return this.namespace ? count : -1;
  14142. }
  14143. if (name === "attributeNS") {
  14144. return count;
  14145. }
  14146. count += this.namespaceString.length;
  14147. if (this.namespace) {
  14148. count += 1;
  14149. }
  14150. if (name === "attribute") {
  14151. return count;
  14152. }
  14153. count += this.stringifyProperty("attribute").length;
  14154. count += attributeSpaces.after.length;
  14155. var operatorSpaces = this._spacesFor("operator");
  14156. count += operatorSpaces.before.length;
  14157. var operator = this.stringifyProperty("operator");
  14158. if (name === "operator") {
  14159. return operator ? count : -1;
  14160. }
  14161. count += operator.length;
  14162. count += operatorSpaces.after.length;
  14163. var valueSpaces = this._spacesFor("value");
  14164. count += valueSpaces.before.length;
  14165. var value = this.stringifyProperty("value");
  14166. if (name === "value") {
  14167. return value ? count : -1;
  14168. }
  14169. count += value.length;
  14170. count += valueSpaces.after.length;
  14171. var insensitiveSpaces = this._spacesFor("insensitive");
  14172. count += insensitiveSpaces.before.length;
  14173. if (name === "insensitive") {
  14174. return this.insensitive ? count : -1;
  14175. }
  14176. return -1;
  14177. };
  14178. _proto.toString = function toString() {
  14179. var _this2 = this;
  14180. var selector = [this.rawSpaceBefore, '['];
  14181. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  14182. if (this.operator && (this.value || this.value === '')) {
  14183. selector.push(this._stringFor('operator'));
  14184. selector.push(this._stringFor('value'));
  14185. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  14186. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  14187. attrSpaces.before = " ";
  14188. }
  14189. return defaultAttrConcat(attrValue, attrSpaces);
  14190. }));
  14191. }
  14192. selector.push(']');
  14193. selector.push(this.rawSpaceAfter);
  14194. return selector.join('');
  14195. };
  14196. _createClass(Attribute, [{
  14197. key: "quoted",
  14198. get: function get() {
  14199. var qm = this.quoteMark;
  14200. return qm === "'" || qm === '"';
  14201. },
  14202. set: function set(value) {
  14203. warnOfDeprecatedQuotedAssignment();
  14204. }
  14205. /**
  14206. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  14207. * returns `null` if the value is not quoted.
  14208. * returns `undefined` if the quotation state is unknown (this can happen when
  14209. * the attribute is constructed without specifying a quote mark.)
  14210. */
  14211. }, {
  14212. key: "quoteMark",
  14213. get: function get() {
  14214. return this._quoteMark;
  14215. }
  14216. /**
  14217. * Set the quote mark to be used by this attribute's value.
  14218. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  14219. * value is updated accordingly.
  14220. *
  14221. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  14222. */,
  14223. set: function set(quoteMark) {
  14224. if (!this._constructed) {
  14225. this._quoteMark = quoteMark;
  14226. return;
  14227. }
  14228. if (this._quoteMark !== quoteMark) {
  14229. this._quoteMark = quoteMark;
  14230. this._syncRawValue();
  14231. }
  14232. }
  14233. }, {
  14234. key: "qualifiedAttribute",
  14235. get: function get() {
  14236. return this.qualifiedName(this.raws.attribute || this.attribute);
  14237. }
  14238. }, {
  14239. key: "insensitiveFlag",
  14240. get: function get() {
  14241. return this.insensitive ? 'i' : '';
  14242. }
  14243. }, {
  14244. key: "value",
  14245. get: function get() {
  14246. return this._value;
  14247. },
  14248. set:
  14249. /**
  14250. * Before 3.0, the value had to be set to an escaped value including any wrapped
  14251. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  14252. * is unescaped during parsing and any quote marks are removed.
  14253. *
  14254. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  14255. * a deprecation warning is raised when the new value contains any characters that would
  14256. * require escaping (including if it contains wrapped quotes).
  14257. *
  14258. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  14259. * how the new value is quoted.
  14260. */
  14261. function set(v) {
  14262. if (this._constructed) {
  14263. var _unescapeValue2 = unescapeValue(v),
  14264. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  14265. unescaped = _unescapeValue2.unescaped,
  14266. quoteMark = _unescapeValue2.quoteMark;
  14267. if (deprecatedUsage) {
  14268. warnOfDeprecatedValueAssignment();
  14269. }
  14270. if (unescaped === this._value && quoteMark === this._quoteMark) {
  14271. return;
  14272. }
  14273. this._value = unescaped;
  14274. this._quoteMark = quoteMark;
  14275. this._syncRawValue();
  14276. } else {
  14277. this._value = v;
  14278. }
  14279. }
  14280. }, {
  14281. key: "insensitive",
  14282. get: function get() {
  14283. return this._insensitive;
  14284. }
  14285. /**
  14286. * Set the case insensitive flag.
  14287. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  14288. * of the attribute is updated accordingly.
  14289. *
  14290. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  14291. */,
  14292. set: function set(insensitive) {
  14293. if (!insensitive) {
  14294. this._insensitive = false;
  14295. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  14296. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  14297. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  14298. this.raws.insensitiveFlag = undefined;
  14299. }
  14300. }
  14301. this._insensitive = insensitive;
  14302. }
  14303. }, {
  14304. key: "attribute",
  14305. get: function get() {
  14306. return this._attribute;
  14307. },
  14308. set: function set(name) {
  14309. this._handleEscapes("attribute", name);
  14310. this._attribute = name;
  14311. }
  14312. }]);
  14313. return Attribute;
  14314. }(_namespace["default"]);
  14315. exports["default"] = Attribute;
  14316. Attribute.NO_QUOTE = null;
  14317. Attribute.SINGLE_QUOTE = "'";
  14318. Attribute.DOUBLE_QUOTE = '"';
  14319. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  14320. "'": {
  14321. quotes: 'single',
  14322. wrap: true
  14323. },
  14324. '"': {
  14325. quotes: 'double',
  14326. wrap: true
  14327. }
  14328. }, _CSSESC_QUOTE_OPTIONS[null] = {
  14329. isIdentifier: true
  14330. }, _CSSESC_QUOTE_OPTIONS);
  14331. function defaultAttrConcat(attrValue, attrSpaces) {
  14332. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  14333. }
  14334. } (attribute));
  14335. return attribute;
  14336. }
  14337. var universal = {exports: {}};
  14338. var hasRequiredUniversal;
  14339. function requireUniversal () {
  14340. if (hasRequiredUniversal) return universal.exports;
  14341. hasRequiredUniversal = 1;
  14342. (function (module, exports) {
  14343. exports.__esModule = true;
  14344. exports["default"] = void 0;
  14345. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14346. var _types = /*@__PURE__*/ requireTypes();
  14347. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14348. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14349. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14350. var Universal = /*#__PURE__*/function (_Namespace) {
  14351. _inheritsLoose(Universal, _Namespace);
  14352. function Universal(opts) {
  14353. var _this;
  14354. _this = _Namespace.call(this, opts) || this;
  14355. _this.type = _types.UNIVERSAL;
  14356. _this.value = '*';
  14357. return _this;
  14358. }
  14359. return Universal;
  14360. }(_namespace["default"]);
  14361. exports["default"] = Universal;
  14362. module.exports = exports.default;
  14363. } (universal, universal.exports));
  14364. return universal.exports;
  14365. }
  14366. var combinator = {exports: {}};
  14367. var hasRequiredCombinator;
  14368. function requireCombinator () {
  14369. if (hasRequiredCombinator) return combinator.exports;
  14370. hasRequiredCombinator = 1;
  14371. (function (module, exports) {
  14372. exports.__esModule = true;
  14373. exports["default"] = void 0;
  14374. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14375. var _types = /*@__PURE__*/ requireTypes();
  14376. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14377. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14378. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14379. var Combinator = /*#__PURE__*/function (_Node) {
  14380. _inheritsLoose(Combinator, _Node);
  14381. function Combinator(opts) {
  14382. var _this;
  14383. _this = _Node.call(this, opts) || this;
  14384. _this.type = _types.COMBINATOR;
  14385. return _this;
  14386. }
  14387. return Combinator;
  14388. }(_node["default"]);
  14389. exports["default"] = Combinator;
  14390. module.exports = exports.default;
  14391. } (combinator, combinator.exports));
  14392. return combinator.exports;
  14393. }
  14394. var nesting = {exports: {}};
  14395. var hasRequiredNesting;
  14396. function requireNesting () {
  14397. if (hasRequiredNesting) return nesting.exports;
  14398. hasRequiredNesting = 1;
  14399. (function (module, exports) {
  14400. exports.__esModule = true;
  14401. exports["default"] = void 0;
  14402. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14403. var _types = /*@__PURE__*/ requireTypes();
  14404. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14405. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14406. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14407. var Nesting = /*#__PURE__*/function (_Node) {
  14408. _inheritsLoose(Nesting, _Node);
  14409. function Nesting(opts) {
  14410. var _this;
  14411. _this = _Node.call(this, opts) || this;
  14412. _this.type = _types.NESTING;
  14413. _this.value = '&';
  14414. return _this;
  14415. }
  14416. return Nesting;
  14417. }(_node["default"]);
  14418. exports["default"] = Nesting;
  14419. module.exports = exports.default;
  14420. } (nesting, nesting.exports));
  14421. return nesting.exports;
  14422. }
  14423. var sortAscending = {exports: {}};
  14424. var hasRequiredSortAscending;
  14425. function requireSortAscending () {
  14426. if (hasRequiredSortAscending) return sortAscending.exports;
  14427. hasRequiredSortAscending = 1;
  14428. (function (module, exports) {
  14429. exports.__esModule = true;
  14430. exports["default"] = sortAscending;
  14431. function sortAscending(list) {
  14432. return list.sort(function (a, b) {
  14433. return a - b;
  14434. });
  14435. }
  14436. module.exports = exports.default;
  14437. } (sortAscending, sortAscending.exports));
  14438. return sortAscending.exports;
  14439. }
  14440. var tokenize = {};
  14441. var tokenTypes = {};
  14442. var hasRequiredTokenTypes;
  14443. function requireTokenTypes () {
  14444. if (hasRequiredTokenTypes) return tokenTypes;
  14445. hasRequiredTokenTypes = 1;
  14446. tokenTypes.__esModule = true;
  14447. tokenTypes.word = tokenTypes.tilde = tokenTypes.tab = tokenTypes.str = tokenTypes.space = tokenTypes.slash = tokenTypes.singleQuote = tokenTypes.semicolon = tokenTypes.plus = tokenTypes.pipe = tokenTypes.openSquare = tokenTypes.openParenthesis = tokenTypes.newline = tokenTypes.greaterThan = tokenTypes.feed = tokenTypes.equals = tokenTypes.doubleQuote = tokenTypes.dollar = tokenTypes.cr = tokenTypes.comment = tokenTypes.comma = tokenTypes.combinator = tokenTypes.colon = tokenTypes.closeSquare = tokenTypes.closeParenthesis = tokenTypes.caret = tokenTypes.bang = tokenTypes.backslash = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0;
  14448. var ampersand = 38; // `&`.charCodeAt(0);
  14449. tokenTypes.ampersand = ampersand;
  14450. var asterisk = 42; // `*`.charCodeAt(0);
  14451. tokenTypes.asterisk = asterisk;
  14452. var at = 64; // `@`.charCodeAt(0);
  14453. tokenTypes.at = at;
  14454. var comma = 44; // `,`.charCodeAt(0);
  14455. tokenTypes.comma = comma;
  14456. var colon = 58; // `:`.charCodeAt(0);
  14457. tokenTypes.colon = colon;
  14458. var semicolon = 59; // `;`.charCodeAt(0);
  14459. tokenTypes.semicolon = semicolon;
  14460. var openParenthesis = 40; // `(`.charCodeAt(0);
  14461. tokenTypes.openParenthesis = openParenthesis;
  14462. var closeParenthesis = 41; // `)`.charCodeAt(0);
  14463. tokenTypes.closeParenthesis = closeParenthesis;
  14464. var openSquare = 91; // `[`.charCodeAt(0);
  14465. tokenTypes.openSquare = openSquare;
  14466. var closeSquare = 93; // `]`.charCodeAt(0);
  14467. tokenTypes.closeSquare = closeSquare;
  14468. var dollar = 36; // `$`.charCodeAt(0);
  14469. tokenTypes.dollar = dollar;
  14470. var tilde = 126; // `~`.charCodeAt(0);
  14471. tokenTypes.tilde = tilde;
  14472. var caret = 94; // `^`.charCodeAt(0);
  14473. tokenTypes.caret = caret;
  14474. var plus = 43; // `+`.charCodeAt(0);
  14475. tokenTypes.plus = plus;
  14476. var equals = 61; // `=`.charCodeAt(0);
  14477. tokenTypes.equals = equals;
  14478. var pipe = 124; // `|`.charCodeAt(0);
  14479. tokenTypes.pipe = pipe;
  14480. var greaterThan = 62; // `>`.charCodeAt(0);
  14481. tokenTypes.greaterThan = greaterThan;
  14482. var space = 32; // ` `.charCodeAt(0);
  14483. tokenTypes.space = space;
  14484. var singleQuote = 39; // `'`.charCodeAt(0);
  14485. tokenTypes.singleQuote = singleQuote;
  14486. var doubleQuote = 34; // `"`.charCodeAt(0);
  14487. tokenTypes.doubleQuote = doubleQuote;
  14488. var slash = 47; // `/`.charCodeAt(0);
  14489. tokenTypes.slash = slash;
  14490. var bang = 33; // `!`.charCodeAt(0);
  14491. tokenTypes.bang = bang;
  14492. var backslash = 92; // '\\'.charCodeAt(0);
  14493. tokenTypes.backslash = backslash;
  14494. var cr = 13; // '\r'.charCodeAt(0);
  14495. tokenTypes.cr = cr;
  14496. var feed = 12; // '\f'.charCodeAt(0);
  14497. tokenTypes.feed = feed;
  14498. var newline = 10; // '\n'.charCodeAt(0);
  14499. tokenTypes.newline = newline;
  14500. var tab = 9; // '\t'.charCodeAt(0);
  14501. // Expose aliases primarily for readability.
  14502. tokenTypes.tab = tab;
  14503. var str = singleQuote;
  14504. // No good single character representation!
  14505. tokenTypes.str = str;
  14506. var comment = -1;
  14507. tokenTypes.comment = comment;
  14508. var word = -2;
  14509. tokenTypes.word = word;
  14510. var combinator = -3;
  14511. tokenTypes.combinator = combinator;
  14512. return tokenTypes;
  14513. }
  14514. var hasRequiredTokenize;
  14515. function requireTokenize () {
  14516. if (hasRequiredTokenize) return tokenize;
  14517. hasRequiredTokenize = 1;
  14518. (function (exports) {
  14519. exports.__esModule = true;
  14520. exports.FIELDS = void 0;
  14521. exports["default"] = tokenize;
  14522. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14523. var _unescapable, _wordDelimiters;
  14524. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  14525. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  14526. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  14527. var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
  14528. var hex = {};
  14529. var hexChars = "0123456789abcdefABCDEF";
  14530. for (var i = 0; i < hexChars.length; i++) {
  14531. hex[hexChars.charCodeAt(i)] = true;
  14532. }
  14533. /**
  14534. * Returns the last index of the bar css word
  14535. * @param {string} css The string in which the word begins
  14536. * @param {number} start The index into the string where word's first letter occurs
  14537. */
  14538. function consumeWord(css, start) {
  14539. var next = start;
  14540. var code;
  14541. do {
  14542. code = css.charCodeAt(next);
  14543. if (wordDelimiters[code]) {
  14544. return next - 1;
  14545. } else if (code === t.backslash) {
  14546. next = consumeEscape(css, next) + 1;
  14547. } else {
  14548. // All other characters are part of the word
  14549. next++;
  14550. }
  14551. } while (next < css.length);
  14552. return next - 1;
  14553. }
  14554. /**
  14555. * Returns the last index of the escape sequence
  14556. * @param {string} css The string in which the sequence begins
  14557. * @param {number} start The index into the string where escape character (`\`) occurs.
  14558. */
  14559. function consumeEscape(css, start) {
  14560. var next = start;
  14561. var code = css.charCodeAt(next + 1);
  14562. if (unescapable[code]) ; else if (hex[code]) {
  14563. var hexDigits = 0;
  14564. // consume up to 6 hex chars
  14565. do {
  14566. next++;
  14567. hexDigits++;
  14568. code = css.charCodeAt(next + 1);
  14569. } while (hex[code] && hexDigits < 6);
  14570. // if fewer than 6 hex chars, a trailing space ends the escape
  14571. if (hexDigits < 6 && code === t.space) {
  14572. next++;
  14573. }
  14574. } else {
  14575. // the next char is part of the current word
  14576. next++;
  14577. }
  14578. return next;
  14579. }
  14580. var FIELDS = {
  14581. TYPE: 0,
  14582. START_LINE: 1,
  14583. START_COL: 2,
  14584. END_LINE: 3,
  14585. END_COL: 4,
  14586. START_POS: 5,
  14587. END_POS: 6
  14588. };
  14589. exports.FIELDS = FIELDS;
  14590. function tokenize(input) {
  14591. var tokens = [];
  14592. var css = input.css.valueOf();
  14593. var _css = css,
  14594. length = _css.length;
  14595. var offset = -1;
  14596. var line = 1;
  14597. var start = 0;
  14598. var end = 0;
  14599. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  14600. function unclosed(what, fix) {
  14601. if (input.safe) {
  14602. // fyi: this is never set to true.
  14603. css += fix;
  14604. next = css.length - 1;
  14605. } else {
  14606. throw input.error('Unclosed ' + what, line, start - offset, start);
  14607. }
  14608. }
  14609. while (start < length) {
  14610. code = css.charCodeAt(start);
  14611. if (code === t.newline) {
  14612. offset = start;
  14613. line += 1;
  14614. }
  14615. switch (code) {
  14616. case t.space:
  14617. case t.tab:
  14618. case t.newline:
  14619. case t.cr:
  14620. case t.feed:
  14621. next = start;
  14622. do {
  14623. next += 1;
  14624. code = css.charCodeAt(next);
  14625. if (code === t.newline) {
  14626. offset = next;
  14627. line += 1;
  14628. }
  14629. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  14630. tokenType = t.space;
  14631. endLine = line;
  14632. endColumn = next - offset - 1;
  14633. end = next;
  14634. break;
  14635. case t.plus:
  14636. case t.greaterThan:
  14637. case t.tilde:
  14638. case t.pipe:
  14639. next = start;
  14640. do {
  14641. next += 1;
  14642. code = css.charCodeAt(next);
  14643. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  14644. tokenType = t.combinator;
  14645. endLine = line;
  14646. endColumn = start - offset;
  14647. end = next;
  14648. break;
  14649. // Consume these characters as single tokens.
  14650. case t.asterisk:
  14651. case t.ampersand:
  14652. case t.bang:
  14653. case t.comma:
  14654. case t.equals:
  14655. case t.dollar:
  14656. case t.caret:
  14657. case t.openSquare:
  14658. case t.closeSquare:
  14659. case t.colon:
  14660. case t.semicolon:
  14661. case t.openParenthesis:
  14662. case t.closeParenthesis:
  14663. next = start;
  14664. tokenType = code;
  14665. endLine = line;
  14666. endColumn = start - offset;
  14667. end = next + 1;
  14668. break;
  14669. case t.singleQuote:
  14670. case t.doubleQuote:
  14671. quote = code === t.singleQuote ? "'" : '"';
  14672. next = start;
  14673. do {
  14674. escaped = false;
  14675. next = css.indexOf(quote, next + 1);
  14676. if (next === -1) {
  14677. unclosed('quote', quote);
  14678. }
  14679. escapePos = next;
  14680. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  14681. escapePos -= 1;
  14682. escaped = !escaped;
  14683. }
  14684. } while (escaped);
  14685. tokenType = t.str;
  14686. endLine = line;
  14687. endColumn = start - offset;
  14688. end = next + 1;
  14689. break;
  14690. default:
  14691. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  14692. next = css.indexOf('*/', start + 2) + 1;
  14693. if (next === 0) {
  14694. unclosed('comment', '*/');
  14695. }
  14696. content = css.slice(start, next + 1);
  14697. lines = content.split('\n');
  14698. last = lines.length - 1;
  14699. if (last > 0) {
  14700. nextLine = line + last;
  14701. nextOffset = next - lines[last].length;
  14702. } else {
  14703. nextLine = line;
  14704. nextOffset = offset;
  14705. }
  14706. tokenType = t.comment;
  14707. line = nextLine;
  14708. endLine = nextLine;
  14709. endColumn = next - nextOffset;
  14710. } else if (code === t.slash) {
  14711. next = start;
  14712. tokenType = code;
  14713. endLine = line;
  14714. endColumn = start - offset;
  14715. end = next + 1;
  14716. } else {
  14717. next = consumeWord(css, start);
  14718. tokenType = t.word;
  14719. endLine = line;
  14720. endColumn = next - offset;
  14721. }
  14722. end = next + 1;
  14723. break;
  14724. }
  14725. // Ensure that the token structure remains consistent
  14726. tokens.push([tokenType,
  14727. // [0] Token type
  14728. line,
  14729. // [1] Starting line
  14730. start - offset,
  14731. // [2] Starting column
  14732. endLine,
  14733. // [3] Ending line
  14734. endColumn,
  14735. // [4] Ending column
  14736. start,
  14737. // [5] Start position / Source index
  14738. end // [6] End position
  14739. ]);
  14740. // Reset offset for the next token
  14741. if (nextOffset) {
  14742. offset = nextOffset;
  14743. nextOffset = null;
  14744. }
  14745. start = end;
  14746. }
  14747. return tokens;
  14748. }
  14749. } (tokenize));
  14750. return tokenize;
  14751. }
  14752. var hasRequiredParser;
  14753. function requireParser () {
  14754. if (hasRequiredParser) return parser.exports;
  14755. hasRequiredParser = 1;
  14756. (function (module, exports) {
  14757. exports.__esModule = true;
  14758. exports["default"] = void 0;
  14759. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  14760. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  14761. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  14762. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  14763. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  14764. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  14765. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  14766. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  14767. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  14768. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  14769. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  14770. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  14771. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  14772. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  14773. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14774. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  14775. var _util = /*@__PURE__*/ requireUtil();
  14776. var _WHITESPACE_TOKENS, _Object$assign;
  14777. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  14778. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  14779. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14780. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  14781. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14782. var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  14783. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  14784. function tokenStart(token) {
  14785. return {
  14786. line: token[_tokenize.FIELDS.START_LINE],
  14787. column: token[_tokenize.FIELDS.START_COL]
  14788. };
  14789. }
  14790. function tokenEnd(token) {
  14791. return {
  14792. line: token[_tokenize.FIELDS.END_LINE],
  14793. column: token[_tokenize.FIELDS.END_COL]
  14794. };
  14795. }
  14796. function getSource(startLine, startColumn, endLine, endColumn) {
  14797. return {
  14798. start: {
  14799. line: startLine,
  14800. column: startColumn
  14801. },
  14802. end: {
  14803. line: endLine,
  14804. column: endColumn
  14805. }
  14806. };
  14807. }
  14808. function getTokenSource(token) {
  14809. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  14810. }
  14811. function getTokenSourceSpan(startToken, endToken) {
  14812. if (!startToken) {
  14813. return undefined;
  14814. }
  14815. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  14816. }
  14817. function unescapeProp(node, prop) {
  14818. var value = node[prop];
  14819. if (typeof value !== "string") {
  14820. return;
  14821. }
  14822. if (value.indexOf("\\") !== -1) {
  14823. (0, _util.ensureObject)(node, 'raws');
  14824. node[prop] = (0, _util.unesc)(value);
  14825. if (node.raws[prop] === undefined) {
  14826. node.raws[prop] = value;
  14827. }
  14828. }
  14829. return node;
  14830. }
  14831. function indexesOf(array, item) {
  14832. var i = -1;
  14833. var indexes = [];
  14834. while ((i = array.indexOf(item, i + 1)) !== -1) {
  14835. indexes.push(i);
  14836. }
  14837. return indexes;
  14838. }
  14839. function uniqs() {
  14840. var list = Array.prototype.concat.apply([], arguments);
  14841. return list.filter(function (item, i) {
  14842. return i === list.indexOf(item);
  14843. });
  14844. }
  14845. var Parser = /*#__PURE__*/function () {
  14846. function Parser(rule, options) {
  14847. if (options === void 0) {
  14848. options = {};
  14849. }
  14850. this.rule = rule;
  14851. this.options = Object.assign({
  14852. lossy: false,
  14853. safe: false
  14854. }, options);
  14855. this.position = 0;
  14856. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  14857. this.tokens = (0, _tokenize["default"])({
  14858. css: this.css,
  14859. error: this._errorGenerator(),
  14860. safe: this.options.safe
  14861. });
  14862. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  14863. this.root = new _root["default"]({
  14864. source: rootSource
  14865. });
  14866. this.root.errorGenerator = this._errorGenerator();
  14867. var selector = new _selector["default"]({
  14868. source: {
  14869. start: {
  14870. line: 1,
  14871. column: 1
  14872. }
  14873. },
  14874. sourceIndex: 0
  14875. });
  14876. this.root.append(selector);
  14877. this.current = selector;
  14878. this.loop();
  14879. }
  14880. var _proto = Parser.prototype;
  14881. _proto._errorGenerator = function _errorGenerator() {
  14882. var _this = this;
  14883. return function (message, errorOptions) {
  14884. if (typeof _this.rule === 'string') {
  14885. return new Error(message);
  14886. }
  14887. return _this.rule.error(message, errorOptions);
  14888. };
  14889. };
  14890. _proto.attribute = function attribute() {
  14891. var attr = [];
  14892. var startingToken = this.currToken;
  14893. this.position++;
  14894. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14895. attr.push(this.currToken);
  14896. this.position++;
  14897. }
  14898. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14899. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  14900. }
  14901. var len = attr.length;
  14902. var node = {
  14903. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  14904. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  14905. };
  14906. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  14907. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  14908. }
  14909. var pos = 0;
  14910. var spaceBefore = '';
  14911. var commentBefore = '';
  14912. var lastAdded = null;
  14913. var spaceAfterMeaningfulToken = false;
  14914. while (pos < len) {
  14915. var token = attr[pos];
  14916. var content = this.content(token);
  14917. var next = attr[pos + 1];
  14918. switch (token[_tokenize.FIELDS.TYPE]) {
  14919. case tokens.space:
  14920. // if (
  14921. // len === 1 ||
  14922. // pos === 0 && this.content(next) === '|'
  14923. // ) {
  14924. // return this.expected('attribute', token[TOKEN.START_POS], content);
  14925. // }
  14926. spaceAfterMeaningfulToken = true;
  14927. if (this.options.lossy) {
  14928. break;
  14929. }
  14930. if (lastAdded) {
  14931. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  14932. var prevContent = node.spaces[lastAdded].after || '';
  14933. node.spaces[lastAdded].after = prevContent + content;
  14934. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  14935. if (existingComment) {
  14936. node.raws.spaces[lastAdded].after = existingComment + content;
  14937. }
  14938. } else {
  14939. spaceBefore = spaceBefore + content;
  14940. commentBefore = commentBefore + content;
  14941. }
  14942. break;
  14943. case tokens.asterisk:
  14944. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14945. node.operator = content;
  14946. lastAdded = 'operator';
  14947. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  14948. if (spaceBefore) {
  14949. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14950. node.spaces.attribute.before = spaceBefore;
  14951. spaceBefore = '';
  14952. }
  14953. if (commentBefore) {
  14954. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14955. node.raws.spaces.attribute.before = spaceBefore;
  14956. commentBefore = '';
  14957. }
  14958. node.namespace = (node.namespace || "") + content;
  14959. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  14960. if (rawValue) {
  14961. node.raws.namespace += content;
  14962. }
  14963. lastAdded = 'namespace';
  14964. }
  14965. spaceAfterMeaningfulToken = false;
  14966. break;
  14967. case tokens.dollar:
  14968. if (lastAdded === "value") {
  14969. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  14970. node.value += "$";
  14971. if (oldRawValue) {
  14972. node.raws.value = oldRawValue + "$";
  14973. }
  14974. break;
  14975. }
  14976. // Falls through
  14977. case tokens.caret:
  14978. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14979. node.operator = content;
  14980. lastAdded = 'operator';
  14981. }
  14982. spaceAfterMeaningfulToken = false;
  14983. break;
  14984. case tokens.combinator:
  14985. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14986. node.operator = content;
  14987. lastAdded = 'operator';
  14988. }
  14989. if (content !== '|') {
  14990. spaceAfterMeaningfulToken = false;
  14991. break;
  14992. }
  14993. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14994. node.operator = content;
  14995. lastAdded = 'operator';
  14996. } else if (!node.namespace && !node.attribute) {
  14997. node.namespace = true;
  14998. }
  14999. spaceAfterMeaningfulToken = false;
  15000. break;
  15001. case tokens.word:
  15002. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  15003. // this look-ahead probably fails with comment nodes involved.
  15004. !node.operator && !node.namespace) {
  15005. node.namespace = content;
  15006. lastAdded = 'namespace';
  15007. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  15008. if (spaceBefore) {
  15009. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  15010. node.spaces.attribute.before = spaceBefore;
  15011. spaceBefore = '';
  15012. }
  15013. if (commentBefore) {
  15014. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  15015. node.raws.spaces.attribute.before = commentBefore;
  15016. commentBefore = '';
  15017. }
  15018. node.attribute = (node.attribute || "") + content;
  15019. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  15020. if (_rawValue) {
  15021. node.raws.attribute += content;
  15022. }
  15023. lastAdded = 'attribute';
  15024. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  15025. var _unescaped = (0, _util.unesc)(content);
  15026. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  15027. var oldValue = node.value || '';
  15028. node.value = oldValue + _unescaped;
  15029. node.quoteMark = null;
  15030. if (_unescaped !== content || _oldRawValue) {
  15031. (0, _util.ensureObject)(node, 'raws');
  15032. node.raws.value = (_oldRawValue || oldValue) + content;
  15033. }
  15034. lastAdded = 'value';
  15035. } else {
  15036. var insensitive = content === 'i' || content === "I";
  15037. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  15038. node.insensitive = insensitive;
  15039. if (!insensitive || content === "I") {
  15040. (0, _util.ensureObject)(node, 'raws');
  15041. node.raws.insensitiveFlag = content;
  15042. }
  15043. lastAdded = 'insensitive';
  15044. if (spaceBefore) {
  15045. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  15046. node.spaces.insensitive.before = spaceBefore;
  15047. spaceBefore = '';
  15048. }
  15049. if (commentBefore) {
  15050. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  15051. node.raws.spaces.insensitive.before = commentBefore;
  15052. commentBefore = '';
  15053. }
  15054. } else if (node.value || node.value === '') {
  15055. lastAdded = 'value';
  15056. node.value += content;
  15057. if (node.raws.value) {
  15058. node.raws.value += content;
  15059. }
  15060. }
  15061. }
  15062. spaceAfterMeaningfulToken = false;
  15063. break;
  15064. case tokens.str:
  15065. if (!node.attribute || !node.operator) {
  15066. return this.error("Expected an attribute followed by an operator preceding the string.", {
  15067. index: token[_tokenize.FIELDS.START_POS]
  15068. });
  15069. }
  15070. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  15071. unescaped = _unescapeValue.unescaped,
  15072. quoteMark = _unescapeValue.quoteMark;
  15073. node.value = unescaped;
  15074. node.quoteMark = quoteMark;
  15075. lastAdded = 'value';
  15076. (0, _util.ensureObject)(node, 'raws');
  15077. node.raws.value = content;
  15078. spaceAfterMeaningfulToken = false;
  15079. break;
  15080. case tokens.equals:
  15081. if (!node.attribute) {
  15082. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  15083. }
  15084. if (node.value) {
  15085. return this.error('Unexpected "=" found; an operator was already defined.', {
  15086. index: token[_tokenize.FIELDS.START_POS]
  15087. });
  15088. }
  15089. node.operator = node.operator ? node.operator + content : content;
  15090. lastAdded = 'operator';
  15091. spaceAfterMeaningfulToken = false;
  15092. break;
  15093. case tokens.comment:
  15094. if (lastAdded) {
  15095. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  15096. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  15097. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  15098. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  15099. node.raws.spaces[lastAdded].after = rawLastComment + content;
  15100. } else {
  15101. var lastValue = node[lastAdded] || '';
  15102. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  15103. (0, _util.ensureObject)(node, 'raws');
  15104. node.raws[lastAdded] = rawLastValue + content;
  15105. }
  15106. } else {
  15107. commentBefore = commentBefore + content;
  15108. }
  15109. break;
  15110. default:
  15111. return this.error("Unexpected \"" + content + "\" found.", {
  15112. index: token[_tokenize.FIELDS.START_POS]
  15113. });
  15114. }
  15115. pos++;
  15116. }
  15117. unescapeProp(node, "attribute");
  15118. unescapeProp(node, "namespace");
  15119. this.newNode(new _attribute["default"](node));
  15120. this.position++;
  15121. }
  15122. /**
  15123. * return a node containing meaningless garbage up to (but not including) the specified token position.
  15124. * if the token position is negative, all remaining tokens are consumed.
  15125. *
  15126. * This returns an array containing a single string node if all whitespace,
  15127. * otherwise an array of comment nodes with space before and after.
  15128. *
  15129. * These tokens are not added to the current selector, the caller can add them or use them to amend
  15130. * a previous node's space metadata.
  15131. *
  15132. * In lossy mode, this returns only comments.
  15133. */;
  15134. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  15135. if (stopPosition < 0) {
  15136. stopPosition = this.tokens.length;
  15137. }
  15138. var startPosition = this.position;
  15139. var nodes = [];
  15140. var space = "";
  15141. var lastComment = undefined;
  15142. do {
  15143. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  15144. if (!this.options.lossy) {
  15145. space += this.content();
  15146. }
  15147. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  15148. var spaces = {};
  15149. if (space) {
  15150. spaces.before = space;
  15151. space = "";
  15152. }
  15153. lastComment = new _comment["default"]({
  15154. value: this.content(),
  15155. source: getTokenSource(this.currToken),
  15156. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15157. spaces: spaces
  15158. });
  15159. nodes.push(lastComment);
  15160. }
  15161. } while (++this.position < stopPosition);
  15162. if (space) {
  15163. if (lastComment) {
  15164. lastComment.spaces.after = space;
  15165. } else if (!this.options.lossy) {
  15166. var firstToken = this.tokens[startPosition];
  15167. var lastToken = this.tokens[this.position - 1];
  15168. nodes.push(new _string["default"]({
  15169. value: '',
  15170. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  15171. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15172. spaces: {
  15173. before: space,
  15174. after: ''
  15175. }
  15176. }));
  15177. }
  15178. }
  15179. return nodes;
  15180. }
  15181. /**
  15182. *
  15183. * @param {*} nodes
  15184. */;
  15185. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  15186. var _this2 = this;
  15187. if (requiredSpace === void 0) {
  15188. requiredSpace = false;
  15189. }
  15190. var space = "";
  15191. var rawSpace = "";
  15192. nodes.forEach(function (n) {
  15193. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  15194. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  15195. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  15196. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  15197. });
  15198. if (rawSpace === space) {
  15199. rawSpace = undefined;
  15200. }
  15201. var result = {
  15202. space: space,
  15203. rawSpace: rawSpace
  15204. };
  15205. return result;
  15206. };
  15207. _proto.isNamedCombinator = function isNamedCombinator(position) {
  15208. if (position === void 0) {
  15209. position = this.position;
  15210. }
  15211. return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  15212. };
  15213. _proto.namedCombinator = function namedCombinator() {
  15214. if (this.isNamedCombinator()) {
  15215. var nameRaw = this.content(this.tokens[this.position + 1]);
  15216. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  15217. var raws = {};
  15218. if (name !== nameRaw) {
  15219. raws.value = "/" + nameRaw + "/";
  15220. }
  15221. var node = new _combinator["default"]({
  15222. value: "/" + name + "/",
  15223. source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
  15224. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15225. raws: raws
  15226. });
  15227. this.position = this.position + 3;
  15228. return node;
  15229. } else {
  15230. this.unexpected();
  15231. }
  15232. };
  15233. _proto.combinator = function combinator() {
  15234. var _this3 = this;
  15235. if (this.content() === '|') {
  15236. return this.namespace();
  15237. }
  15238. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  15239. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  15240. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15241. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15242. if (nodes.length > 0) {
  15243. var last = this.current.last;
  15244. if (last) {
  15245. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  15246. space = _this$convertWhitespa.space,
  15247. rawSpace = _this$convertWhitespa.rawSpace;
  15248. if (rawSpace !== undefined) {
  15249. last.rawSpaceAfter += rawSpace;
  15250. }
  15251. last.spaces.after += space;
  15252. } else {
  15253. nodes.forEach(function (n) {
  15254. return _this3.newNode(n);
  15255. });
  15256. }
  15257. }
  15258. return;
  15259. }
  15260. var firstToken = this.currToken;
  15261. var spaceOrDescendantSelectorNodes = undefined;
  15262. if (nextSigTokenPos > this.position) {
  15263. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15264. }
  15265. var node;
  15266. if (this.isNamedCombinator()) {
  15267. node = this.namedCombinator();
  15268. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  15269. node = new _combinator["default"]({
  15270. value: this.content(),
  15271. source: getTokenSource(this.currToken),
  15272. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  15273. });
  15274. this.position++;
  15275. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  15276. this.unexpected();
  15277. }
  15278. if (node) {
  15279. if (spaceOrDescendantSelectorNodes) {
  15280. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  15281. _space = _this$convertWhitespa2.space,
  15282. _rawSpace = _this$convertWhitespa2.rawSpace;
  15283. node.spaces.before = _space;
  15284. node.rawSpaceBefore = _rawSpace;
  15285. }
  15286. } else {
  15287. // descendant combinator
  15288. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  15289. _space2 = _this$convertWhitespa3.space,
  15290. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  15291. if (!_rawSpace2) {
  15292. _rawSpace2 = _space2;
  15293. }
  15294. var spaces = {};
  15295. var raws = {
  15296. spaces: {}
  15297. };
  15298. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  15299. spaces.before = _space2.slice(0, _space2.length - 1);
  15300. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  15301. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  15302. spaces.after = _space2.slice(1);
  15303. raws.spaces.after = _rawSpace2.slice(1);
  15304. } else {
  15305. raws.value = _rawSpace2;
  15306. }
  15307. node = new _combinator["default"]({
  15308. value: ' ',
  15309. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  15310. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15311. spaces: spaces,
  15312. raws: raws
  15313. });
  15314. }
  15315. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  15316. node.spaces.after = this.optionalSpace(this.content());
  15317. this.position++;
  15318. }
  15319. return this.newNode(node);
  15320. };
  15321. _proto.comma = function comma() {
  15322. if (this.position === this.tokens.length - 1) {
  15323. this.root.trailingComma = true;
  15324. this.position++;
  15325. return;
  15326. }
  15327. this.current._inferEndPosition();
  15328. var selector = new _selector["default"]({
  15329. source: {
  15330. start: tokenStart(this.tokens[this.position + 1])
  15331. },
  15332. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  15333. });
  15334. this.current.parent.append(selector);
  15335. this.current = selector;
  15336. this.position++;
  15337. };
  15338. _proto.comment = function comment() {
  15339. var current = this.currToken;
  15340. this.newNode(new _comment["default"]({
  15341. value: this.content(),
  15342. source: getTokenSource(current),
  15343. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15344. }));
  15345. this.position++;
  15346. };
  15347. _proto.error = function error(message, opts) {
  15348. throw this.root.error(message, opts);
  15349. };
  15350. _proto.missingBackslash = function missingBackslash() {
  15351. return this.error('Expected a backslash preceding the semicolon.', {
  15352. index: this.currToken[_tokenize.FIELDS.START_POS]
  15353. });
  15354. };
  15355. _proto.missingParenthesis = function missingParenthesis() {
  15356. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15357. };
  15358. _proto.missingSquareBracket = function missingSquareBracket() {
  15359. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15360. };
  15361. _proto.unexpected = function unexpected() {
  15362. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  15363. };
  15364. _proto.unexpectedPipe = function unexpectedPipe() {
  15365. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  15366. };
  15367. _proto.namespace = function namespace() {
  15368. var before = this.prevToken && this.content(this.prevToken) || true;
  15369. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15370. this.position++;
  15371. return this.word(before);
  15372. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  15373. this.position++;
  15374. return this.universal(before);
  15375. }
  15376. this.unexpectedPipe();
  15377. };
  15378. _proto.nesting = function nesting() {
  15379. if (this.nextToken) {
  15380. var nextContent = this.content(this.nextToken);
  15381. if (nextContent === "|") {
  15382. this.position++;
  15383. return;
  15384. }
  15385. }
  15386. var current = this.currToken;
  15387. this.newNode(new _nesting["default"]({
  15388. value: this.content(),
  15389. source: getTokenSource(current),
  15390. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15391. }));
  15392. this.position++;
  15393. };
  15394. _proto.parentheses = function parentheses() {
  15395. var last = this.current.last;
  15396. var unbalanced = 1;
  15397. this.position++;
  15398. if (last && last.type === types.PSEUDO) {
  15399. var selector = new _selector["default"]({
  15400. source: {
  15401. start: tokenStart(this.tokens[this.position])
  15402. },
  15403. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  15404. });
  15405. var cache = this.current;
  15406. last.append(selector);
  15407. this.current = selector;
  15408. while (this.position < this.tokens.length && unbalanced) {
  15409. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15410. unbalanced++;
  15411. }
  15412. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15413. unbalanced--;
  15414. }
  15415. if (unbalanced) {
  15416. this.parse();
  15417. } else {
  15418. this.current.source.end = tokenEnd(this.currToken);
  15419. this.current.parent.source.end = tokenEnd(this.currToken);
  15420. this.position++;
  15421. }
  15422. }
  15423. this.current = cache;
  15424. } else {
  15425. // I think this case should be an error. It's used to implement a basic parse of media queries
  15426. // but I don't think it's a good idea.
  15427. var parenStart = this.currToken;
  15428. var parenValue = "(";
  15429. var parenEnd;
  15430. while (this.position < this.tokens.length && unbalanced) {
  15431. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15432. unbalanced++;
  15433. }
  15434. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15435. unbalanced--;
  15436. }
  15437. parenEnd = this.currToken;
  15438. parenValue += this.parseParenthesisToken(this.currToken);
  15439. this.position++;
  15440. }
  15441. if (last) {
  15442. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  15443. } else {
  15444. this.newNode(new _string["default"]({
  15445. value: parenValue,
  15446. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  15447. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  15448. }));
  15449. }
  15450. }
  15451. if (unbalanced) {
  15452. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15453. }
  15454. };
  15455. _proto.pseudo = function pseudo() {
  15456. var _this4 = this;
  15457. var pseudoStr = '';
  15458. var startingToken = this.currToken;
  15459. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  15460. pseudoStr += this.content();
  15461. this.position++;
  15462. }
  15463. if (!this.currToken) {
  15464. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  15465. }
  15466. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15467. this.splitWord(false, function (first, length) {
  15468. pseudoStr += first;
  15469. _this4.newNode(new _pseudo["default"]({
  15470. value: pseudoStr,
  15471. source: getTokenSourceSpan(startingToken, _this4.currToken),
  15472. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15473. }));
  15474. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15475. _this4.error('Misplaced parenthesis.', {
  15476. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  15477. });
  15478. }
  15479. });
  15480. } else {
  15481. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  15482. }
  15483. };
  15484. _proto.space = function space() {
  15485. var content = this.content();
  15486. // Handle space before and after the selector
  15487. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  15488. return node.type === 'comment';
  15489. })) {
  15490. this.spaces = this.optionalSpace(content);
  15491. this.position++;
  15492. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15493. this.current.last.spaces.after = this.optionalSpace(content);
  15494. this.position++;
  15495. } else {
  15496. this.combinator();
  15497. }
  15498. };
  15499. _proto.string = function string() {
  15500. var current = this.currToken;
  15501. this.newNode(new _string["default"]({
  15502. value: this.content(),
  15503. source: getTokenSource(current),
  15504. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15505. }));
  15506. this.position++;
  15507. };
  15508. _proto.universal = function universal(namespace) {
  15509. var nextToken = this.nextToken;
  15510. if (nextToken && this.content(nextToken) === '|') {
  15511. this.position++;
  15512. return this.namespace();
  15513. }
  15514. var current = this.currToken;
  15515. this.newNode(new _universal["default"]({
  15516. value: this.content(),
  15517. source: getTokenSource(current),
  15518. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15519. }), namespace);
  15520. this.position++;
  15521. };
  15522. _proto.splitWord = function splitWord(namespace, firstCallback) {
  15523. var _this5 = this;
  15524. var nextToken = this.nextToken;
  15525. var word = this.content();
  15526. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  15527. this.position++;
  15528. var current = this.content();
  15529. word += current;
  15530. if (current.lastIndexOf('\\') === current.length - 1) {
  15531. var next = this.nextToken;
  15532. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  15533. word += this.requiredSpace(this.content(next));
  15534. this.position++;
  15535. }
  15536. }
  15537. nextToken = this.nextToken;
  15538. }
  15539. var hasClass = indexesOf(word, '.').filter(function (i) {
  15540. // Allow escaped dot within class name
  15541. var escapedDot = word[i - 1] === '\\';
  15542. // Allow decimal numbers percent in @keyframes
  15543. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  15544. return !escapedDot && !isKeyframesPercent;
  15545. });
  15546. var hasId = indexesOf(word, '#').filter(function (i) {
  15547. return word[i - 1] !== '\\';
  15548. });
  15549. // Eliminate Sass interpolations from the list of id indexes
  15550. var interpolations = indexesOf(word, '#{');
  15551. if (interpolations.length) {
  15552. hasId = hasId.filter(function (hashIndex) {
  15553. return !~interpolations.indexOf(hashIndex);
  15554. });
  15555. }
  15556. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  15557. indices.forEach(function (ind, i) {
  15558. var index = indices[i + 1] || word.length;
  15559. var value = word.slice(ind, index);
  15560. if (i === 0 && firstCallback) {
  15561. return firstCallback.call(_this5, value, indices.length);
  15562. }
  15563. var node;
  15564. var current = _this5.currToken;
  15565. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  15566. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  15567. if (~hasClass.indexOf(ind)) {
  15568. var classNameOpts = {
  15569. value: value.slice(1),
  15570. source: source,
  15571. sourceIndex: sourceIndex
  15572. };
  15573. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  15574. } else if (~hasId.indexOf(ind)) {
  15575. var idOpts = {
  15576. value: value.slice(1),
  15577. source: source,
  15578. sourceIndex: sourceIndex
  15579. };
  15580. node = new _id["default"](unescapeProp(idOpts, "value"));
  15581. } else {
  15582. var tagOpts = {
  15583. value: value,
  15584. source: source,
  15585. sourceIndex: sourceIndex
  15586. };
  15587. unescapeProp(tagOpts, "value");
  15588. node = new _tag["default"](tagOpts);
  15589. }
  15590. _this5.newNode(node, namespace);
  15591. // Ensure that the namespace is used only once
  15592. namespace = null;
  15593. });
  15594. this.position++;
  15595. };
  15596. _proto.word = function word(namespace) {
  15597. var nextToken = this.nextToken;
  15598. if (nextToken && this.content(nextToken) === '|') {
  15599. this.position++;
  15600. return this.namespace();
  15601. }
  15602. return this.splitWord(namespace);
  15603. };
  15604. _proto.loop = function loop() {
  15605. while (this.position < this.tokens.length) {
  15606. this.parse(true);
  15607. }
  15608. this.current._inferEndPosition();
  15609. return this.root;
  15610. };
  15611. _proto.parse = function parse(throwOnParenthesis) {
  15612. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  15613. case tokens.space:
  15614. this.space();
  15615. break;
  15616. case tokens.comment:
  15617. this.comment();
  15618. break;
  15619. case tokens.openParenthesis:
  15620. this.parentheses();
  15621. break;
  15622. case tokens.closeParenthesis:
  15623. if (throwOnParenthesis) {
  15624. this.missingParenthesis();
  15625. }
  15626. break;
  15627. case tokens.openSquare:
  15628. this.attribute();
  15629. break;
  15630. case tokens.dollar:
  15631. case tokens.caret:
  15632. case tokens.equals:
  15633. case tokens.word:
  15634. this.word();
  15635. break;
  15636. case tokens.colon:
  15637. this.pseudo();
  15638. break;
  15639. case tokens.comma:
  15640. this.comma();
  15641. break;
  15642. case tokens.asterisk:
  15643. this.universal();
  15644. break;
  15645. case tokens.ampersand:
  15646. this.nesting();
  15647. break;
  15648. case tokens.slash:
  15649. case tokens.combinator:
  15650. this.combinator();
  15651. break;
  15652. case tokens.str:
  15653. this.string();
  15654. break;
  15655. // These cases throw; no break needed.
  15656. case tokens.closeSquare:
  15657. this.missingSquareBracket();
  15658. case tokens.semicolon:
  15659. this.missingBackslash();
  15660. default:
  15661. this.unexpected();
  15662. }
  15663. }
  15664. /**
  15665. * Helpers
  15666. */;
  15667. _proto.expected = function expected(description, index, found) {
  15668. if (Array.isArray(description)) {
  15669. var last = description.pop();
  15670. description = description.join(', ') + " or " + last;
  15671. }
  15672. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  15673. if (!found) {
  15674. return this.error("Expected " + an + " " + description + ".", {
  15675. index: index
  15676. });
  15677. }
  15678. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  15679. index: index
  15680. });
  15681. };
  15682. _proto.requiredSpace = function requiredSpace(space) {
  15683. return this.options.lossy ? ' ' : space;
  15684. };
  15685. _proto.optionalSpace = function optionalSpace(space) {
  15686. return this.options.lossy ? '' : space;
  15687. };
  15688. _proto.lossySpace = function lossySpace(space, required) {
  15689. if (this.options.lossy) {
  15690. return required ? ' ' : '';
  15691. } else {
  15692. return space;
  15693. }
  15694. };
  15695. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  15696. var content = this.content(token);
  15697. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  15698. return this.requiredSpace(content);
  15699. } else {
  15700. return content;
  15701. }
  15702. };
  15703. _proto.newNode = function newNode(node, namespace) {
  15704. if (namespace) {
  15705. if (/^ +$/.test(namespace)) {
  15706. if (!this.options.lossy) {
  15707. this.spaces = (this.spaces || '') + namespace;
  15708. }
  15709. namespace = true;
  15710. }
  15711. node.namespace = namespace;
  15712. unescapeProp(node, "namespace");
  15713. }
  15714. if (this.spaces) {
  15715. node.spaces.before = this.spaces;
  15716. this.spaces = '';
  15717. }
  15718. return this.current.append(node);
  15719. };
  15720. _proto.content = function content(token) {
  15721. if (token === void 0) {
  15722. token = this.currToken;
  15723. }
  15724. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  15725. };
  15726. /**
  15727. * returns the index of the next non-whitespace, non-comment token.
  15728. * returns -1 if no meaningful token is found.
  15729. */
  15730. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  15731. if (startPosition === void 0) {
  15732. startPosition = this.position + 1;
  15733. }
  15734. var searchPosition = startPosition;
  15735. while (searchPosition < this.tokens.length) {
  15736. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  15737. searchPosition++;
  15738. continue;
  15739. } else {
  15740. return searchPosition;
  15741. }
  15742. }
  15743. return -1;
  15744. };
  15745. _createClass(Parser, [{
  15746. key: "currToken",
  15747. get: function get() {
  15748. return this.tokens[this.position];
  15749. }
  15750. }, {
  15751. key: "nextToken",
  15752. get: function get() {
  15753. return this.tokens[this.position + 1];
  15754. }
  15755. }, {
  15756. key: "prevToken",
  15757. get: function get() {
  15758. return this.tokens[this.position - 1];
  15759. }
  15760. }]);
  15761. return Parser;
  15762. }();
  15763. exports["default"] = Parser;
  15764. module.exports = exports.default;
  15765. } (parser, parser.exports));
  15766. return parser.exports;
  15767. }
  15768. var hasRequiredProcessor;
  15769. function requireProcessor () {
  15770. if (hasRequiredProcessor) return processor.exports;
  15771. hasRequiredProcessor = 1;
  15772. (function (module, exports) {
  15773. exports.__esModule = true;
  15774. exports["default"] = void 0;
  15775. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  15776. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15777. var Processor = /*#__PURE__*/function () {
  15778. function Processor(func, options) {
  15779. this.func = func || function noop() {};
  15780. this.funcRes = null;
  15781. this.options = options;
  15782. }
  15783. var _proto = Processor.prototype;
  15784. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  15785. if (options === void 0) {
  15786. options = {};
  15787. }
  15788. var merged = Object.assign({}, this.options, options);
  15789. if (merged.updateSelector === false) {
  15790. return false;
  15791. } else {
  15792. return typeof rule !== "string";
  15793. }
  15794. };
  15795. _proto._isLossy = function _isLossy(options) {
  15796. if (options === void 0) {
  15797. options = {};
  15798. }
  15799. var merged = Object.assign({}, this.options, options);
  15800. if (merged.lossless === false) {
  15801. return true;
  15802. } else {
  15803. return false;
  15804. }
  15805. };
  15806. _proto._root = function _root(rule, options) {
  15807. if (options === void 0) {
  15808. options = {};
  15809. }
  15810. var parser = new _parser["default"](rule, this._parseOptions(options));
  15811. return parser.root;
  15812. };
  15813. _proto._parseOptions = function _parseOptions(options) {
  15814. return {
  15815. lossy: this._isLossy(options)
  15816. };
  15817. };
  15818. _proto._run = function _run(rule, options) {
  15819. var _this = this;
  15820. if (options === void 0) {
  15821. options = {};
  15822. }
  15823. return new Promise(function (resolve, reject) {
  15824. try {
  15825. var root = _this._root(rule, options);
  15826. Promise.resolve(_this.func(root)).then(function (transform) {
  15827. var string = undefined;
  15828. if (_this._shouldUpdateSelector(rule, options)) {
  15829. string = root.toString();
  15830. rule.selector = string;
  15831. }
  15832. return {
  15833. transform: transform,
  15834. root: root,
  15835. string: string
  15836. };
  15837. }).then(resolve, reject);
  15838. } catch (e) {
  15839. reject(e);
  15840. return;
  15841. }
  15842. });
  15843. };
  15844. _proto._runSync = function _runSync(rule, options) {
  15845. if (options === void 0) {
  15846. options = {};
  15847. }
  15848. var root = this._root(rule, options);
  15849. var transform = this.func(root);
  15850. if (transform && typeof transform.then === "function") {
  15851. throw new Error("Selector processor returned a promise to a synchronous call.");
  15852. }
  15853. var string = undefined;
  15854. if (options.updateSelector && typeof rule !== "string") {
  15855. string = root.toString();
  15856. rule.selector = string;
  15857. }
  15858. return {
  15859. transform: transform,
  15860. root: root,
  15861. string: string
  15862. };
  15863. }
  15864. /**
  15865. * Process rule into a selector AST.
  15866. *
  15867. * @param rule {postcss.Rule | string} The css selector to be processed
  15868. * @param options The options for processing
  15869. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  15870. */;
  15871. _proto.ast = function ast(rule, options) {
  15872. return this._run(rule, options).then(function (result) {
  15873. return result.root;
  15874. });
  15875. }
  15876. /**
  15877. * Process rule into a selector AST synchronously.
  15878. *
  15879. * @param rule {postcss.Rule | string} The css selector to be processed
  15880. * @param options The options for processing
  15881. * @returns {parser.Root} The AST of the selector after processing it.
  15882. */;
  15883. _proto.astSync = function astSync(rule, options) {
  15884. return this._runSync(rule, options).root;
  15885. }
  15886. /**
  15887. * Process a selector into a transformed value asynchronously
  15888. *
  15889. * @param rule {postcss.Rule | string} The css selector to be processed
  15890. * @param options The options for processing
  15891. * @returns {Promise<any>} The value returned by the processor.
  15892. */;
  15893. _proto.transform = function transform(rule, options) {
  15894. return this._run(rule, options).then(function (result) {
  15895. return result.transform;
  15896. });
  15897. }
  15898. /**
  15899. * Process a selector into a transformed value synchronously.
  15900. *
  15901. * @param rule {postcss.Rule | string} The css selector to be processed
  15902. * @param options The options for processing
  15903. * @returns {any} The value returned by the processor.
  15904. */;
  15905. _proto.transformSync = function transformSync(rule, options) {
  15906. return this._runSync(rule, options).transform;
  15907. }
  15908. /**
  15909. * Process a selector into a new selector string asynchronously.
  15910. *
  15911. * @param rule {postcss.Rule | string} The css selector to be processed
  15912. * @param options The options for processing
  15913. * @returns {string} the selector after processing.
  15914. */;
  15915. _proto.process = function process(rule, options) {
  15916. return this._run(rule, options).then(function (result) {
  15917. return result.string || result.root.toString();
  15918. });
  15919. }
  15920. /**
  15921. * Process a selector into a new selector string synchronously.
  15922. *
  15923. * @param rule {postcss.Rule | string} The css selector to be processed
  15924. * @param options The options for processing
  15925. * @returns {string} the selector after processing.
  15926. */;
  15927. _proto.processSync = function processSync(rule, options) {
  15928. var result = this._runSync(rule, options);
  15929. return result.string || result.root.toString();
  15930. };
  15931. return Processor;
  15932. }();
  15933. exports["default"] = Processor;
  15934. module.exports = exports.default;
  15935. } (processor, processor.exports));
  15936. return processor.exports;
  15937. }
  15938. var selectors = {};
  15939. var constructors = {};
  15940. var hasRequiredConstructors;
  15941. function requireConstructors () {
  15942. if (hasRequiredConstructors) return constructors;
  15943. hasRequiredConstructors = 1;
  15944. constructors.__esModule = true;
  15945. constructors.universal = constructors.tag = constructors.string = constructors.selector = constructors.root = constructors.pseudo = constructors.nesting = constructors.id = constructors.comment = constructors.combinator = constructors.className = constructors.attribute = void 0;
  15946. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  15947. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  15948. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  15949. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  15950. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  15951. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  15952. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  15953. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  15954. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  15955. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  15956. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  15957. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  15958. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15959. var attribute = function attribute(opts) {
  15960. return new _attribute["default"](opts);
  15961. };
  15962. constructors.attribute = attribute;
  15963. var className = function className(opts) {
  15964. return new _className["default"](opts);
  15965. };
  15966. constructors.className = className;
  15967. var combinator = function combinator(opts) {
  15968. return new _combinator["default"](opts);
  15969. };
  15970. constructors.combinator = combinator;
  15971. var comment = function comment(opts) {
  15972. return new _comment["default"](opts);
  15973. };
  15974. constructors.comment = comment;
  15975. var id = function id(opts) {
  15976. return new _id["default"](opts);
  15977. };
  15978. constructors.id = id;
  15979. var nesting = function nesting(opts) {
  15980. return new _nesting["default"](opts);
  15981. };
  15982. constructors.nesting = nesting;
  15983. var pseudo = function pseudo(opts) {
  15984. return new _pseudo["default"](opts);
  15985. };
  15986. constructors.pseudo = pseudo;
  15987. var root = function root(opts) {
  15988. return new _root["default"](opts);
  15989. };
  15990. constructors.root = root;
  15991. var selector = function selector(opts) {
  15992. return new _selector["default"](opts);
  15993. };
  15994. constructors.selector = selector;
  15995. var string = function string(opts) {
  15996. return new _string["default"](opts);
  15997. };
  15998. constructors.string = string;
  15999. var tag = function tag(opts) {
  16000. return new _tag["default"](opts);
  16001. };
  16002. constructors.tag = tag;
  16003. var universal = function universal(opts) {
  16004. return new _universal["default"](opts);
  16005. };
  16006. constructors.universal = universal;
  16007. return constructors;
  16008. }
  16009. var guards = {};
  16010. var hasRequiredGuards;
  16011. function requireGuards () {
  16012. if (hasRequiredGuards) return guards;
  16013. hasRequiredGuards = 1;
  16014. guards.__esModule = true;
  16015. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  16016. guards.isContainer = isContainer;
  16017. guards.isIdentifier = void 0;
  16018. guards.isNamespace = isNamespace;
  16019. guards.isNesting = void 0;
  16020. guards.isNode = isNode;
  16021. guards.isPseudo = void 0;
  16022. guards.isPseudoClass = isPseudoClass;
  16023. guards.isPseudoElement = isPseudoElement;
  16024. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  16025. var _types = /*@__PURE__*/ requireTypes();
  16026. var _IS_TYPE;
  16027. var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
  16028. function isNode(node) {
  16029. return typeof node === "object" && IS_TYPE[node.type];
  16030. }
  16031. function isNodeType(type, node) {
  16032. return isNode(node) && node.type === type;
  16033. }
  16034. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  16035. guards.isAttribute = isAttribute;
  16036. var isClassName = isNodeType.bind(null, _types.CLASS);
  16037. guards.isClassName = isClassName;
  16038. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  16039. guards.isCombinator = isCombinator;
  16040. var isComment = isNodeType.bind(null, _types.COMMENT);
  16041. guards.isComment = isComment;
  16042. var isIdentifier = isNodeType.bind(null, _types.ID);
  16043. guards.isIdentifier = isIdentifier;
  16044. var isNesting = isNodeType.bind(null, _types.NESTING);
  16045. guards.isNesting = isNesting;
  16046. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  16047. guards.isPseudo = isPseudo;
  16048. var isRoot = isNodeType.bind(null, _types.ROOT);
  16049. guards.isRoot = isRoot;
  16050. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  16051. guards.isSelector = isSelector;
  16052. var isString = isNodeType.bind(null, _types.STRING);
  16053. guards.isString = isString;
  16054. var isTag = isNodeType.bind(null, _types.TAG);
  16055. guards.isTag = isTag;
  16056. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  16057. guards.isUniversal = isUniversal;
  16058. function isPseudoElement(node) {
  16059. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line");
  16060. }
  16061. function isPseudoClass(node) {
  16062. return isPseudo(node) && !isPseudoElement(node);
  16063. }
  16064. function isContainer(node) {
  16065. return !!(isNode(node) && node.walk);
  16066. }
  16067. function isNamespace(node) {
  16068. return isAttribute(node) || isTag(node);
  16069. }
  16070. return guards;
  16071. }
  16072. var hasRequiredSelectors;
  16073. function requireSelectors () {
  16074. if (hasRequiredSelectors) return selectors;
  16075. hasRequiredSelectors = 1;
  16076. (function (exports) {
  16077. exports.__esModule = true;
  16078. var _types = /*@__PURE__*/ requireTypes();
  16079. Object.keys(_types).forEach(function (key) {
  16080. if (key === "default" || key === "__esModule") return;
  16081. if (key in exports && exports[key] === _types[key]) return;
  16082. exports[key] = _types[key];
  16083. });
  16084. var _constructors = /*@__PURE__*/ requireConstructors();
  16085. Object.keys(_constructors).forEach(function (key) {
  16086. if (key === "default" || key === "__esModule") return;
  16087. if (key in exports && exports[key] === _constructors[key]) return;
  16088. exports[key] = _constructors[key];
  16089. });
  16090. var _guards = /*@__PURE__*/ requireGuards();
  16091. Object.keys(_guards).forEach(function (key) {
  16092. if (key === "default" || key === "__esModule") return;
  16093. if (key in exports && exports[key] === _guards[key]) return;
  16094. exports[key] = _guards[key];
  16095. });
  16096. } (selectors));
  16097. return selectors;
  16098. }
  16099. var hasRequiredDist;
  16100. function requireDist () {
  16101. if (hasRequiredDist) return dist.exports;
  16102. hasRequiredDist = 1;
  16103. (function (module, exports) {
  16104. exports.__esModule = true;
  16105. exports["default"] = void 0;
  16106. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  16107. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  16108. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  16109. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  16110. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  16111. var parser = function parser(processor) {
  16112. return new _processor["default"](processor);
  16113. };
  16114. Object.assign(parser, selectors);
  16115. delete parser.__esModule;
  16116. var _default = parser;
  16117. exports["default"] = _default;
  16118. module.exports = exports.default;
  16119. } (dist, dist.exports));
  16120. return dist.exports;
  16121. }
  16122. var parse;
  16123. var hasRequiredParse;
  16124. function requireParse () {
  16125. if (hasRequiredParse) return parse;
  16126. hasRequiredParse = 1;
  16127. var openParentheses = "(".charCodeAt(0);
  16128. var closeParentheses = ")".charCodeAt(0);
  16129. var singleQuote = "'".charCodeAt(0);
  16130. var doubleQuote = '"'.charCodeAt(0);
  16131. var backslash = "\\".charCodeAt(0);
  16132. var slash = "/".charCodeAt(0);
  16133. var comma = ",".charCodeAt(0);
  16134. var colon = ":".charCodeAt(0);
  16135. var star = "*".charCodeAt(0);
  16136. var uLower = "u".charCodeAt(0);
  16137. var uUpper = "U".charCodeAt(0);
  16138. var plus = "+".charCodeAt(0);
  16139. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  16140. parse = function(input) {
  16141. var tokens = [];
  16142. var value = input;
  16143. var next,
  16144. quote,
  16145. prev,
  16146. token,
  16147. escape,
  16148. escapePos,
  16149. whitespacePos,
  16150. parenthesesOpenPos;
  16151. var pos = 0;
  16152. var code = value.charCodeAt(pos);
  16153. var max = value.length;
  16154. var stack = [{ nodes: tokens }];
  16155. var balanced = 0;
  16156. var parent;
  16157. var name = "";
  16158. var before = "";
  16159. var after = "";
  16160. while (pos < max) {
  16161. // Whitespaces
  16162. if (code <= 32) {
  16163. next = pos;
  16164. do {
  16165. next += 1;
  16166. code = value.charCodeAt(next);
  16167. } while (code <= 32);
  16168. token = value.slice(pos, next);
  16169. prev = tokens[tokens.length - 1];
  16170. if (code === closeParentheses && balanced) {
  16171. after = token;
  16172. } else if (prev && prev.type === "div") {
  16173. prev.after = token;
  16174. prev.sourceEndIndex += token.length;
  16175. } else if (
  16176. code === comma ||
  16177. code === colon ||
  16178. (code === slash &&
  16179. value.charCodeAt(next + 1) !== star &&
  16180. (!parent ||
  16181. (parent && parent.type === "function" && parent.value !== "calc")))
  16182. ) {
  16183. before = token;
  16184. } else {
  16185. tokens.push({
  16186. type: "space",
  16187. sourceIndex: pos,
  16188. sourceEndIndex: next,
  16189. value: token
  16190. });
  16191. }
  16192. pos = next;
  16193. // Quotes
  16194. } else if (code === singleQuote || code === doubleQuote) {
  16195. next = pos;
  16196. quote = code === singleQuote ? "'" : '"';
  16197. token = {
  16198. type: "string",
  16199. sourceIndex: pos,
  16200. quote: quote
  16201. };
  16202. do {
  16203. escape = false;
  16204. next = value.indexOf(quote, next + 1);
  16205. if (~next) {
  16206. escapePos = next;
  16207. while (value.charCodeAt(escapePos - 1) === backslash) {
  16208. escapePos -= 1;
  16209. escape = !escape;
  16210. }
  16211. } else {
  16212. value += quote;
  16213. next = value.length - 1;
  16214. token.unclosed = true;
  16215. }
  16216. } while (escape);
  16217. token.value = value.slice(pos + 1, next);
  16218. token.sourceEndIndex = token.unclosed ? next : next + 1;
  16219. tokens.push(token);
  16220. pos = next + 1;
  16221. code = value.charCodeAt(pos);
  16222. // Comments
  16223. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  16224. next = value.indexOf("*/", pos);
  16225. token = {
  16226. type: "comment",
  16227. sourceIndex: pos,
  16228. sourceEndIndex: next + 2
  16229. };
  16230. if (next === -1) {
  16231. token.unclosed = true;
  16232. next = value.length;
  16233. token.sourceEndIndex = next;
  16234. }
  16235. token.value = value.slice(pos + 2, next);
  16236. tokens.push(token);
  16237. pos = next + 2;
  16238. code = value.charCodeAt(pos);
  16239. // Operation within calc
  16240. } else if (
  16241. (code === slash || code === star) &&
  16242. parent &&
  16243. parent.type === "function" &&
  16244. parent.value === "calc"
  16245. ) {
  16246. token = value[pos];
  16247. tokens.push({
  16248. type: "word",
  16249. sourceIndex: pos - before.length,
  16250. sourceEndIndex: pos + token.length,
  16251. value: token
  16252. });
  16253. pos += 1;
  16254. code = value.charCodeAt(pos);
  16255. // Dividers
  16256. } else if (code === slash || code === comma || code === colon) {
  16257. token = value[pos];
  16258. tokens.push({
  16259. type: "div",
  16260. sourceIndex: pos - before.length,
  16261. sourceEndIndex: pos + token.length,
  16262. value: token,
  16263. before: before,
  16264. after: ""
  16265. });
  16266. before = "";
  16267. pos += 1;
  16268. code = value.charCodeAt(pos);
  16269. // Open parentheses
  16270. } else if (openParentheses === code) {
  16271. // Whitespaces after open parentheses
  16272. next = pos;
  16273. do {
  16274. next += 1;
  16275. code = value.charCodeAt(next);
  16276. } while (code <= 32);
  16277. parenthesesOpenPos = pos;
  16278. token = {
  16279. type: "function",
  16280. sourceIndex: pos - name.length,
  16281. value: name,
  16282. before: value.slice(parenthesesOpenPos + 1, next)
  16283. };
  16284. pos = next;
  16285. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  16286. next -= 1;
  16287. do {
  16288. escape = false;
  16289. next = value.indexOf(")", next + 1);
  16290. if (~next) {
  16291. escapePos = next;
  16292. while (value.charCodeAt(escapePos - 1) === backslash) {
  16293. escapePos -= 1;
  16294. escape = !escape;
  16295. }
  16296. } else {
  16297. value += ")";
  16298. next = value.length - 1;
  16299. token.unclosed = true;
  16300. }
  16301. } while (escape);
  16302. // Whitespaces before closed
  16303. whitespacePos = next;
  16304. do {
  16305. whitespacePos -= 1;
  16306. code = value.charCodeAt(whitespacePos);
  16307. } while (code <= 32);
  16308. if (parenthesesOpenPos < whitespacePos) {
  16309. if (pos !== whitespacePos + 1) {
  16310. token.nodes = [
  16311. {
  16312. type: "word",
  16313. sourceIndex: pos,
  16314. sourceEndIndex: whitespacePos + 1,
  16315. value: value.slice(pos, whitespacePos + 1)
  16316. }
  16317. ];
  16318. } else {
  16319. token.nodes = [];
  16320. }
  16321. if (token.unclosed && whitespacePos + 1 !== next) {
  16322. token.after = "";
  16323. token.nodes.push({
  16324. type: "space",
  16325. sourceIndex: whitespacePos + 1,
  16326. sourceEndIndex: next,
  16327. value: value.slice(whitespacePos + 1, next)
  16328. });
  16329. } else {
  16330. token.after = value.slice(whitespacePos + 1, next);
  16331. token.sourceEndIndex = next;
  16332. }
  16333. } else {
  16334. token.after = "";
  16335. token.nodes = [];
  16336. }
  16337. pos = next + 1;
  16338. token.sourceEndIndex = token.unclosed ? next : pos;
  16339. code = value.charCodeAt(pos);
  16340. tokens.push(token);
  16341. } else {
  16342. balanced += 1;
  16343. token.after = "";
  16344. token.sourceEndIndex = pos + 1;
  16345. tokens.push(token);
  16346. stack.push(token);
  16347. tokens = token.nodes = [];
  16348. parent = token;
  16349. }
  16350. name = "";
  16351. // Close parentheses
  16352. } else if (closeParentheses === code && balanced) {
  16353. pos += 1;
  16354. code = value.charCodeAt(pos);
  16355. parent.after = after;
  16356. parent.sourceEndIndex += after.length;
  16357. after = "";
  16358. balanced -= 1;
  16359. stack[stack.length - 1].sourceEndIndex = pos;
  16360. stack.pop();
  16361. parent = stack[balanced];
  16362. tokens = parent.nodes;
  16363. // Words
  16364. } else {
  16365. next = pos;
  16366. do {
  16367. if (code === backslash) {
  16368. next += 1;
  16369. }
  16370. next += 1;
  16371. code = value.charCodeAt(next);
  16372. } while (
  16373. next < max &&
  16374. !(
  16375. code <= 32 ||
  16376. code === singleQuote ||
  16377. code === doubleQuote ||
  16378. code === comma ||
  16379. code === colon ||
  16380. code === slash ||
  16381. code === openParentheses ||
  16382. (code === star &&
  16383. parent &&
  16384. parent.type === "function" &&
  16385. parent.value === "calc") ||
  16386. (code === slash &&
  16387. parent.type === "function" &&
  16388. parent.value === "calc") ||
  16389. (code === closeParentheses && balanced)
  16390. )
  16391. );
  16392. token = value.slice(pos, next);
  16393. if (openParentheses === code) {
  16394. name = token;
  16395. } else if (
  16396. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  16397. plus === token.charCodeAt(1) &&
  16398. isUnicodeRange.test(token.slice(2))
  16399. ) {
  16400. tokens.push({
  16401. type: "unicode-range",
  16402. sourceIndex: pos,
  16403. sourceEndIndex: next,
  16404. value: token
  16405. });
  16406. } else {
  16407. tokens.push({
  16408. type: "word",
  16409. sourceIndex: pos,
  16410. sourceEndIndex: next,
  16411. value: token
  16412. });
  16413. }
  16414. pos = next;
  16415. }
  16416. }
  16417. for (pos = stack.length - 1; pos; pos -= 1) {
  16418. stack[pos].unclosed = true;
  16419. stack[pos].sourceEndIndex = value.length;
  16420. }
  16421. return stack[0].nodes;
  16422. };
  16423. return parse;
  16424. }
  16425. var walk$1;
  16426. var hasRequiredWalk;
  16427. function requireWalk () {
  16428. if (hasRequiredWalk) return walk$1;
  16429. hasRequiredWalk = 1;
  16430. walk$1 = function walk(nodes, cb, bubble) {
  16431. var i, max, node, result;
  16432. for (i = 0, max = nodes.length; i < max; i += 1) {
  16433. node = nodes[i];
  16434. if (!bubble) {
  16435. result = cb(node, i, nodes);
  16436. }
  16437. if (
  16438. result !== false &&
  16439. node.type === "function" &&
  16440. Array.isArray(node.nodes)
  16441. ) {
  16442. walk(node.nodes, cb, bubble);
  16443. }
  16444. if (bubble) {
  16445. cb(node, i, nodes);
  16446. }
  16447. }
  16448. };
  16449. return walk$1;
  16450. }
  16451. var stringify_1;
  16452. var hasRequiredStringify;
  16453. function requireStringify () {
  16454. if (hasRequiredStringify) return stringify_1;
  16455. hasRequiredStringify = 1;
  16456. function stringifyNode(node, custom) {
  16457. var type = node.type;
  16458. var value = node.value;
  16459. var buf;
  16460. var customResult;
  16461. if (custom && (customResult = custom(node)) !== undefined) {
  16462. return customResult;
  16463. } else if (type === "word" || type === "space") {
  16464. return value;
  16465. } else if (type === "string") {
  16466. buf = node.quote || "";
  16467. return buf + value + (node.unclosed ? "" : buf);
  16468. } else if (type === "comment") {
  16469. return "/*" + value + (node.unclosed ? "" : "*/");
  16470. } else if (type === "div") {
  16471. return (node.before || "") + value + (node.after || "");
  16472. } else if (Array.isArray(node.nodes)) {
  16473. buf = stringify(node.nodes, custom);
  16474. if (type !== "function") {
  16475. return buf;
  16476. }
  16477. return (
  16478. value +
  16479. "(" +
  16480. (node.before || "") +
  16481. buf +
  16482. (node.after || "") +
  16483. (node.unclosed ? "" : ")")
  16484. );
  16485. }
  16486. return value;
  16487. }
  16488. function stringify(nodes, custom) {
  16489. var result, i;
  16490. if (Array.isArray(nodes)) {
  16491. result = "";
  16492. for (i = nodes.length - 1; ~i; i -= 1) {
  16493. result = stringifyNode(nodes[i], custom) + result;
  16494. }
  16495. return result;
  16496. }
  16497. return stringifyNode(nodes, custom);
  16498. }
  16499. stringify_1 = stringify;
  16500. return stringify_1;
  16501. }
  16502. var unit;
  16503. var hasRequiredUnit;
  16504. function requireUnit () {
  16505. if (hasRequiredUnit) return unit;
  16506. hasRequiredUnit = 1;
  16507. var minus = "-".charCodeAt(0);
  16508. var plus = "+".charCodeAt(0);
  16509. var dot = ".".charCodeAt(0);
  16510. var exp = "e".charCodeAt(0);
  16511. var EXP = "E".charCodeAt(0);
  16512. // Check if three code points would start a number
  16513. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  16514. function likeNumber(value) {
  16515. var code = value.charCodeAt(0);
  16516. var nextCode;
  16517. if (code === plus || code === minus) {
  16518. nextCode = value.charCodeAt(1);
  16519. if (nextCode >= 48 && nextCode <= 57) {
  16520. return true;
  16521. }
  16522. var nextNextCode = value.charCodeAt(2);
  16523. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  16524. return true;
  16525. }
  16526. return false;
  16527. }
  16528. if (code === dot) {
  16529. nextCode = value.charCodeAt(1);
  16530. if (nextCode >= 48 && nextCode <= 57) {
  16531. return true;
  16532. }
  16533. return false;
  16534. }
  16535. if (code >= 48 && code <= 57) {
  16536. return true;
  16537. }
  16538. return false;
  16539. }
  16540. // Consume a number
  16541. // https://www.w3.org/TR/css-syntax-3/#consume-number
  16542. unit = function(value) {
  16543. var pos = 0;
  16544. var length = value.length;
  16545. var code;
  16546. var nextCode;
  16547. var nextNextCode;
  16548. if (length === 0 || !likeNumber(value)) {
  16549. return false;
  16550. }
  16551. code = value.charCodeAt(pos);
  16552. if (code === plus || code === minus) {
  16553. pos++;
  16554. }
  16555. while (pos < length) {
  16556. code = value.charCodeAt(pos);
  16557. if (code < 48 || code > 57) {
  16558. break;
  16559. }
  16560. pos += 1;
  16561. }
  16562. code = value.charCodeAt(pos);
  16563. nextCode = value.charCodeAt(pos + 1);
  16564. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  16565. pos += 2;
  16566. while (pos < length) {
  16567. code = value.charCodeAt(pos);
  16568. if (code < 48 || code > 57) {
  16569. break;
  16570. }
  16571. pos += 1;
  16572. }
  16573. }
  16574. code = value.charCodeAt(pos);
  16575. nextCode = value.charCodeAt(pos + 1);
  16576. nextNextCode = value.charCodeAt(pos + 2);
  16577. if (
  16578. (code === exp || code === EXP) &&
  16579. ((nextCode >= 48 && nextCode <= 57) ||
  16580. ((nextCode === plus || nextCode === minus) &&
  16581. nextNextCode >= 48 &&
  16582. nextNextCode <= 57))
  16583. ) {
  16584. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  16585. while (pos < length) {
  16586. code = value.charCodeAt(pos);
  16587. if (code < 48 || code > 57) {
  16588. break;
  16589. }
  16590. pos += 1;
  16591. }
  16592. }
  16593. return {
  16594. number: value.slice(0, pos),
  16595. unit: value.slice(pos)
  16596. };
  16597. };
  16598. return unit;
  16599. }
  16600. var lib;
  16601. var hasRequiredLib;
  16602. function requireLib () {
  16603. if (hasRequiredLib) return lib;
  16604. hasRequiredLib = 1;
  16605. var parse = /*@__PURE__*/ requireParse();
  16606. var walk = /*@__PURE__*/ requireWalk();
  16607. var stringify = /*@__PURE__*/ requireStringify();
  16608. function ValueParser(value) {
  16609. if (this instanceof ValueParser) {
  16610. this.nodes = parse(value);
  16611. return this;
  16612. }
  16613. return new ValueParser(value);
  16614. }
  16615. ValueParser.prototype.toString = function() {
  16616. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  16617. };
  16618. ValueParser.prototype.walk = function(cb, bubble) {
  16619. walk(this.nodes, cb, bubble);
  16620. return this;
  16621. };
  16622. ValueParser.unit = /*@__PURE__*/ requireUnit();
  16623. ValueParser.walk = walk;
  16624. ValueParser.stringify = stringify;
  16625. lib = ValueParser;
  16626. return lib;
  16627. }
  16628. var hasRequiredSrc$2;
  16629. function requireSrc$2 () {
  16630. if (hasRequiredSrc$2) return src$2.exports;
  16631. hasRequiredSrc$2 = 1;
  16632. const selectorParser = /*@__PURE__*/ requireDist();
  16633. const valueParser = /*@__PURE__*/ requireLib();
  16634. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  16635. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  16636. function normalizeNodeArray(nodes) {
  16637. const array = [];
  16638. nodes.forEach((x) => {
  16639. if (Array.isArray(x)) {
  16640. normalizeNodeArray(x).forEach((item) => {
  16641. array.push(item);
  16642. });
  16643. } else if (x) {
  16644. array.push(x);
  16645. }
  16646. });
  16647. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  16648. array.pop();
  16649. }
  16650. return array;
  16651. }
  16652. function localizeNode(rule, mode, localAliasMap) {
  16653. const transform = (node, context) => {
  16654. if (context.ignoreNextSpacing && !isSpacing(node)) {
  16655. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  16656. }
  16657. if (context.enforceNoSpacing && isSpacing(node)) {
  16658. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  16659. }
  16660. let newNodes;
  16661. switch (node.type) {
  16662. case "root": {
  16663. let resultingGlobal;
  16664. context.hasPureGlobals = false;
  16665. newNodes = node.nodes.map((n) => {
  16666. const nContext = {
  16667. global: context.global,
  16668. lastWasSpacing: true,
  16669. hasLocals: false,
  16670. explicit: false,
  16671. };
  16672. n = transform(n, nContext);
  16673. if (typeof resultingGlobal === "undefined") {
  16674. resultingGlobal = nContext.global;
  16675. } else if (resultingGlobal !== nContext.global) {
  16676. throw new Error(
  16677. 'Inconsistent rule global/local result in rule "' +
  16678. node +
  16679. '" (multiple selectors must result in the same mode for the rule)'
  16680. );
  16681. }
  16682. if (!nContext.hasLocals) {
  16683. context.hasPureGlobals = true;
  16684. }
  16685. return n;
  16686. });
  16687. context.global = resultingGlobal;
  16688. node.nodes = normalizeNodeArray(newNodes);
  16689. break;
  16690. }
  16691. case "selector": {
  16692. newNodes = node.map((childNode) => transform(childNode, context));
  16693. node = node.clone();
  16694. node.nodes = normalizeNodeArray(newNodes);
  16695. break;
  16696. }
  16697. case "combinator": {
  16698. if (isSpacing(node)) {
  16699. if (context.ignoreNextSpacing) {
  16700. context.ignoreNextSpacing = false;
  16701. context.lastWasSpacing = false;
  16702. context.enforceNoSpacing = false;
  16703. return null;
  16704. }
  16705. context.lastWasSpacing = true;
  16706. return node;
  16707. }
  16708. break;
  16709. }
  16710. case "pseudo": {
  16711. let childContext;
  16712. const isNested = !!node.length;
  16713. const isScoped = node.value === ":local" || node.value === ":global";
  16714. const isImportExport =
  16715. node.value === ":import" || node.value === ":export";
  16716. if (isImportExport) {
  16717. context.hasLocals = true;
  16718. // :local(.foo)
  16719. } else if (isNested) {
  16720. if (isScoped) {
  16721. if (node.nodes.length === 0) {
  16722. throw new Error(`${node.value}() can't be empty`);
  16723. }
  16724. if (context.inside) {
  16725. throw new Error(
  16726. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16727. );
  16728. }
  16729. childContext = {
  16730. global: node.value === ":global",
  16731. inside: node.value,
  16732. hasLocals: false,
  16733. explicit: true,
  16734. };
  16735. newNodes = node
  16736. .map((childNode) => transform(childNode, childContext))
  16737. .reduce((acc, next) => acc.concat(next.nodes), []);
  16738. if (newNodes.length) {
  16739. const { before, after } = node.spaces;
  16740. const first = newNodes[0];
  16741. const last = newNodes[newNodes.length - 1];
  16742. first.spaces = { before, after: first.spaces.after };
  16743. last.spaces = { before: last.spaces.before, after };
  16744. }
  16745. node = newNodes;
  16746. break;
  16747. } else {
  16748. childContext = {
  16749. global: context.global,
  16750. inside: context.inside,
  16751. lastWasSpacing: true,
  16752. hasLocals: false,
  16753. explicit: context.explicit,
  16754. };
  16755. newNodes = node.map((childNode) => {
  16756. const newContext = {
  16757. ...childContext,
  16758. enforceNoSpacing: false,
  16759. };
  16760. const result = transform(childNode, newContext);
  16761. childContext.global = newContext.global;
  16762. childContext.hasLocals = newContext.hasLocals;
  16763. return result;
  16764. });
  16765. node = node.clone();
  16766. node.nodes = normalizeNodeArray(newNodes);
  16767. if (childContext.hasLocals) {
  16768. context.hasLocals = true;
  16769. }
  16770. }
  16771. break;
  16772. //:local .foo .bar
  16773. } else if (isScoped) {
  16774. if (context.inside) {
  16775. throw new Error(
  16776. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16777. );
  16778. }
  16779. const addBackSpacing = !!node.spaces.before;
  16780. context.ignoreNextSpacing = context.lastWasSpacing
  16781. ? node.value
  16782. : false;
  16783. context.enforceNoSpacing = context.lastWasSpacing
  16784. ? false
  16785. : node.value;
  16786. context.global = node.value === ":global";
  16787. context.explicit = true;
  16788. // because this node has spacing that is lost when we remove it
  16789. // we make up for it by adding an extra combinator in since adding
  16790. // spacing on the parent selector doesn't work
  16791. return addBackSpacing
  16792. ? selectorParser.combinator({ value: " " })
  16793. : null;
  16794. }
  16795. break;
  16796. }
  16797. case "id":
  16798. case "class": {
  16799. if (!node.value) {
  16800. throw new Error("Invalid class or id selector syntax");
  16801. }
  16802. if (context.global) {
  16803. break;
  16804. }
  16805. const isImportedValue = localAliasMap.has(node.value);
  16806. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  16807. if (!isImportedValue || isImportedWithExplicitScope) {
  16808. const innerNode = node.clone();
  16809. innerNode.spaces = { before: "", after: "" };
  16810. node = selectorParser.pseudo({
  16811. value: ":local",
  16812. nodes: [innerNode],
  16813. spaces: node.spaces,
  16814. });
  16815. context.hasLocals = true;
  16816. }
  16817. break;
  16818. }
  16819. case "nesting": {
  16820. if (node.value === "&") {
  16821. context.hasLocals = true;
  16822. }
  16823. }
  16824. }
  16825. context.lastWasSpacing = false;
  16826. context.ignoreNextSpacing = false;
  16827. context.enforceNoSpacing = false;
  16828. return node;
  16829. };
  16830. const rootContext = {
  16831. global: mode === "global",
  16832. hasPureGlobals: false,
  16833. };
  16834. rootContext.selector = selectorParser((root) => {
  16835. transform(root, rootContext);
  16836. }).processSync(rule, { updateSelector: false, lossless: true });
  16837. return rootContext;
  16838. }
  16839. function localizeDeclNode(node, context) {
  16840. switch (node.type) {
  16841. case "word":
  16842. if (context.localizeNextItem) {
  16843. if (!context.localAliasMap.has(node.value)) {
  16844. node.value = ":local(" + node.value + ")";
  16845. context.localizeNextItem = false;
  16846. }
  16847. }
  16848. break;
  16849. case "function":
  16850. if (
  16851. context.options &&
  16852. context.options.rewriteUrl &&
  16853. node.value.toLowerCase() === "url"
  16854. ) {
  16855. node.nodes.map((nestedNode) => {
  16856. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  16857. return;
  16858. }
  16859. let newUrl = context.options.rewriteUrl(
  16860. context.global,
  16861. nestedNode.value
  16862. );
  16863. switch (nestedNode.type) {
  16864. case "string":
  16865. if (nestedNode.quote === "'") {
  16866. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  16867. }
  16868. if (nestedNode.quote === '"') {
  16869. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  16870. }
  16871. break;
  16872. case "word":
  16873. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  16874. break;
  16875. }
  16876. nestedNode.value = newUrl;
  16877. });
  16878. }
  16879. break;
  16880. }
  16881. return node;
  16882. }
  16883. // `none` is special value, other is global values
  16884. const specialKeywords = [
  16885. "none",
  16886. "inherit",
  16887. "initial",
  16888. "revert",
  16889. "revert-layer",
  16890. "unset",
  16891. ];
  16892. function localizeDeclarationValues(localize, declaration, context) {
  16893. const valueNodes = valueParser(declaration.value);
  16894. valueNodes.walk((node, index, nodes) => {
  16895. if (
  16896. node.type === "function" &&
  16897. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  16898. ) {
  16899. return false;
  16900. }
  16901. if (
  16902. node.type === "word" &&
  16903. specialKeywords.includes(node.value.toLowerCase())
  16904. ) {
  16905. return;
  16906. }
  16907. const subContext = {
  16908. options: context.options,
  16909. global: context.global,
  16910. localizeNextItem: localize && !context.global,
  16911. localAliasMap: context.localAliasMap,
  16912. };
  16913. nodes[index] = localizeDeclNode(node, subContext);
  16914. });
  16915. declaration.value = valueNodes.toString();
  16916. }
  16917. function localizeDeclaration(declaration, context) {
  16918. const isAnimation = /animation$/i.test(declaration.prop);
  16919. if (isAnimation) {
  16920. // letter
  16921. // An uppercase letter or a lowercase letter.
  16922. //
  16923. // ident-start code point
  16924. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  16925. //
  16926. // ident code point
  16927. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  16928. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  16929. const validIdent =
  16930. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  16931. /*
  16932. The spec defines some keywords that you can use to describe properties such as the timing
  16933. function. These are still valid animation names, so as long as there is a property that accepts
  16934. a keyword, it is given priority. Only when all the properties that can take a keyword are
  16935. exhausted can the animation name be set to the keyword. I.e.
  16936. animation: infinite infinite;
  16937. The animation will repeat an infinite number of times from the first argument, and will have an
  16938. animation name of infinite from the second.
  16939. */
  16940. const animationKeywords = {
  16941. // animation-direction
  16942. $normal: 1,
  16943. $reverse: 1,
  16944. $alternate: 1,
  16945. "$alternate-reverse": 1,
  16946. // animation-fill-mode
  16947. $forwards: 1,
  16948. $backwards: 1,
  16949. $both: 1,
  16950. // animation-iteration-count
  16951. $infinite: 1,
  16952. // animation-play-state
  16953. $paused: 1,
  16954. $running: 1,
  16955. // animation-timing-function
  16956. $ease: 1,
  16957. "$ease-in": 1,
  16958. "$ease-out": 1,
  16959. "$ease-in-out": 1,
  16960. $linear: 1,
  16961. "$step-end": 1,
  16962. "$step-start": 1,
  16963. // Special
  16964. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  16965. // Global values
  16966. $initial: Infinity,
  16967. $inherit: Infinity,
  16968. $unset: Infinity,
  16969. $revert: Infinity,
  16970. "$revert-layer": Infinity,
  16971. };
  16972. let parsedAnimationKeywords = {};
  16973. const valueNodes = valueParser(declaration.value).walk((node) => {
  16974. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  16975. if (node.type === "div") {
  16976. parsedAnimationKeywords = {};
  16977. return;
  16978. }
  16979. // Do not handle nested functions
  16980. else if (node.type === "function") {
  16981. return false;
  16982. }
  16983. // Ignore all except word
  16984. else if (node.type !== "word") {
  16985. return;
  16986. }
  16987. const value = node.type === "word" ? node.value.toLowerCase() : null;
  16988. let shouldParseAnimationName = false;
  16989. if (value && validIdent.test(value)) {
  16990. if ("$" + value in animationKeywords) {
  16991. parsedAnimationKeywords["$" + value] =
  16992. "$" + value in parsedAnimationKeywords
  16993. ? parsedAnimationKeywords["$" + value] + 1
  16994. : 0;
  16995. shouldParseAnimationName =
  16996. parsedAnimationKeywords["$" + value] >=
  16997. animationKeywords["$" + value];
  16998. } else {
  16999. shouldParseAnimationName = true;
  17000. }
  17001. }
  17002. const subContext = {
  17003. options: context.options,
  17004. global: context.global,
  17005. localizeNextItem: shouldParseAnimationName && !context.global,
  17006. localAliasMap: context.localAliasMap,
  17007. };
  17008. return localizeDeclNode(node, subContext);
  17009. });
  17010. declaration.value = valueNodes.toString();
  17011. return;
  17012. }
  17013. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  17014. if (isAnimationName) {
  17015. return localizeDeclarationValues(true, declaration, context);
  17016. }
  17017. const hasUrl = /url\(/i.test(declaration.value);
  17018. if (hasUrl) {
  17019. return localizeDeclarationValues(false, declaration, context);
  17020. }
  17021. }
  17022. src$2.exports = (options = {}) => {
  17023. if (
  17024. options &&
  17025. options.mode &&
  17026. options.mode !== "global" &&
  17027. options.mode !== "local" &&
  17028. options.mode !== "pure"
  17029. ) {
  17030. throw new Error(
  17031. 'options.mode must be either "global", "local" or "pure" (default "local")'
  17032. );
  17033. }
  17034. const pureMode = options && options.mode === "pure";
  17035. const globalMode = options && options.mode === "global";
  17036. return {
  17037. postcssPlugin: "postcss-modules-local-by-default",
  17038. prepare() {
  17039. const localAliasMap = new Map();
  17040. return {
  17041. Once(root) {
  17042. const { icssImports } = extractICSS(root, false);
  17043. Object.keys(icssImports).forEach((key) => {
  17044. Object.keys(icssImports[key]).forEach((prop) => {
  17045. localAliasMap.set(prop, icssImports[key][prop]);
  17046. });
  17047. });
  17048. root.walkAtRules((atRule) => {
  17049. if (/keyframes$/i.test(atRule.name)) {
  17050. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  17051. atRule.params
  17052. );
  17053. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  17054. atRule.params
  17055. );
  17056. let globalKeyframes = globalMode;
  17057. if (globalMatch) {
  17058. if (pureMode) {
  17059. throw atRule.error(
  17060. "@keyframes :global(...) is not allowed in pure mode"
  17061. );
  17062. }
  17063. atRule.params = globalMatch[1];
  17064. globalKeyframes = true;
  17065. } else if (localMatch) {
  17066. atRule.params = localMatch[0];
  17067. globalKeyframes = false;
  17068. } else if (
  17069. atRule.params &&
  17070. !globalMode &&
  17071. !localAliasMap.has(atRule.params)
  17072. ) {
  17073. atRule.params = ":local(" + atRule.params + ")";
  17074. }
  17075. atRule.walkDecls((declaration) => {
  17076. localizeDeclaration(declaration, {
  17077. localAliasMap,
  17078. options: options,
  17079. global: globalKeyframes,
  17080. });
  17081. });
  17082. } else if (/scope$/i.test(atRule.name)) {
  17083. if (atRule.params) {
  17084. atRule.params = atRule.params
  17085. .split("to")
  17086. .map((item) => {
  17087. const selector = item.trim().slice(1, -1).trim();
  17088. const context = localizeNode(
  17089. selector,
  17090. options.mode,
  17091. localAliasMap
  17092. );
  17093. context.options = options;
  17094. context.localAliasMap = localAliasMap;
  17095. if (pureMode && context.hasPureGlobals) {
  17096. throw atRule.error(
  17097. 'Selector in at-rule"' +
  17098. selector +
  17099. '" is not pure ' +
  17100. "(pure selectors must contain at least one local class or id)"
  17101. );
  17102. }
  17103. return `(${context.selector})`;
  17104. })
  17105. .join(" to ");
  17106. }
  17107. atRule.nodes.forEach((declaration) => {
  17108. if (declaration.type === "decl") {
  17109. localizeDeclaration(declaration, {
  17110. localAliasMap,
  17111. options: options,
  17112. global: globalMode,
  17113. });
  17114. }
  17115. });
  17116. } else if (atRule.nodes) {
  17117. atRule.nodes.forEach((declaration) => {
  17118. if (declaration.type === "decl") {
  17119. localizeDeclaration(declaration, {
  17120. localAliasMap,
  17121. options: options,
  17122. global: globalMode,
  17123. });
  17124. }
  17125. });
  17126. }
  17127. });
  17128. root.walkRules((rule) => {
  17129. if (
  17130. rule.parent &&
  17131. rule.parent.type === "atrule" &&
  17132. /keyframes$/i.test(rule.parent.name)
  17133. ) {
  17134. // ignore keyframe rules
  17135. return;
  17136. }
  17137. const context = localizeNode(rule, options.mode, localAliasMap);
  17138. context.options = options;
  17139. context.localAliasMap = localAliasMap;
  17140. if (pureMode && context.hasPureGlobals) {
  17141. throw rule.error(
  17142. 'Selector "' +
  17143. rule.selector +
  17144. '" is not pure ' +
  17145. "(pure selectors must contain at least one local class or id)"
  17146. );
  17147. }
  17148. rule.selector = context.selector;
  17149. // Less-syntax mixins parse as rules with no nodes
  17150. if (rule.nodes) {
  17151. rule.nodes.forEach((declaration) =>
  17152. localizeDeclaration(declaration, context)
  17153. );
  17154. }
  17155. });
  17156. },
  17157. };
  17158. },
  17159. };
  17160. };
  17161. src$2.exports.postcss = true;
  17162. return src$2.exports;
  17163. }
  17164. var src$1;
  17165. var hasRequiredSrc$1;
  17166. function requireSrc$1 () {
  17167. if (hasRequiredSrc$1) return src$1;
  17168. hasRequiredSrc$1 = 1;
  17169. const selectorParser = /*@__PURE__*/ requireDist();
  17170. const hasOwnProperty = Object.prototype.hasOwnProperty;
  17171. function isNestedRule(rule) {
  17172. if (!rule.parent || rule.parent.type === "root") {
  17173. return false;
  17174. }
  17175. if (rule.parent.type === "rule") {
  17176. return true;
  17177. }
  17178. return isNestedRule(rule.parent);
  17179. }
  17180. function getSingleLocalNamesForComposes(root, rule) {
  17181. if (isNestedRule(rule)) {
  17182. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  17183. }
  17184. return root.nodes.map((node) => {
  17185. if (node.type !== "selector" || node.nodes.length !== 1) {
  17186. throw new Error(
  17187. `composition is only allowed when selector is single :local class name not in "${root}"`
  17188. );
  17189. }
  17190. node = node.nodes[0];
  17191. if (
  17192. node.type !== "pseudo" ||
  17193. node.value !== ":local" ||
  17194. node.nodes.length !== 1
  17195. ) {
  17196. throw new Error(
  17197. 'composition is only allowed when selector is single :local class name not in "' +
  17198. root +
  17199. '", "' +
  17200. node +
  17201. '" is weird'
  17202. );
  17203. }
  17204. node = node.first;
  17205. if (node.type !== "selector" || node.length !== 1) {
  17206. throw new Error(
  17207. 'composition is only allowed when selector is single :local class name not in "' +
  17208. root +
  17209. '", "' +
  17210. node +
  17211. '" is weird'
  17212. );
  17213. }
  17214. node = node.first;
  17215. if (node.type !== "class") {
  17216. // 'id' is not possible, because you can't compose ids
  17217. throw new Error(
  17218. 'composition is only allowed when selector is single :local class name not in "' +
  17219. root +
  17220. '", "' +
  17221. node +
  17222. '" is weird'
  17223. );
  17224. }
  17225. return node.value;
  17226. });
  17227. }
  17228. const whitespace = "[\\x20\\t\\r\\n\\f]";
  17229. const unescapeRegExp = new RegExp(
  17230. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  17231. "ig"
  17232. );
  17233. function unescape(str) {
  17234. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  17235. const high = "0x" + escaped - 0x10000;
  17236. // NaN means non-codepoint
  17237. // Workaround erroneous numeric interpretation of +"0x"
  17238. return high !== high || escapedWhitespace
  17239. ? escaped
  17240. : high < 0
  17241. ? // BMP codepoint
  17242. String.fromCharCode(high + 0x10000)
  17243. : // Supplemental Plane codepoint (surrogate pair)
  17244. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  17245. });
  17246. }
  17247. const plugin = (options = {}) => {
  17248. const generateScopedName =
  17249. (options && options.generateScopedName) || plugin.generateScopedName;
  17250. const generateExportEntry =
  17251. (options && options.generateExportEntry) || plugin.generateExportEntry;
  17252. const exportGlobals = options && options.exportGlobals;
  17253. return {
  17254. postcssPlugin: "postcss-modules-scope",
  17255. Once(root, { rule }) {
  17256. const exports = Object.create(null);
  17257. function exportScopedName(name, rawName, node) {
  17258. const scopedName = generateScopedName(
  17259. rawName ? rawName : name,
  17260. root.source.input.from,
  17261. root.source.input.css,
  17262. node
  17263. );
  17264. const exportEntry = generateExportEntry(
  17265. rawName ? rawName : name,
  17266. scopedName,
  17267. root.source.input.from,
  17268. root.source.input.css,
  17269. node
  17270. );
  17271. const { key, value } = exportEntry;
  17272. exports[key] = exports[key] || [];
  17273. if (exports[key].indexOf(value) < 0) {
  17274. exports[key].push(value);
  17275. }
  17276. return scopedName;
  17277. }
  17278. function localizeNode(node) {
  17279. switch (node.type) {
  17280. case "selector":
  17281. node.nodes = node.map((item) => localizeNode(item));
  17282. return node;
  17283. case "class":
  17284. return selectorParser.className({
  17285. value: exportScopedName(
  17286. node.value,
  17287. node.raws && node.raws.value ? node.raws.value : null,
  17288. node
  17289. ),
  17290. });
  17291. case "id": {
  17292. return selectorParser.id({
  17293. value: exportScopedName(
  17294. node.value,
  17295. node.raws && node.raws.value ? node.raws.value : null,
  17296. node
  17297. ),
  17298. });
  17299. }
  17300. case "attribute": {
  17301. if (node.attribute === "class" && node.operator === "=") {
  17302. return selectorParser.attribute({
  17303. attribute: node.attribute,
  17304. operator: node.operator,
  17305. quoteMark: "'",
  17306. value: exportScopedName(node.value, null, null),
  17307. });
  17308. }
  17309. }
  17310. }
  17311. throw new Error(
  17312. `${node.type} ("${node}") is not allowed in a :local block`
  17313. );
  17314. }
  17315. function traverseNode(node) {
  17316. switch (node.type) {
  17317. case "pseudo":
  17318. if (node.value === ":local") {
  17319. if (node.nodes.length !== 1) {
  17320. throw new Error('Unexpected comma (",") in :local block');
  17321. }
  17322. const selector = localizeNode(node.first);
  17323. // move the spaces that were around the pseudo selector to the first
  17324. // non-container node
  17325. selector.first.spaces = node.spaces;
  17326. const nextNode = node.next();
  17327. if (
  17328. nextNode &&
  17329. nextNode.type === "combinator" &&
  17330. nextNode.value === " " &&
  17331. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  17332. ) {
  17333. selector.last.spaces.after = " ";
  17334. }
  17335. node.replaceWith(selector);
  17336. return;
  17337. }
  17338. /* falls through */
  17339. case "root":
  17340. case "selector": {
  17341. node.each((item) => traverseNode(item));
  17342. break;
  17343. }
  17344. case "id":
  17345. case "class":
  17346. if (exportGlobals) {
  17347. exports[node.value] = [node.value];
  17348. }
  17349. break;
  17350. }
  17351. return node;
  17352. }
  17353. // Find any :import and remember imported names
  17354. const importedNames = {};
  17355. root.walkRules(/^:import\(.+\)$/, (rule) => {
  17356. rule.walkDecls((decl) => {
  17357. importedNames[decl.prop] = true;
  17358. });
  17359. });
  17360. // Find any :local selectors
  17361. root.walkRules((rule) => {
  17362. let parsedSelector = selectorParser().astSync(rule);
  17363. rule.selector = traverseNode(parsedSelector.clone()).toString();
  17364. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  17365. const localNames = getSingleLocalNamesForComposes(
  17366. parsedSelector,
  17367. decl.parent
  17368. );
  17369. const multiple = decl.value.split(",");
  17370. multiple.forEach((value) => {
  17371. const classes = value.trim().split(/\s+/);
  17372. classes.forEach((className) => {
  17373. const global = /^global\(([^)]+)\)$/.exec(className);
  17374. if (global) {
  17375. localNames.forEach((exportedName) => {
  17376. exports[exportedName].push(global[1]);
  17377. });
  17378. } else if (hasOwnProperty.call(importedNames, className)) {
  17379. localNames.forEach((exportedName) => {
  17380. exports[exportedName].push(className);
  17381. });
  17382. } else if (hasOwnProperty.call(exports, className)) {
  17383. localNames.forEach((exportedName) => {
  17384. exports[className].forEach((item) => {
  17385. exports[exportedName].push(item);
  17386. });
  17387. });
  17388. } else {
  17389. throw decl.error(
  17390. `referenced class name "${className}" in ${decl.prop} not found`
  17391. );
  17392. }
  17393. });
  17394. });
  17395. decl.remove();
  17396. });
  17397. // Find any :local values
  17398. rule.walkDecls((decl) => {
  17399. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  17400. return;
  17401. }
  17402. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  17403. tokens = tokens.map((token, idx) => {
  17404. if (idx === 0 || tokens[idx - 1] === ",") {
  17405. let result = token;
  17406. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  17407. if (localMatch) {
  17408. const input = localMatch.input;
  17409. const matchPattern = localMatch[0];
  17410. const matchVal = localMatch[1];
  17411. const newVal = exportScopedName(matchVal);
  17412. result = input.replace(matchPattern, newVal);
  17413. } else {
  17414. return token;
  17415. }
  17416. return result;
  17417. } else {
  17418. return token;
  17419. }
  17420. });
  17421. decl.value = tokens.join("");
  17422. });
  17423. });
  17424. // Find any :local keyframes
  17425. root.walkAtRules(/keyframes$/i, (atRule) => {
  17426. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  17427. if (!localMatch) {
  17428. return;
  17429. }
  17430. atRule.params = exportScopedName(localMatch[1]);
  17431. });
  17432. root.walkAtRules(/scope$/i, (atRule) => {
  17433. if (atRule.params) {
  17434. atRule.params = atRule.params
  17435. .split("to")
  17436. .map((item) => {
  17437. const selector = item.trim().slice(1, -1).trim();
  17438. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  17439. if (!localMatch) {
  17440. return `(${selector})`;
  17441. }
  17442. let parsedSelector = selectorParser().astSync(selector);
  17443. return `(${traverseNode(parsedSelector).toString()})`;
  17444. })
  17445. .join(" to ");
  17446. }
  17447. });
  17448. // If we found any :locals, insert an :export rule
  17449. const exportedNames = Object.keys(exports);
  17450. if (exportedNames.length > 0) {
  17451. const exportRule = rule({ selector: ":export" });
  17452. exportedNames.forEach((exportedName) =>
  17453. exportRule.append({
  17454. prop: exportedName,
  17455. value: exports[exportedName].join(" "),
  17456. raws: { before: "\n " },
  17457. })
  17458. );
  17459. root.append(exportRule);
  17460. }
  17461. },
  17462. };
  17463. };
  17464. plugin.postcss = true;
  17465. plugin.generateScopedName = function (name, path) {
  17466. const sanitisedPath = path
  17467. .replace(/\.[^./\\]+$/, "")
  17468. .replace(/[\W_]+/g, "_")
  17469. .replace(/^_|_$/g, "");
  17470. return `_${sanitisedPath}__${name}`.trim();
  17471. };
  17472. plugin.generateExportEntry = function (name, scopedName) {
  17473. return {
  17474. key: unescape(name),
  17475. value: unescape(scopedName),
  17476. };
  17477. };
  17478. src$1 = plugin;
  17479. return src$1;
  17480. }
  17481. var stringHash;
  17482. var hasRequiredStringHash;
  17483. function requireStringHash () {
  17484. if (hasRequiredStringHash) return stringHash;
  17485. hasRequiredStringHash = 1;
  17486. function hash(str) {
  17487. var hash = 5381,
  17488. i = str.length;
  17489. while(i) {
  17490. hash = (hash * 33) ^ str.charCodeAt(--i);
  17491. }
  17492. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  17493. * integers. Since we want the results to be always positive, convert the
  17494. * signed int to an unsigned by doing an unsigned bitshift. */
  17495. return hash >>> 0;
  17496. }
  17497. stringHash = hash;
  17498. return stringHash;
  17499. }
  17500. var src = {exports: {}};
  17501. var hasRequiredSrc;
  17502. function requireSrc () {
  17503. if (hasRequiredSrc) return src.exports;
  17504. hasRequiredSrc = 1;
  17505. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  17506. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  17507. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  17508. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  17509. src.exports = (options) => {
  17510. let importIndex = 0;
  17511. const createImportedName =
  17512. (options && options.createImportedName) ||
  17513. ((importName /*, path*/) =>
  17514. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  17515. return {
  17516. postcssPlugin: "postcss-modules-values",
  17517. prepare(result) {
  17518. const importAliases = [];
  17519. const definitions = {};
  17520. return {
  17521. Once(root, postcss) {
  17522. root.walkAtRules(/value/i, (atRule) => {
  17523. const matches = atRule.params.match(matchImports);
  17524. if (matches) {
  17525. let [, /*match*/ aliases, path] = matches;
  17526. // We can use constants for path names
  17527. if (definitions[path]) {
  17528. path = definitions[path];
  17529. }
  17530. const imports = aliases
  17531. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  17532. .split(/\s*,\s*/)
  17533. .map((alias) => {
  17534. const tokens = matchImport.exec(alias);
  17535. if (tokens) {
  17536. const [, /*match*/ theirName, myName = theirName] = tokens;
  17537. const importedName = createImportedName(myName);
  17538. definitions[myName] = importedName;
  17539. return { theirName, importedName };
  17540. } else {
  17541. throw new Error(`@import statement "${alias}" is invalid!`);
  17542. }
  17543. });
  17544. importAliases.push({ path, imports });
  17545. atRule.remove();
  17546. return;
  17547. }
  17548. if (atRule.params.indexOf("@value") !== -1) {
  17549. result.warn("Invalid value definition: " + atRule.params);
  17550. }
  17551. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  17552. matchValueDefinition
  17553. );
  17554. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  17555. if (normalizedValue.length === 0) {
  17556. result.warn("Invalid value definition: " + atRule.params);
  17557. atRule.remove();
  17558. return;
  17559. }
  17560. let isOnlySpace = /^\s+$/.test(normalizedValue);
  17561. if (!isOnlySpace) {
  17562. value = value.trim();
  17563. }
  17564. // Add to the definitions, knowing that values can refer to each other
  17565. definitions[key] = ICSSUtils.replaceValueSymbols(
  17566. value,
  17567. definitions
  17568. );
  17569. atRule.remove();
  17570. });
  17571. /* If we have no definitions, don't continue */
  17572. if (!Object.keys(definitions).length) {
  17573. return;
  17574. }
  17575. /* Perform replacements */
  17576. ICSSUtils.replaceSymbols(root, definitions);
  17577. /* We want to export anything defined by now, but don't add it to the CSS yet or it well get picked up by the replacement stuff */
  17578. const exportDeclarations = Object.keys(definitions).map((key) =>
  17579. postcss.decl({
  17580. value: definitions[key],
  17581. prop: key,
  17582. raws: { before: "\n " },
  17583. })
  17584. );
  17585. /* Add export rules if any */
  17586. if (exportDeclarations.length > 0) {
  17587. const exportRule = postcss.rule({
  17588. selector: ":export",
  17589. raws: { after: "\n" },
  17590. });
  17591. exportRule.append(exportDeclarations);
  17592. root.prepend(exportRule);
  17593. }
  17594. /* Add import rules */
  17595. importAliases.reverse().forEach(({ path, imports }) => {
  17596. const importRule = postcss.rule({
  17597. selector: `:import(${path})`,
  17598. raws: { after: "\n" },
  17599. });
  17600. imports.forEach(({ theirName, importedName }) => {
  17601. importRule.append({
  17602. value: theirName,
  17603. prop: importedName,
  17604. raws: { before: "\n " },
  17605. });
  17606. });
  17607. root.prepend(importRule);
  17608. });
  17609. },
  17610. };
  17611. },
  17612. };
  17613. };
  17614. src.exports.postcss = true;
  17615. return src.exports;
  17616. }
  17617. var hasRequiredScoping;
  17618. function requireScoping () {
  17619. if (hasRequiredScoping) return scoping;
  17620. hasRequiredScoping = 1;
  17621. Object.defineProperty(scoping, "__esModule", {
  17622. value: true
  17623. });
  17624. scoping.behaviours = void 0;
  17625. scoping.getDefaultPlugins = getDefaultPlugins;
  17626. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  17627. scoping.getScopedNameGenerator = getScopedNameGenerator;
  17628. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  17629. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  17630. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  17631. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  17632. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  17633. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  17634. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17635. const behaviours = {
  17636. LOCAL: "local",
  17637. GLOBAL: "global"
  17638. };
  17639. scoping.behaviours = behaviours;
  17640. function getDefaultPlugins({
  17641. behaviour,
  17642. generateScopedName,
  17643. exportGlobals
  17644. }) {
  17645. const scope = (0, _postcssModulesScope.default)({
  17646. generateScopedName,
  17647. exportGlobals
  17648. });
  17649. const plugins = {
  17650. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17651. mode: "local"
  17652. }), _postcssModulesExtractImports.default, scope],
  17653. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17654. mode: "global"
  17655. }), _postcssModulesExtractImports.default, scope]
  17656. };
  17657. return plugins[behaviour];
  17658. }
  17659. function isValidBehaviour(behaviour) {
  17660. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  17661. }
  17662. function getDefaultScopeBehaviour(scopeBehaviour) {
  17663. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  17664. }
  17665. function generateScopedNameDefault(name, filename, css) {
  17666. const i = css.indexOf(`.${name}`);
  17667. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  17668. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  17669. return `_${name}_${hash}_${lineNumber}`;
  17670. }
  17671. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  17672. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  17673. if (typeof scopedNameGenerator === "function") {
  17674. return scopedNameGenerator;
  17675. }
  17676. return (0, _genericNames.default)(scopedNameGenerator, {
  17677. context: process.cwd(),
  17678. hashPrefix: hashPrefix
  17679. });
  17680. }
  17681. return scoping;
  17682. }
  17683. var hasRequiredPluginFactory;
  17684. function requirePluginFactory () {
  17685. if (hasRequiredPluginFactory) return pluginFactory;
  17686. hasRequiredPluginFactory = 1;
  17687. Object.defineProperty(pluginFactory, "__esModule", {
  17688. value: true
  17689. });
  17690. pluginFactory.makePlugin = makePlugin;
  17691. var _postcss = _interopRequireDefault(require$$0$1);
  17692. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  17693. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  17694. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  17695. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  17696. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  17697. var _scoping = /*@__PURE__*/ requireScoping();
  17698. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17699. const PLUGIN_NAME = "postcss-modules";
  17700. function isGlobalModule(globalModules, inputFile) {
  17701. return globalModules.some(regex => inputFile.match(regex));
  17702. }
  17703. function getDefaultPluginsList(opts, inputFile) {
  17704. const globalModulesList = opts.globalModulePaths || null;
  17705. const exportGlobals = opts.exportGlobals || false;
  17706. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  17707. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  17708. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  17709. return (0, _scoping.getDefaultPlugins)({
  17710. behaviour: _scoping.behaviours.GLOBAL,
  17711. generateScopedName,
  17712. exportGlobals
  17713. });
  17714. }
  17715. return (0, _scoping.getDefaultPlugins)({
  17716. behaviour: defaultBehaviour,
  17717. generateScopedName,
  17718. exportGlobals
  17719. });
  17720. }
  17721. function getLoader(opts, plugins) {
  17722. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  17723. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  17724. }
  17725. function isOurPlugin(plugin) {
  17726. return plugin.postcssPlugin === PLUGIN_NAME;
  17727. }
  17728. function makePlugin(opts) {
  17729. return {
  17730. postcssPlugin: PLUGIN_NAME,
  17731. async OnceExit(css, {
  17732. result
  17733. }) {
  17734. const getJSON = opts.getJSON || _saveJSON.default;
  17735. const inputFile = css.source.input.file;
  17736. const pluginList = getDefaultPluginsList(opts, inputFile);
  17737. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  17738. if (resultPluginIndex === -1) {
  17739. throw new Error("Plugin missing from options.");
  17740. }
  17741. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  17742. const loaderPlugins = [...earlierPlugins, ...pluginList];
  17743. const loader = getLoader(opts, loaderPlugins);
  17744. const fetcher = async (file, relativeTo, depTrace) => {
  17745. const unquoteFile = (0, _unquote.default)(file);
  17746. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  17747. };
  17748. const parser = new _Parser.default(fetcher);
  17749. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  17750. from: inputFile
  17751. });
  17752. const out = loader.finalSource;
  17753. if (out) css.prepend(out);
  17754. if (opts.localsConvention) {
  17755. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  17756. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  17757. }
  17758. result.messages.push({
  17759. type: "export",
  17760. plugin: "postcss-modules",
  17761. exportTokens: parser.exportTokens
  17762. }); // getJSON may return a promise
  17763. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  17764. }
  17765. };
  17766. }
  17767. return pluginFactory;
  17768. }
  17769. var hasRequiredBuild;
  17770. function requireBuild () {
  17771. if (hasRequiredBuild) return build.exports;
  17772. hasRequiredBuild = 1;
  17773. var _fs = require$$0;
  17774. var _fs2 = /*@__PURE__*/ requireFs();
  17775. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  17776. (0, _fs2.setFileSystem)({
  17777. readFile: _fs.readFile,
  17778. writeFile: _fs.writeFile
  17779. });
  17780. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  17781. build.exports.postcss = true;
  17782. return build.exports;
  17783. }
  17784. var buildExports = /*@__PURE__*/ requireBuild();
  17785. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  17786. function compileStyle(options) {
  17787. return doCompileStyle({
  17788. ...options,
  17789. isAsync: false
  17790. });
  17791. }
  17792. function compileStyleAsync(options) {
  17793. return doCompileStyle({
  17794. ...options,
  17795. isAsync: true
  17796. });
  17797. }
  17798. function doCompileStyle(options) {
  17799. const {
  17800. filename,
  17801. id,
  17802. scoped = false,
  17803. trim = true,
  17804. isProd = false,
  17805. modules = false,
  17806. modulesOptions = {},
  17807. preprocessLang,
  17808. postcssOptions,
  17809. postcssPlugins
  17810. } = options;
  17811. const preprocessor = preprocessLang && processors[preprocessLang];
  17812. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  17813. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  17814. const source = preProcessedSource ? preProcessedSource.code : options.source;
  17815. const shortId = id.replace(/^data-v-/, "");
  17816. const longId = `data-v-${shortId}`;
  17817. const plugins = (postcssPlugins || []).slice();
  17818. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  17819. if (trim) {
  17820. plugins.push(trimPlugin());
  17821. }
  17822. if (scoped) {
  17823. plugins.push(scopedPlugin(longId));
  17824. }
  17825. let cssModules;
  17826. if (modules) {
  17827. if (!options.isAsync) {
  17828. throw new Error(
  17829. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  17830. );
  17831. }
  17832. plugins.push(
  17833. postcssModules({
  17834. ...modulesOptions,
  17835. getJSON: (_cssFileName, json) => {
  17836. cssModules = json;
  17837. }
  17838. })
  17839. );
  17840. }
  17841. const postCSSOptions = {
  17842. ...postcssOptions,
  17843. to: filename,
  17844. from: filename
  17845. };
  17846. if (map) {
  17847. postCSSOptions.map = {
  17848. inline: false,
  17849. annotation: false,
  17850. prev: map
  17851. };
  17852. }
  17853. let result;
  17854. let code;
  17855. let outMap;
  17856. const dependencies = new Set(
  17857. preProcessedSource ? preProcessedSource.dependencies : []
  17858. );
  17859. dependencies.delete(filename);
  17860. const errors = [];
  17861. if (preProcessedSource && preProcessedSource.errors.length) {
  17862. errors.push(...preProcessedSource.errors);
  17863. }
  17864. const recordPlainCssDependencies = (messages) => {
  17865. messages.forEach((msg) => {
  17866. if (msg.type === "dependency") {
  17867. dependencies.add(msg.file);
  17868. }
  17869. });
  17870. return dependencies;
  17871. };
  17872. try {
  17873. result = require$$0$1(plugins).process(source, postCSSOptions);
  17874. if (options.isAsync) {
  17875. return result.then((result2) => ({
  17876. code: result2.css || "",
  17877. map: result2.map && result2.map.toJSON(),
  17878. errors,
  17879. modules: cssModules,
  17880. rawResult: result2,
  17881. dependencies: recordPlainCssDependencies(result2.messages)
  17882. })).catch((error) => ({
  17883. code: "",
  17884. map: void 0,
  17885. errors: [...errors, error],
  17886. rawResult: void 0,
  17887. dependencies
  17888. }));
  17889. }
  17890. recordPlainCssDependencies(result.messages);
  17891. code = result.css;
  17892. outMap = result.map;
  17893. } catch (e) {
  17894. errors.push(e);
  17895. }
  17896. return {
  17897. code: code || ``,
  17898. map: outMap && outMap.toJSON(),
  17899. errors,
  17900. rawResult: result,
  17901. dependencies
  17902. };
  17903. }
  17904. function preprocess(options, preprocessor) {
  17905. return preprocessor(
  17906. options.source,
  17907. options.inMap || options.map,
  17908. {
  17909. filename: options.filename,
  17910. ...options.preprocessOptions
  17911. },
  17912. options.preprocessCustomRequire
  17913. );
  17914. }
  17915. const UNKNOWN_TYPE = "Unknown";
  17916. function resolveObjectKey(node, computed) {
  17917. switch (node.type) {
  17918. case "StringLiteral":
  17919. case "NumericLiteral":
  17920. return String(node.value);
  17921. case "Identifier":
  17922. if (!computed) return node.name;
  17923. }
  17924. return void 0;
  17925. }
  17926. function concatStrings(strs) {
  17927. return strs.filter((s) => !!s).join(", ");
  17928. }
  17929. function isLiteralNode(node) {
  17930. return node.type.endsWith("Literal");
  17931. }
  17932. function isCallOf(node, test) {
  17933. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  17934. }
  17935. function toRuntimeTypeString(types) {
  17936. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  17937. }
  17938. function getImportedName(specifier) {
  17939. if (specifier.type === "ImportSpecifier")
  17940. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  17941. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  17942. return "default";
  17943. }
  17944. function getId(node) {
  17945. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  17946. }
  17947. function getStringLiteralKey(node) {
  17948. return node.computed ? node.key.type === "TemplateLiteral" && !node.key.expressions.length ? node.key.quasis.map((q) => q.value.cooked).join("") : null : node.key.type === "Identifier" ? node.key.name : node.key.type === "StringLiteral" ? node.key.value : node.key.type === "NumericLiteral" ? String(node.key.value) : null;
  17949. }
  17950. const identity = (str) => str;
  17951. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  17952. const toLowerCase = (str) => str.toLowerCase();
  17953. function toFileNameLowerCase(x) {
  17954. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  17955. }
  17956. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  17957. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  17958. }
  17959. const normalize = (path$1.posix || path$1).normalize;
  17960. const windowsSlashRE = /\\/g;
  17961. function normalizePath(p) {
  17962. return normalize(p.replace(windowsSlashRE, "/"));
  17963. }
  17964. const joinPaths = (path$1.posix || path$1).join;
  17965. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  17966. function getEscapedPropName(key) {
  17967. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  17968. }
  17969. const isJS = (...langs) => langs.some((lang) => lang === "js" || lang === "jsx");
  17970. const isTS = (...langs) => langs.some((lang) => lang === "ts" || lang === "tsx");
  17971. function analyzeScriptBindings(ast) {
  17972. for (const node of ast) {
  17973. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  17974. return analyzeBindingsFromOptions(node.declaration);
  17975. }
  17976. }
  17977. return {};
  17978. }
  17979. function analyzeBindingsFromOptions(node) {
  17980. const bindings = {};
  17981. Object.defineProperty(bindings, "__isScriptSetup", {
  17982. enumerable: false,
  17983. value: false
  17984. });
  17985. for (const property of node.properties) {
  17986. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  17987. if (property.key.name === "props") {
  17988. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17989. bindings[key] = "props";
  17990. }
  17991. } else if (property.key.name === "inject") {
  17992. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17993. bindings[key] = "options";
  17994. }
  17995. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  17996. for (const key of getObjectExpressionKeys(property.value)) {
  17997. bindings[key] = "options";
  17998. }
  17999. }
  18000. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  18001. for (const bodyItem of property.body.body) {
  18002. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  18003. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  18004. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  18005. }
  18006. }
  18007. }
  18008. }
  18009. }
  18010. return bindings;
  18011. }
  18012. function getObjectExpressionKeys(node) {
  18013. const keys = [];
  18014. for (const prop of node.properties) {
  18015. if (prop.type === "SpreadElement") continue;
  18016. const key = resolveObjectKey(prop.key, prop.computed);
  18017. if (key) keys.push(String(key));
  18018. }
  18019. return keys;
  18020. }
  18021. function getArrayExpressionKeys(node) {
  18022. const keys = [];
  18023. for (const element of node.elements) {
  18024. if (element && element.type === "StringLiteral") {
  18025. keys.push(element.value);
  18026. }
  18027. }
  18028. return keys;
  18029. }
  18030. function getObjectOrArrayExpressionKeys(value) {
  18031. if (value.type === "ArrayExpression") {
  18032. return getArrayExpressionKeys(value);
  18033. }
  18034. if (value.type === "ObjectExpression") {
  18035. return getObjectExpressionKeys(value);
  18036. }
  18037. return [];
  18038. }
  18039. var _a$1, _b;
  18040. class ScriptCompileContext {
  18041. constructor(descriptor, options) {
  18042. this.descriptor = descriptor;
  18043. this.options = options;
  18044. this.isCE = false;
  18045. this.source = this.descriptor.source;
  18046. this.filename = this.descriptor.filename;
  18047. this.s = new MagicString(this.source);
  18048. this.startOffset = (_a$1 = this.descriptor.scriptSetup) == null ? void 0 : _a$1.loc.start.offset;
  18049. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  18050. this.userImports = /* @__PURE__ */ Object.create(null);
  18051. // macros presence check
  18052. this.hasDefinePropsCall = false;
  18053. this.hasDefineEmitCall = false;
  18054. this.hasDefineExposeCall = false;
  18055. this.hasDefaultExportName = false;
  18056. this.hasDefaultExportRender = false;
  18057. this.hasDefineOptionsCall = false;
  18058. this.hasDefineSlotsCall = false;
  18059. this.hasDefineModelCall = false;
  18060. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  18061. // defineModel
  18062. this.modelDecls = /* @__PURE__ */ Object.create(null);
  18063. // codegen
  18064. this.bindingMetadata = {};
  18065. this.helperImports = /* @__PURE__ */ new Set();
  18066. const { script, scriptSetup } = descriptor;
  18067. const scriptLang = script && script.lang;
  18068. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  18069. this.isJS = isJS(scriptLang, scriptSetupLang);
  18070. this.isTS = isTS(scriptLang, scriptSetupLang);
  18071. const customElement = options.customElement;
  18072. const filename = this.descriptor.filename;
  18073. if (customElement) {
  18074. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  18075. }
  18076. const plugins = resolveParserPlugins(
  18077. scriptLang || scriptSetupLang,
  18078. options.babelParserPlugins
  18079. );
  18080. function parse(input, offset) {
  18081. try {
  18082. return parser$2.parse(input, {
  18083. plugins,
  18084. sourceType: "module"
  18085. }).program;
  18086. } catch (e) {
  18087. e.message = `[vue/compiler-sfc] ${e.message}
  18088. ${descriptor.filename}
  18089. ${shared.generateCodeFrame(
  18090. descriptor.source,
  18091. e.pos + offset,
  18092. e.pos + offset + 1
  18093. )}`;
  18094. throw e;
  18095. }
  18096. }
  18097. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  18098. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  18099. }
  18100. helper(key) {
  18101. this.helperImports.add(key);
  18102. return `_${key}`;
  18103. }
  18104. getString(node, scriptSetup = true) {
  18105. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  18106. return block.content.slice(node.start, node.end);
  18107. }
  18108. warn(msg, node, scope) {
  18109. warn(generateError(msg, node, this, scope));
  18110. }
  18111. error(msg, node, scope) {
  18112. throw new Error(
  18113. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  18114. );
  18115. }
  18116. }
  18117. function generateError(msg, node, ctx, scope) {
  18118. const offset = scope ? scope.offset : ctx.startOffset;
  18119. return `${msg}
  18120. ${(scope || ctx.descriptor).filename}
  18121. ${shared.generateCodeFrame(
  18122. (scope || ctx.descriptor).source,
  18123. node.start + offset,
  18124. node.end + offset
  18125. )}`;
  18126. }
  18127. function resolveParserPlugins(lang, userPlugins, dts = false) {
  18128. const plugins = [];
  18129. if (!userPlugins || !userPlugins.some(
  18130. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  18131. )) {
  18132. plugins.push("importAttributes");
  18133. }
  18134. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  18135. plugins.push("jsx");
  18136. } else if (userPlugins) {
  18137. userPlugins = userPlugins.filter((p) => p !== "jsx");
  18138. }
  18139. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "cts" || lang === "mtsx") {
  18140. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  18141. if (!userPlugins || !userPlugins.includes("decorators")) {
  18142. plugins.push("decorators-legacy");
  18143. }
  18144. }
  18145. if (userPlugins) {
  18146. plugins.push(...userPlugins);
  18147. }
  18148. return plugins;
  18149. }
  18150. function rewriteDefault(input, as, parserPlugins) {
  18151. const ast = parser$2.parse(input, {
  18152. sourceType: "module",
  18153. plugins: resolveParserPlugins("js", parserPlugins)
  18154. }).program.body;
  18155. const s = new MagicString(input);
  18156. rewriteDefaultAST(ast, s, as);
  18157. return s.toString();
  18158. }
  18159. function rewriteDefaultAST(ast, s, as) {
  18160. if (!hasDefaultExport(ast)) {
  18161. s.append(`
  18162. const ${as} = {}`);
  18163. return;
  18164. }
  18165. ast.forEach((node) => {
  18166. if (node.type === "ExportDefaultDeclaration") {
  18167. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  18168. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  18169. s.overwrite(start, node.declaration.id.start, ` class `);
  18170. s.append(`
  18171. const ${as} = ${node.declaration.id.name}`);
  18172. } else {
  18173. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  18174. }
  18175. } else if (node.type === "ExportNamedDeclaration") {
  18176. for (const specifier of node.specifiers) {
  18177. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  18178. if (node.source) {
  18179. if (specifier.local.name === "default") {
  18180. s.prepend(
  18181. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  18182. `
  18183. );
  18184. const end2 = specifierEnd(s, specifier.local.end, node.end);
  18185. s.remove(specifier.start, end2);
  18186. s.append(`
  18187. const ${as} = __VUE_DEFAULT__`);
  18188. continue;
  18189. } else {
  18190. s.prepend(
  18191. `import { ${s.slice(
  18192. specifier.local.start,
  18193. specifier.local.end
  18194. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  18195. `
  18196. );
  18197. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  18198. s.remove(specifier.start, end2);
  18199. s.append(`
  18200. const ${as} = __VUE_DEFAULT__`);
  18201. continue;
  18202. }
  18203. }
  18204. const end = specifierEnd(s, specifier.end, node.end);
  18205. s.remove(specifier.start, end);
  18206. s.append(`
  18207. const ${as} = ${specifier.local.name}`);
  18208. }
  18209. }
  18210. }
  18211. });
  18212. }
  18213. function hasDefaultExport(ast) {
  18214. for (const stmt of ast) {
  18215. if (stmt.type === "ExportDefaultDeclaration") {
  18216. return true;
  18217. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  18218. (spec) => spec.exported.name === "default"
  18219. )) {
  18220. return true;
  18221. }
  18222. }
  18223. return false;
  18224. }
  18225. function specifierEnd(s, end, nodeEnd) {
  18226. let hasCommas = false;
  18227. let oldEnd = end;
  18228. while (end < nodeEnd) {
  18229. if (/\s/.test(s.slice(end, end + 1))) {
  18230. end++;
  18231. } else if (s.slice(end, end + 1) === ",") {
  18232. end++;
  18233. hasCommas = true;
  18234. break;
  18235. } else if (s.slice(end, end + 1) === "}") {
  18236. break;
  18237. }
  18238. }
  18239. return hasCommas ? end : oldEnd;
  18240. }
  18241. const normalScriptDefaultVar = `__default__`;
  18242. function processNormalScript(ctx, scopeId) {
  18243. var _a;
  18244. const script = ctx.descriptor.script;
  18245. try {
  18246. let content = script.content;
  18247. let map = script.map;
  18248. const scriptAst = ctx.scriptAst;
  18249. const bindings = analyzeScriptBindings(scriptAst.body);
  18250. const { cssVars } = ctx.descriptor;
  18251. const { genDefaultAs, isProd } = ctx.options;
  18252. if (cssVars.length || genDefaultAs) {
  18253. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  18254. const s = new MagicString(content);
  18255. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  18256. content = s.toString();
  18257. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  18258. content += genNormalScriptCssVarsCode(
  18259. cssVars,
  18260. bindings,
  18261. scopeId,
  18262. !!isProd,
  18263. defaultVar
  18264. );
  18265. }
  18266. if (!genDefaultAs) {
  18267. content += `
  18268. export default ${defaultVar}`;
  18269. }
  18270. }
  18271. return {
  18272. ...script,
  18273. content,
  18274. map,
  18275. bindings,
  18276. scriptAst: scriptAst.body
  18277. };
  18278. } catch (e) {
  18279. return script;
  18280. }
  18281. }
  18282. const balanced = (a, b, str) => {
  18283. const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
  18284. const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
  18285. const r = ma !== null && mb != null && range(ma, mb, str);
  18286. return (r && {
  18287. start: r[0],
  18288. end: r[1],
  18289. pre: str.slice(0, r[0]),
  18290. body: str.slice(r[0] + ma.length, r[1]),
  18291. post: str.slice(r[1] + mb.length),
  18292. });
  18293. };
  18294. const maybeMatch = (reg, str) => {
  18295. const m = str.match(reg);
  18296. return m ? m[0] : null;
  18297. };
  18298. const range = (a, b, str) => {
  18299. let begs, beg, left, right = undefined, result;
  18300. let ai = str.indexOf(a);
  18301. let bi = str.indexOf(b, ai + 1);
  18302. let i = ai;
  18303. if (ai >= 0 && bi > 0) {
  18304. if (a === b) {
  18305. return [ai, bi];
  18306. }
  18307. begs = [];
  18308. left = str.length;
  18309. while (i >= 0 && !result) {
  18310. if (i === ai) {
  18311. begs.push(i);
  18312. ai = str.indexOf(a, i + 1);
  18313. }
  18314. else if (begs.length === 1) {
  18315. const r = begs.pop();
  18316. if (r !== undefined)
  18317. result = [r, bi];
  18318. }
  18319. else {
  18320. beg = begs.pop();
  18321. if (beg !== undefined && beg < left) {
  18322. left = beg;
  18323. right = bi;
  18324. }
  18325. bi = str.indexOf(b, i + 1);
  18326. }
  18327. i = ai < bi && ai >= 0 ? ai : bi;
  18328. }
  18329. if (begs.length && right !== undefined) {
  18330. result = [left, right];
  18331. }
  18332. }
  18333. return result;
  18334. };
  18335. const escSlash = '\0SLASH' + Math.random() + '\0';
  18336. const escOpen = '\0OPEN' + Math.random() + '\0';
  18337. const escClose = '\0CLOSE' + Math.random() + '\0';
  18338. const escComma = '\0COMMA' + Math.random() + '\0';
  18339. const escPeriod = '\0PERIOD' + Math.random() + '\0';
  18340. const escSlashPattern = new RegExp(escSlash, 'g');
  18341. const escOpenPattern = new RegExp(escOpen, 'g');
  18342. const escClosePattern = new RegExp(escClose, 'g');
  18343. const escCommaPattern = new RegExp(escComma, 'g');
  18344. const escPeriodPattern = new RegExp(escPeriod, 'g');
  18345. const slashPattern = /\\\\/g;
  18346. const openPattern = /\\{/g;
  18347. const closePattern = /\\}/g;
  18348. const commaPattern = /\\,/g;
  18349. const periodPattern = /\\\./g;
  18350. const EXPANSION_MAX = 100_000;
  18351. function numeric(str) {
  18352. return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
  18353. }
  18354. function escapeBraces(str) {
  18355. return str
  18356. .replace(slashPattern, escSlash)
  18357. .replace(openPattern, escOpen)
  18358. .replace(closePattern, escClose)
  18359. .replace(commaPattern, escComma)
  18360. .replace(periodPattern, escPeriod);
  18361. }
  18362. function unescapeBraces(str) {
  18363. return str
  18364. .replace(escSlashPattern, '\\')
  18365. .replace(escOpenPattern, '{')
  18366. .replace(escClosePattern, '}')
  18367. .replace(escCommaPattern, ',')
  18368. .replace(escPeriodPattern, '.');
  18369. }
  18370. /**
  18371. * Basically just str.split(","), but handling cases
  18372. * where we have nested braced sections, which should be
  18373. * treated as individual members, like {a,{b,c},d}
  18374. */
  18375. function parseCommaParts(str) {
  18376. if (!str) {
  18377. return [''];
  18378. }
  18379. const parts = [];
  18380. const m = balanced('{', '}', str);
  18381. if (!m) {
  18382. return str.split(',');
  18383. }
  18384. const { pre, body, post } = m;
  18385. const p = pre.split(',');
  18386. p[p.length - 1] += '{' + body + '}';
  18387. const postParts = parseCommaParts(post);
  18388. if (post.length) {
  18389. p[p.length - 1] += postParts.shift();
  18390. p.push.apply(p, postParts);
  18391. }
  18392. parts.push.apply(parts, p);
  18393. return parts;
  18394. }
  18395. function expand(str, options = {}) {
  18396. if (!str) {
  18397. return [];
  18398. }
  18399. const { max = EXPANSION_MAX } = options;
  18400. // I don't know why Bash 4.3 does this, but it does.
  18401. // Anything starting with {} will have the first two bytes preserved
  18402. // but *only* at the top level, so {},a}b will not expand to anything,
  18403. // but a{},b}c will be expanded to [a}c,abc].
  18404. // One could argue that this is a bug in Bash, but since the goal of
  18405. // this module is to match Bash's rules, we escape a leading {}
  18406. if (str.slice(0, 2) === '{}') {
  18407. str = '\\{\\}' + str.slice(2);
  18408. }
  18409. return expand_(escapeBraces(str), max, true).map(unescapeBraces);
  18410. }
  18411. function embrace(str) {
  18412. return '{' + str + '}';
  18413. }
  18414. function isPadded(el) {
  18415. return /^-?0\d/.test(el);
  18416. }
  18417. function lte(i, y) {
  18418. return i <= y;
  18419. }
  18420. function gte(i, y) {
  18421. return i >= y;
  18422. }
  18423. function expand_(str, max, isTop) {
  18424. /** @type {string[]} */
  18425. const expansions = [];
  18426. const m = balanced('{', '}', str);
  18427. if (!m)
  18428. return [str];
  18429. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18430. const pre = m.pre;
  18431. const post = m.post.length ? expand_(m.post, max, false) : [''];
  18432. if (/\$$/.test(m.pre)) {
  18433. for (let k = 0; k < post.length && k < max; k++) {
  18434. const expansion = pre + '{' + m.body + '}' + post[k];
  18435. expansions.push(expansion);
  18436. }
  18437. }
  18438. else {
  18439. const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18440. const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18441. const isSequence = isNumericSequence || isAlphaSequence;
  18442. const isOptions = m.body.indexOf(',') >= 0;
  18443. if (!isSequence && !isOptions) {
  18444. // {a},b}
  18445. if (m.post.match(/,(?!,).*\}/)) {
  18446. str = m.pre + '{' + m.body + escClose + m.post;
  18447. return expand_(str, max, true);
  18448. }
  18449. return [str];
  18450. }
  18451. let n;
  18452. if (isSequence) {
  18453. n = m.body.split(/\.\./);
  18454. }
  18455. else {
  18456. n = parseCommaParts(m.body);
  18457. if (n.length === 1 && n[0] !== undefined) {
  18458. // x{{a,b}}y ==> x{a}y x{b}y
  18459. n = expand_(n[0], max, false).map(embrace);
  18460. //XXX is this necessary? Can't seem to hit it in tests.
  18461. /* c8 ignore start */
  18462. if (n.length === 1) {
  18463. return post.map(p => m.pre + n[0] + p);
  18464. }
  18465. /* c8 ignore stop */
  18466. }
  18467. }
  18468. // at this point, n is the parts, and we know it's not a comma set
  18469. // with a single entry.
  18470. let N;
  18471. if (isSequence && n[0] !== undefined && n[1] !== undefined) {
  18472. const x = numeric(n[0]);
  18473. const y = numeric(n[1]);
  18474. const width = Math.max(n[0].length, n[1].length);
  18475. let incr = n.length === 3 && n[2] !== undefined ?
  18476. Math.max(Math.abs(numeric(n[2])), 1)
  18477. : 1;
  18478. let test = lte;
  18479. const reverse = y < x;
  18480. if (reverse) {
  18481. incr *= -1;
  18482. test = gte;
  18483. }
  18484. const pad = n.some(isPadded);
  18485. N = [];
  18486. for (let i = x; test(i, y); i += incr) {
  18487. let c;
  18488. if (isAlphaSequence) {
  18489. c = String.fromCharCode(i);
  18490. if (c === '\\') {
  18491. c = '';
  18492. }
  18493. }
  18494. else {
  18495. c = String(i);
  18496. if (pad) {
  18497. const need = width - c.length;
  18498. if (need > 0) {
  18499. const z = new Array(need + 1).join('0');
  18500. if (i < 0) {
  18501. c = '-' + z + c.slice(1);
  18502. }
  18503. else {
  18504. c = z + c;
  18505. }
  18506. }
  18507. }
  18508. }
  18509. N.push(c);
  18510. }
  18511. }
  18512. else {
  18513. N = [];
  18514. for (let j = 0; j < n.length; j++) {
  18515. N.push.apply(N, expand_(n[j], max, false));
  18516. }
  18517. }
  18518. for (let j = 0; j < N.length; j++) {
  18519. for (let k = 0; k < post.length && expansions.length < max; k++) {
  18520. const expansion = pre + N[j] + post[k];
  18521. if (!isTop || isSequence || expansion) {
  18522. expansions.push(expansion);
  18523. }
  18524. }
  18525. }
  18526. }
  18527. return expansions;
  18528. }
  18529. const MAX_PATTERN_LENGTH = 1024 * 64;
  18530. const assertValidPattern = (pattern) => {
  18531. if (typeof pattern !== 'string') {
  18532. throw new TypeError('invalid pattern');
  18533. }
  18534. if (pattern.length > MAX_PATTERN_LENGTH) {
  18535. throw new TypeError('pattern is too long');
  18536. }
  18537. };
  18538. // translate the various posix character classes into unicode properties
  18539. // this works across all unicode locales
  18540. // { <posix class>: [<translation>, /u flag required, negated]
  18541. const posixClasses = {
  18542. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  18543. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  18544. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  18545. '[:blank:]': ['\\p{Zs}\\t', true],
  18546. '[:cntrl:]': ['\\p{Cc}', true],
  18547. '[:digit:]': ['\\p{Nd}', true],
  18548. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  18549. '[:lower:]': ['\\p{Ll}', true],
  18550. '[:print:]': ['\\p{C}', true],
  18551. '[:punct:]': ['\\p{P}', true],
  18552. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  18553. '[:upper:]': ['\\p{Lu}', true],
  18554. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  18555. '[:xdigit:]': ['A-Fa-f0-9', false],
  18556. };
  18557. // only need to escape a few things inside of brace expressions
  18558. // escapes: [ \ ] -
  18559. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  18560. // escape all regexp magic characters
  18561. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18562. // everything has already been escaped, we just have to join
  18563. const rangesToString = (ranges) => ranges.join('');
  18564. // takes a glob string at a posix brace expression, and returns
  18565. // an equivalent regular expression source, and boolean indicating
  18566. // whether the /u flag needs to be applied, and the number of chars
  18567. // consumed to parse the character class.
  18568. // This also removes out of order ranges, and returns ($.) if the
  18569. // entire class just no good.
  18570. const parseClass = (glob, position) => {
  18571. const pos = position;
  18572. /* c8 ignore start */
  18573. if (glob.charAt(pos) !== '[') {
  18574. throw new Error('not in a brace expression');
  18575. }
  18576. /* c8 ignore stop */
  18577. const ranges = [];
  18578. const negs = [];
  18579. let i = pos + 1;
  18580. let sawStart = false;
  18581. let uflag = false;
  18582. let escaping = false;
  18583. let negate = false;
  18584. let endPos = pos;
  18585. let rangeStart = '';
  18586. WHILE: while (i < glob.length) {
  18587. const c = glob.charAt(i);
  18588. if ((c === '!' || c === '^') && i === pos + 1) {
  18589. negate = true;
  18590. i++;
  18591. continue;
  18592. }
  18593. if (c === ']' && sawStart && !escaping) {
  18594. endPos = i + 1;
  18595. break;
  18596. }
  18597. sawStart = true;
  18598. if (c === '\\') {
  18599. if (!escaping) {
  18600. escaping = true;
  18601. i++;
  18602. continue;
  18603. }
  18604. // escaped \ char, fall through and treat like normal char
  18605. }
  18606. if (c === '[' && !escaping) {
  18607. // either a posix class, a collation equivalent, or just a [
  18608. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  18609. if (glob.startsWith(cls, i)) {
  18610. // invalid, [a-[] is fine, but not [a-[:alpha]]
  18611. if (rangeStart) {
  18612. return ['$.', false, glob.length - pos, true];
  18613. }
  18614. i += cls.length;
  18615. if (neg)
  18616. negs.push(unip);
  18617. else
  18618. ranges.push(unip);
  18619. uflag = uflag || u;
  18620. continue WHILE;
  18621. }
  18622. }
  18623. }
  18624. // now it's just a normal character, effectively
  18625. escaping = false;
  18626. if (rangeStart) {
  18627. // throw this range away if it's not valid, but others
  18628. // can still match.
  18629. if (c > rangeStart) {
  18630. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  18631. }
  18632. else if (c === rangeStart) {
  18633. ranges.push(braceEscape(c));
  18634. }
  18635. rangeStart = '';
  18636. i++;
  18637. continue;
  18638. }
  18639. // now might be the start of a range.
  18640. // can be either c-d or c-] or c<more...>] or c] at this point
  18641. if (glob.startsWith('-]', i + 1)) {
  18642. ranges.push(braceEscape(c + '-'));
  18643. i += 2;
  18644. continue;
  18645. }
  18646. if (glob.startsWith('-', i + 1)) {
  18647. rangeStart = c;
  18648. i += 2;
  18649. continue;
  18650. }
  18651. // not the start of a range, just a single character
  18652. ranges.push(braceEscape(c));
  18653. i++;
  18654. }
  18655. if (endPos < i) {
  18656. // didn't see the end of the class, not a valid class,
  18657. // but might still be valid as a literal match.
  18658. return ['', false, 0, false];
  18659. }
  18660. // if we got no ranges and no negates, then we have a range that
  18661. // cannot possibly match anything, and that poisons the whole glob
  18662. if (!ranges.length && !negs.length) {
  18663. return ['$.', false, glob.length - pos, true];
  18664. }
  18665. // if we got one positive range, and it's a single character, then that's
  18666. // not actually a magic pattern, it's just that one literal character.
  18667. // we should not treat that as "magic", we should just return the literal
  18668. // character. [_] is a perfectly valid way to escape glob magic chars.
  18669. if (negs.length === 0 &&
  18670. ranges.length === 1 &&
  18671. /^\\?.$/.test(ranges[0]) &&
  18672. !negate) {
  18673. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  18674. return [regexpEscape(r), false, endPos - pos, false];
  18675. }
  18676. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  18677. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  18678. const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
  18679. : ranges.length ? sranges
  18680. : snegs;
  18681. return [comb, uflag, endPos - pos, true];
  18682. };
  18683. /**
  18684. * Un-escape a string that has been escaped with {@link escape}.
  18685. *
  18686. * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
  18687. * square-bracket escapes are removed, but not backslash escapes.
  18688. *
  18689. * For example, it will turn the string `'[*]'` into `*`, but it will not
  18690. * turn `'\\*'` into `'*'`, because `\` is a path separator in
  18691. * `windowsPathsNoEscape` mode.
  18692. *
  18693. * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
  18694. * backslash escapes are removed.
  18695. *
  18696. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  18697. * or unescaped.
  18698. *
  18699. * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
  18700. * unescaped.
  18701. */
  18702. const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
  18703. if (magicalBraces) {
  18704. return windowsPathsNoEscape ?
  18705. s.replace(/\[([^/\\])\]/g, '$1')
  18706. : s
  18707. .replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
  18708. .replace(/\\([^/])/g, '$1');
  18709. }
  18710. return windowsPathsNoEscape ?
  18711. s.replace(/\[([^/\\{}])\]/g, '$1')
  18712. : s
  18713. .replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
  18714. .replace(/\\([^/{}])/g, '$1');
  18715. };
  18716. // parse a single path portion
  18717. var _a;
  18718. const types = new Set(['!', '?', '+', '*', '@']);
  18719. const isExtglobType = (c) => types.has(c);
  18720. const isExtglobAST = (c) => isExtglobType(c.type);
  18721. // Map of which extglob types can adopt the children of a nested extglob
  18722. //
  18723. // anything but ! can adopt a matching type:
  18724. // +(a|+(b|c)|d) => +(a|b|c|d)
  18725. // *(a|*(b|c)|d) => *(a|b|c|d)
  18726. // @(a|@(b|c)|d) => @(a|b|c|d)
  18727. // ?(a|?(b|c)|d) => ?(a|b|c|d)
  18728. //
  18729. // * can adopt anything, because 0 or repetition is allowed
  18730. // *(a|?(b|c)|d) => *(a|b|c|d)
  18731. // *(a|+(b|c)|d) => *(a|b|c|d)
  18732. // *(a|@(b|c)|d) => *(a|b|c|d)
  18733. //
  18734. // + can adopt @, because 1 or repetition is allowed
  18735. // +(a|@(b|c)|d) => +(a|b|c|d)
  18736. //
  18737. // + and @ CANNOT adopt *, because 0 would be allowed
  18738. // +(a|*(b|c)|d) => would match "", on *(b|c)
  18739. // @(a|*(b|c)|d) => would match "", on *(b|c)
  18740. //
  18741. // + and @ CANNOT adopt ?, because 0 would be allowed
  18742. // +(a|?(b|c)|d) => would match "", on ?(b|c)
  18743. // @(a|?(b|c)|d) => would match "", on ?(b|c)
  18744. //
  18745. // ? can adopt @, because 0 or 1 is allowed
  18746. // ?(a|@(b|c)|d) => ?(a|b|c|d)
  18747. //
  18748. // ? and @ CANNOT adopt * or +, because >1 would be allowed
  18749. // ?(a|*(b|c)|d) => would match bbb on *(b|c)
  18750. // @(a|*(b|c)|d) => would match bbb on *(b|c)
  18751. // ?(a|+(b|c)|d) => would match bbb on +(b|c)
  18752. // @(a|+(b|c)|d) => would match bbb on +(b|c)
  18753. //
  18754. // ! CANNOT adopt ! (nothing else can either)
  18755. // !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
  18756. //
  18757. // ! can adopt @
  18758. // !(a|@(b|c)|d) => !(a|b|c|d)
  18759. //
  18760. // ! CANNOT adopt *
  18761. // !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  18762. //
  18763. // ! CANNOT adopt +
  18764. // !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  18765. //
  18766. // ! CANNOT adopt ?
  18767. // x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
  18768. const adoptionMap = new Map([
  18769. ['!', ['@']],
  18770. ['?', ['?', '@']],
  18771. ['@', ['@']],
  18772. ['*', ['*', '+', '?', '@']],
  18773. ['+', ['+', '@']],
  18774. ]);
  18775. // nested extglobs that can be adopted in, but with the addition of
  18776. // a blank '' element.
  18777. const adoptionWithSpaceMap = new Map([
  18778. ['!', ['?']],
  18779. ['@', ['?']],
  18780. ['+', ['?', '*']],
  18781. ]);
  18782. // union of the previous two maps
  18783. const adoptionAnyMap = new Map([
  18784. ['!', ['?', '@']],
  18785. ['?', ['?', '@']],
  18786. ['@', ['?', '@']],
  18787. ['*', ['*', '+', '?', '@']],
  18788. ['+', ['+', '@', '?', '*']],
  18789. ]);
  18790. // Extglobs that can take over their parent if they are the only child
  18791. // the key is parent, value maps child to resulting extglob parent type
  18792. // '@' is omitted because it's a special case. An `@` extglob with a single
  18793. // member can always be usurped by that subpattern.
  18794. const usurpMap = new Map([
  18795. ['!', new Map([['!', '@']])],
  18796. [
  18797. '?',
  18798. new Map([
  18799. ['*', '*'],
  18800. ['+', '*'],
  18801. ]),
  18802. ],
  18803. [
  18804. '@',
  18805. new Map([
  18806. ['!', '!'],
  18807. ['?', '?'],
  18808. ['@', '@'],
  18809. ['*', '*'],
  18810. ['+', '+'],
  18811. ]),
  18812. ],
  18813. [
  18814. '+',
  18815. new Map([
  18816. ['?', '*'],
  18817. ['*', '*'],
  18818. ]),
  18819. ],
  18820. ]);
  18821. // Patterns that get prepended to bind to the start of either the
  18822. // entire string, or just a single path portion, to prevent dots
  18823. // and/or traversal patterns, when needed.
  18824. // Exts don't need the ^ or / bit, because the root binds that already.
  18825. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  18826. const startNoDot = '(?!\\.)';
  18827. // characters that indicate a start of pattern needs the "no dots" bit,
  18828. // because a dot *might* be matched. ( is not in the list, because in
  18829. // the case of a child extglob, it will handle the prevention itself.
  18830. const addPatternStart = new Set(['[', '.']);
  18831. // cases where traversal is A-OK, no dot prevention needed
  18832. const justDots = new Set(['..', '.']);
  18833. const reSpecials = new Set('().*{}+?[]^$\\!');
  18834. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18835. // any single thing other than /
  18836. const qmark$1 = '[^/]';
  18837. // * => any number of characters
  18838. const star$1 = qmark$1 + '*?';
  18839. // use + when we need to ensure that *something* matches, because the * is
  18840. // the only thing in the path portion.
  18841. const starNoEmpty = qmark$1 + '+?';
  18842. // remove the \ chars that we added if we end up doing a nonmagic compare
  18843. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  18844. let ID = 0;
  18845. class AST {
  18846. type;
  18847. #root;
  18848. #hasMagic;
  18849. #uflag = false;
  18850. #parts = [];
  18851. #parent;
  18852. #parentIndex;
  18853. #negs;
  18854. #filledNegs = false;
  18855. #options;
  18856. #toString;
  18857. // set to true if it's an extglob with no children
  18858. // (which really means one child of '')
  18859. #emptyExt = false;
  18860. id = ++ID;
  18861. get depth() {
  18862. return (this.#parent?.depth ?? -1) + 1;
  18863. }
  18864. [Symbol.for('nodejs.util.inspect.custom')]() {
  18865. return {
  18866. '@@type': 'AST',
  18867. id: this.id,
  18868. type: this.type,
  18869. root: this.#root.id,
  18870. parent: this.#parent?.id,
  18871. depth: this.depth,
  18872. partsLength: this.#parts.length,
  18873. parts: this.#parts,
  18874. };
  18875. }
  18876. constructor(type, parent, options = {}) {
  18877. this.type = type;
  18878. // extglobs are inherently magical
  18879. if (type)
  18880. this.#hasMagic = true;
  18881. this.#parent = parent;
  18882. this.#root = this.#parent ? this.#parent.#root : this;
  18883. this.#options = this.#root === this ? options : this.#root.#options;
  18884. this.#negs = this.#root === this ? [] : this.#root.#negs;
  18885. if (type === '!' && !this.#root.#filledNegs)
  18886. this.#negs.push(this);
  18887. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  18888. }
  18889. get hasMagic() {
  18890. /* c8 ignore start */
  18891. if (this.#hasMagic !== undefined)
  18892. return this.#hasMagic;
  18893. /* c8 ignore stop */
  18894. for (const p of this.#parts) {
  18895. if (typeof p === 'string')
  18896. continue;
  18897. if (p.type || p.hasMagic)
  18898. return (this.#hasMagic = true);
  18899. }
  18900. // note: will be undefined until we generate the regexp src and find out
  18901. return this.#hasMagic;
  18902. }
  18903. // reconstructs the pattern
  18904. toString() {
  18905. return (this.#toString !== undefined ? this.#toString
  18906. : !this.type ?
  18907. (this.#toString = this.#parts.map(p => String(p)).join(''))
  18908. : (this.#toString =
  18909. this.type +
  18910. '(' +
  18911. this.#parts.map(p => String(p)).join('|') +
  18912. ')'));
  18913. }
  18914. #fillNegs() {
  18915. /* c8 ignore start */
  18916. if (this !== this.#root)
  18917. throw new Error('should only call on root');
  18918. if (this.#filledNegs)
  18919. return this;
  18920. /* c8 ignore stop */
  18921. // call toString() once to fill this out
  18922. this.toString();
  18923. this.#filledNegs = true;
  18924. let n;
  18925. while ((n = this.#negs.pop())) {
  18926. if (n.type !== '!')
  18927. continue;
  18928. // walk up the tree, appending everthing that comes AFTER parentIndex
  18929. let p = n;
  18930. let pp = p.#parent;
  18931. while (pp) {
  18932. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  18933. for (const part of n.#parts) {
  18934. /* c8 ignore start */
  18935. if (typeof part === 'string') {
  18936. throw new Error('string part in extglob AST??');
  18937. }
  18938. /* c8 ignore stop */
  18939. part.copyIn(pp.#parts[i]);
  18940. }
  18941. }
  18942. p = pp;
  18943. pp = p.#parent;
  18944. }
  18945. }
  18946. return this;
  18947. }
  18948. push(...parts) {
  18949. for (const p of parts) {
  18950. if (p === '')
  18951. continue;
  18952. /* c8 ignore start */
  18953. if (typeof p !== 'string' &&
  18954. !(p instanceof _a && p.#parent === this)) {
  18955. throw new Error('invalid part: ' + p);
  18956. }
  18957. /* c8 ignore stop */
  18958. this.#parts.push(p);
  18959. }
  18960. }
  18961. toJSON() {
  18962. const ret = this.type === null ?
  18963. this.#parts
  18964. .slice()
  18965. .map(p => (typeof p === 'string' ? p : p.toJSON()))
  18966. : [this.type, ...this.#parts.map(p => p.toJSON())];
  18967. if (this.isStart() && !this.type)
  18968. ret.unshift([]);
  18969. if (this.isEnd() &&
  18970. (this === this.#root ||
  18971. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  18972. ret.push({});
  18973. }
  18974. return ret;
  18975. }
  18976. isStart() {
  18977. if (this.#root === this)
  18978. return true;
  18979. // if (this.type) return !!this.#parent?.isStart()
  18980. if (!this.#parent?.isStart())
  18981. return false;
  18982. if (this.#parentIndex === 0)
  18983. return true;
  18984. // if everything AHEAD of this is a negation, then it's still the "start"
  18985. const p = this.#parent;
  18986. for (let i = 0; i < this.#parentIndex; i++) {
  18987. const pp = p.#parts[i];
  18988. if (!(pp instanceof _a && pp.type === '!')) {
  18989. return false;
  18990. }
  18991. }
  18992. return true;
  18993. }
  18994. isEnd() {
  18995. if (this.#root === this)
  18996. return true;
  18997. if (this.#parent?.type === '!')
  18998. return true;
  18999. if (!this.#parent?.isEnd())
  19000. return false;
  19001. if (!this.type)
  19002. return this.#parent?.isEnd();
  19003. // if not root, it'll always have a parent
  19004. /* c8 ignore start */
  19005. const pl = this.#parent ? this.#parent.#parts.length : 0;
  19006. /* c8 ignore stop */
  19007. return this.#parentIndex === pl - 1;
  19008. }
  19009. copyIn(part) {
  19010. if (typeof part === 'string')
  19011. this.push(part);
  19012. else
  19013. this.push(part.clone(this));
  19014. }
  19015. clone(parent) {
  19016. const c = new _a(this.type, parent);
  19017. for (const p of this.#parts) {
  19018. c.copyIn(p);
  19019. }
  19020. return c;
  19021. }
  19022. static #parseAST(str, ast, pos, opt, extDepth) {
  19023. const maxDepth = opt.maxExtglobRecursion ?? 2;
  19024. let escaping = false;
  19025. let inBrace = false;
  19026. let braceStart = -1;
  19027. let braceNeg = false;
  19028. if (ast.type === null) {
  19029. // outside of a extglob, append until we find a start
  19030. let i = pos;
  19031. let acc = '';
  19032. while (i < str.length) {
  19033. const c = str.charAt(i++);
  19034. // still accumulate escapes at this point, but we do ignore
  19035. // starts that are escaped
  19036. if (escaping || c === '\\') {
  19037. escaping = !escaping;
  19038. acc += c;
  19039. continue;
  19040. }
  19041. if (inBrace) {
  19042. if (i === braceStart + 1) {
  19043. if (c === '^' || c === '!') {
  19044. braceNeg = true;
  19045. }
  19046. }
  19047. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  19048. inBrace = false;
  19049. }
  19050. acc += c;
  19051. continue;
  19052. }
  19053. else if (c === '[') {
  19054. inBrace = true;
  19055. braceStart = i;
  19056. braceNeg = false;
  19057. acc += c;
  19058. continue;
  19059. }
  19060. // we don't have to check for adoption here, because that's
  19061. // done at the other recursion point.
  19062. const doRecurse = !opt.noext &&
  19063. isExtglobType(c) &&
  19064. str.charAt(i) === '(' &&
  19065. extDepth <= maxDepth;
  19066. if (doRecurse) {
  19067. ast.push(acc);
  19068. acc = '';
  19069. const ext = new _a(c, ast);
  19070. i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
  19071. ast.push(ext);
  19072. continue;
  19073. }
  19074. acc += c;
  19075. }
  19076. ast.push(acc);
  19077. return i;
  19078. }
  19079. // some kind of extglob, pos is at the (
  19080. // find the next | or )
  19081. let i = pos + 1;
  19082. let part = new _a(null, ast);
  19083. const parts = [];
  19084. let acc = '';
  19085. while (i < str.length) {
  19086. const c = str.charAt(i++);
  19087. // still accumulate escapes at this point, but we do ignore
  19088. // starts that are escaped
  19089. if (escaping || c === '\\') {
  19090. escaping = !escaping;
  19091. acc += c;
  19092. continue;
  19093. }
  19094. if (inBrace) {
  19095. if (i === braceStart + 1) {
  19096. if (c === '^' || c === '!') {
  19097. braceNeg = true;
  19098. }
  19099. }
  19100. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  19101. inBrace = false;
  19102. }
  19103. acc += c;
  19104. continue;
  19105. }
  19106. else if (c === '[') {
  19107. inBrace = true;
  19108. braceStart = i;
  19109. braceNeg = false;
  19110. acc += c;
  19111. continue;
  19112. }
  19113. const doRecurse = !opt.noext &&
  19114. isExtglobType(c) &&
  19115. str.charAt(i) === '(' &&
  19116. /* c8 ignore start - the maxDepth is sufficient here */
  19117. (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
  19118. /* c8 ignore stop */
  19119. if (doRecurse) {
  19120. const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
  19121. part.push(acc);
  19122. acc = '';
  19123. const ext = new _a(c, part);
  19124. part.push(ext);
  19125. i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
  19126. continue;
  19127. }
  19128. if (c === '|') {
  19129. part.push(acc);
  19130. acc = '';
  19131. parts.push(part);
  19132. part = new _a(null, ast);
  19133. continue;
  19134. }
  19135. if (c === ')') {
  19136. if (acc === '' && ast.#parts.length === 0) {
  19137. ast.#emptyExt = true;
  19138. }
  19139. part.push(acc);
  19140. acc = '';
  19141. ast.push(...parts, part);
  19142. return i;
  19143. }
  19144. acc += c;
  19145. }
  19146. // unfinished extglob
  19147. // if we got here, it was a malformed extglob! not an extglob, but
  19148. // maybe something else in there.
  19149. ast.type = null;
  19150. ast.#hasMagic = undefined;
  19151. ast.#parts = [str.substring(pos - 1)];
  19152. return i;
  19153. }
  19154. #canAdoptWithSpace(child) {
  19155. return this.#canAdopt(child, adoptionWithSpaceMap);
  19156. }
  19157. #canAdopt(child, map = adoptionMap) {
  19158. if (!child ||
  19159. typeof child !== 'object' ||
  19160. child.type !== null ||
  19161. child.#parts.length !== 1 ||
  19162. this.type === null) {
  19163. return false;
  19164. }
  19165. const gc = child.#parts[0];
  19166. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19167. return false;
  19168. }
  19169. return this.#canAdoptType(gc.type, map);
  19170. }
  19171. #canAdoptType(c, map = adoptionAnyMap) {
  19172. return !!map.get(this.type)?.includes(c);
  19173. }
  19174. #adoptWithSpace(child, index) {
  19175. const gc = child.#parts[0];
  19176. const blank = new _a(null, gc, this.options);
  19177. blank.#parts.push('');
  19178. gc.push(blank);
  19179. this.#adopt(child, index);
  19180. }
  19181. #adopt(child, index) {
  19182. const gc = child.#parts[0];
  19183. this.#parts.splice(index, 1, ...gc.#parts);
  19184. for (const p of gc.#parts) {
  19185. if (typeof p === 'object')
  19186. p.#parent = this;
  19187. }
  19188. this.#toString = undefined;
  19189. }
  19190. #canUsurpType(c) {
  19191. const m = usurpMap.get(this.type);
  19192. return !!m?.has(c);
  19193. }
  19194. #canUsurp(child) {
  19195. if (!child ||
  19196. typeof child !== 'object' ||
  19197. child.type !== null ||
  19198. child.#parts.length !== 1 ||
  19199. this.type === null ||
  19200. this.#parts.length !== 1) {
  19201. return false;
  19202. }
  19203. const gc = child.#parts[0];
  19204. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19205. return false;
  19206. }
  19207. return this.#canUsurpType(gc.type);
  19208. }
  19209. #usurp(child) {
  19210. const m = usurpMap.get(this.type);
  19211. const gc = child.#parts[0];
  19212. const nt = m?.get(gc.type);
  19213. /* c8 ignore start - impossible */
  19214. if (!nt)
  19215. return false;
  19216. /* c8 ignore stop */
  19217. this.#parts = gc.#parts;
  19218. for (const p of this.#parts) {
  19219. if (typeof p === 'object') {
  19220. p.#parent = this;
  19221. }
  19222. }
  19223. this.type = nt;
  19224. this.#toString = undefined;
  19225. this.#emptyExt = false;
  19226. }
  19227. static fromGlob(pattern, options = {}) {
  19228. const ast = new _a(null, undefined, options);
  19229. _a.#parseAST(pattern, ast, 0, options, 0);
  19230. return ast;
  19231. }
  19232. // returns the regular expression if there's magic, or the unescaped
  19233. // string if not.
  19234. toMMPattern() {
  19235. // should only be called on root
  19236. /* c8 ignore start */
  19237. if (this !== this.#root)
  19238. return this.#root.toMMPattern();
  19239. /* c8 ignore stop */
  19240. const glob = this.toString();
  19241. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  19242. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  19243. // still need a regular expression if we have to case-insensitively
  19244. // match capital/lowercase characters.
  19245. const anyMagic = hasMagic ||
  19246. this.#hasMagic ||
  19247. (this.#options.nocase &&
  19248. !this.#options.nocaseMagicOnly &&
  19249. glob.toUpperCase() !== glob.toLowerCase());
  19250. if (!anyMagic) {
  19251. return body;
  19252. }
  19253. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  19254. return Object.assign(new RegExp(`^${re}$`, flags), {
  19255. _src: re,
  19256. _glob: glob,
  19257. });
  19258. }
  19259. get options() {
  19260. return this.#options;
  19261. }
  19262. // returns the string match, the regexp source, whether there's magic
  19263. // in the regexp (so a regular expression is required) and whether or
  19264. // not the uflag is needed for the regular expression (for posix classes)
  19265. // TODO: instead of injecting the start/end at this point, just return
  19266. // the BODY of the regexp, along with the start/end portions suitable
  19267. // for binding the start/end in either a joined full-path makeRe context
  19268. // (where we bind to (^|/), or a standalone matchPart context (where
  19269. // we bind to ^, and not /). Otherwise slashes get duped!
  19270. //
  19271. // In part-matching mode, the start is:
  19272. // - if not isStart: nothing
  19273. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  19274. // - if dots allowed or not possible: ^
  19275. // - if dots possible and not allowed: ^(?!\.)
  19276. // end is:
  19277. // - if not isEnd(): nothing
  19278. // - else: $
  19279. //
  19280. // In full-path matching mode, we put the slash at the START of the
  19281. // pattern, so start is:
  19282. // - if first pattern: same as part-matching mode
  19283. // - if not isStart(): nothing
  19284. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  19285. // - if dots allowed or not possible: /
  19286. // - if dots possible and not allowed: /(?!\.)
  19287. // end is:
  19288. // - if last pattern, same as part-matching mode
  19289. // - else nothing
  19290. //
  19291. // Always put the (?:$|/) on negated tails, though, because that has to be
  19292. // there to bind the end of the negated pattern portion, and it's easier to
  19293. // just stick it in now rather than try to inject it later in the middle of
  19294. // the pattern.
  19295. //
  19296. // We can just always return the same end, and leave it up to the caller
  19297. // to know whether it's going to be used joined or in parts.
  19298. // And, if the start is adjusted slightly, can do the same there:
  19299. // - if not isStart: nothing
  19300. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  19301. // - if dots allowed or not possible: (?:/|^)
  19302. // - if dots possible and not allowed: (?:/|^)(?!\.)
  19303. //
  19304. // But it's better to have a simpler binding without a conditional, for
  19305. // performance, so probably better to return both start options.
  19306. //
  19307. // Then the caller just ignores the end if it's not the first pattern,
  19308. // and the start always gets applied.
  19309. //
  19310. // But that's always going to be $ if it's the ending pattern, or nothing,
  19311. // so the caller can just attach $ at the end of the pattern when building.
  19312. //
  19313. // So the todo is:
  19314. // - better detect what kind of start is needed
  19315. // - return both flavors of starting pattern
  19316. // - attach $ at the end of the pattern when creating the actual RegExp
  19317. //
  19318. // Ah, but wait, no, that all only applies to the root when the first pattern
  19319. // is not an extglob. If the first pattern IS an extglob, then we need all
  19320. // that dot prevention biz to live in the extglob portions, because eg
  19321. // +(*|.x*) can match .xy but not .yx.
  19322. //
  19323. // So, return the two flavors if it's #root and the first child is not an
  19324. // AST, otherwise leave it to the child AST to handle it, and there,
  19325. // use the (?:^|/) style of start binding.
  19326. //
  19327. // Even simplified further:
  19328. // - Since the start for a join is eg /(?!\.) and the start for a part
  19329. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  19330. // or start or whatever) and prepend ^ or / at the Regexp construction.
  19331. toRegExpSource(allowDot) {
  19332. const dot = allowDot ?? !!this.#options.dot;
  19333. if (this.#root === this) {
  19334. this.#flatten();
  19335. this.#fillNegs();
  19336. }
  19337. if (!isExtglobAST(this)) {
  19338. const noEmpty = this.isStart() &&
  19339. this.isEnd() &&
  19340. !this.#parts.some(s => typeof s !== 'string');
  19341. const src = this.#parts
  19342. .map(p => {
  19343. const [re, _, hasMagic, uflag] = typeof p === 'string' ?
  19344. _a.#parseGlob(p, this.#hasMagic, noEmpty)
  19345. : p.toRegExpSource(allowDot);
  19346. this.#hasMagic = this.#hasMagic || hasMagic;
  19347. this.#uflag = this.#uflag || uflag;
  19348. return re;
  19349. })
  19350. .join('');
  19351. let start = '';
  19352. if (this.isStart()) {
  19353. if (typeof this.#parts[0] === 'string') {
  19354. // this is the string that will match the start of the pattern,
  19355. // so we need to protect against dots and such.
  19356. // '.' and '..' cannot match unless the pattern is that exactly,
  19357. // even if it starts with . or dot:true is set.
  19358. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  19359. if (!dotTravAllowed) {
  19360. const aps = addPatternStart;
  19361. // check if we have a possibility of matching . or ..,
  19362. // and prevent that.
  19363. const needNoTrav =
  19364. // dots are allowed, and the pattern starts with [ or .
  19365. (dot && aps.has(src.charAt(0))) ||
  19366. // the pattern starts with \., and then [ or .
  19367. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  19368. // the pattern starts with \.\., and then [ or .
  19369. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  19370. // no need to prevent dots if it can't match a dot, or if a
  19371. // sub-pattern will be preventing it anyway.
  19372. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  19373. start =
  19374. needNoTrav ? startNoTraversal
  19375. : needNoDot ? startNoDot
  19376. : '';
  19377. }
  19378. }
  19379. }
  19380. // append the "end of path portion" pattern to negation tails
  19381. let end = '';
  19382. if (this.isEnd() &&
  19383. this.#root.#filledNegs &&
  19384. this.#parent?.type === '!') {
  19385. end = '(?:$|\\/)';
  19386. }
  19387. const final = start + src + end;
  19388. return [
  19389. final,
  19390. unescape(src),
  19391. (this.#hasMagic = !!this.#hasMagic),
  19392. this.#uflag,
  19393. ];
  19394. }
  19395. // We need to calculate the body *twice* if it's a repeat pattern
  19396. // at the start, once in nodot mode, then again in dot mode, so a
  19397. // pattern like *(?) can match 'x.y'
  19398. const repeated = this.type === '*' || this.type === '+';
  19399. // some kind of extglob
  19400. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  19401. let body = this.#partsToRegExp(dot);
  19402. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  19403. // invalid extglob, has to at least be *something* present, if it's
  19404. // the entire path portion.
  19405. const s = this.toString();
  19406. const me = this;
  19407. me.#parts = [s];
  19408. me.type = null;
  19409. me.#hasMagic = undefined;
  19410. return [s, unescape(this.toString()), false, false];
  19411. }
  19412. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
  19413. ''
  19414. : this.#partsToRegExp(true);
  19415. if (bodyDotAllowed === body) {
  19416. bodyDotAllowed = '';
  19417. }
  19418. if (bodyDotAllowed) {
  19419. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  19420. }
  19421. // an empty !() is exactly equivalent to a starNoEmpty
  19422. let final = '';
  19423. if (this.type === '!' && this.#emptyExt) {
  19424. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  19425. }
  19426. else {
  19427. const close = this.type === '!' ?
  19428. // !() must match something,but !(x) can match ''
  19429. '))' +
  19430. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  19431. star$1 +
  19432. ')'
  19433. : this.type === '@' ? ')'
  19434. : this.type === '?' ? ')?'
  19435. : this.type === '+' && bodyDotAllowed ? ')'
  19436. : this.type === '*' && bodyDotAllowed ? `)?`
  19437. : `)${this.type}`;
  19438. final = start + body + close;
  19439. }
  19440. return [
  19441. final,
  19442. unescape(body),
  19443. (this.#hasMagic = !!this.#hasMagic),
  19444. this.#uflag,
  19445. ];
  19446. }
  19447. #flatten() {
  19448. if (!isExtglobAST(this)) {
  19449. for (const p of this.#parts) {
  19450. if (typeof p === 'object') {
  19451. p.#flatten();
  19452. }
  19453. }
  19454. }
  19455. else {
  19456. // do up to 10 passes to flatten as much as possible
  19457. let iterations = 0;
  19458. let done = false;
  19459. do {
  19460. done = true;
  19461. for (let i = 0; i < this.#parts.length; i++) {
  19462. const c = this.#parts[i];
  19463. if (typeof c === 'object') {
  19464. c.#flatten();
  19465. if (this.#canAdopt(c)) {
  19466. done = false;
  19467. this.#adopt(c, i);
  19468. }
  19469. else if (this.#canAdoptWithSpace(c)) {
  19470. done = false;
  19471. this.#adoptWithSpace(c, i);
  19472. }
  19473. else if (this.#canUsurp(c)) {
  19474. done = false;
  19475. this.#usurp(c);
  19476. }
  19477. }
  19478. }
  19479. } while (!done && ++iterations < 10);
  19480. }
  19481. this.#toString = undefined;
  19482. }
  19483. #partsToRegExp(dot) {
  19484. return this.#parts
  19485. .map(p => {
  19486. // extglob ASTs should only contain parent ASTs
  19487. /* c8 ignore start */
  19488. if (typeof p === 'string') {
  19489. throw new Error('string type in extglob ast??');
  19490. }
  19491. /* c8 ignore stop */
  19492. // can ignore hasMagic, because extglobs are already always magic
  19493. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  19494. this.#uflag = this.#uflag || uflag;
  19495. return re;
  19496. })
  19497. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  19498. .join('|');
  19499. }
  19500. static #parseGlob(glob, hasMagic, noEmpty = false) {
  19501. let escaping = false;
  19502. let re = '';
  19503. let uflag = false;
  19504. // multiple stars that aren't globstars coalesce into one *
  19505. let inStar = false;
  19506. for (let i = 0; i < glob.length; i++) {
  19507. const c = glob.charAt(i);
  19508. if (escaping) {
  19509. escaping = false;
  19510. re += (reSpecials.has(c) ? '\\' : '') + c;
  19511. continue;
  19512. }
  19513. if (c === '*') {
  19514. if (inStar)
  19515. continue;
  19516. inStar = true;
  19517. re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star$1;
  19518. hasMagic = true;
  19519. continue;
  19520. }
  19521. else {
  19522. inStar = false;
  19523. }
  19524. if (c === '\\') {
  19525. if (i === glob.length - 1) {
  19526. re += '\\\\';
  19527. }
  19528. else {
  19529. escaping = true;
  19530. }
  19531. continue;
  19532. }
  19533. if (c === '[') {
  19534. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  19535. if (consumed) {
  19536. re += src;
  19537. uflag = uflag || needUflag;
  19538. i += consumed - 1;
  19539. hasMagic = hasMagic || magic;
  19540. continue;
  19541. }
  19542. }
  19543. if (c === '?') {
  19544. re += qmark$1;
  19545. hasMagic = true;
  19546. continue;
  19547. }
  19548. re += regExpEscape$1(c);
  19549. }
  19550. return [re, unescape(glob), !!hasMagic, uflag];
  19551. }
  19552. }
  19553. _a = AST;
  19554. /**
  19555. * Escape all magic characters in a glob pattern.
  19556. *
  19557. * If the {@link MinimatchOptions.windowsPathsNoEscape}
  19558. * option is used, then characters are escaped by wrapping in `[]`, because
  19559. * a magic character wrapped in a character class can only be satisfied by
  19560. * that exact character. In this mode, `\` is _not_ escaped, because it is
  19561. * not interpreted as a magic character, but instead as a path separator.
  19562. *
  19563. * If the {@link MinimatchOptions.magicalBraces} option is used,
  19564. * then braces (`{` and `}`) will be escaped.
  19565. */
  19566. const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
  19567. // don't need to escape +@! because we escape the parens
  19568. // that make those magic, and escaping ! as [!] isn't valid,
  19569. // because [!]] is a valid glob class meaning not ']'.
  19570. if (magicalBraces) {
  19571. return windowsPathsNoEscape ?
  19572. s.replace(/[?*()[\]{}]/g, '[$&]')
  19573. : s.replace(/[?*()[\]\\{}]/g, '\\$&');
  19574. }
  19575. return windowsPathsNoEscape ?
  19576. s.replace(/[?*()[\]]/g, '[$&]')
  19577. : s.replace(/[?*()[\]\\]/g, '\\$&');
  19578. };
  19579. const minimatch = (p, pattern, options = {}) => {
  19580. assertValidPattern(pattern);
  19581. // shortcut: comments match nothing.
  19582. if (!options.nocomment && pattern.charAt(0) === '#') {
  19583. return false;
  19584. }
  19585. return new Minimatch(pattern, options).match(p);
  19586. };
  19587. // Optimized checking for the most common glob patterns.
  19588. const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
  19589. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  19590. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  19591. const starDotExtTestNocase = (ext) => {
  19592. ext = ext.toLowerCase();
  19593. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  19594. };
  19595. const starDotExtTestNocaseDot = (ext) => {
  19596. ext = ext.toLowerCase();
  19597. return (f) => f.toLowerCase().endsWith(ext);
  19598. };
  19599. const starDotStarRE = /^\*+\.\*+$/;
  19600. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  19601. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  19602. const dotStarRE = /^\.\*+$/;
  19603. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  19604. const starRE = /^\*+$/;
  19605. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  19606. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  19607. const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
  19608. const qmarksTestNocase = ([$0, ext = '']) => {
  19609. const noext = qmarksTestNoExt([$0]);
  19610. if (!ext)
  19611. return noext;
  19612. ext = ext.toLowerCase();
  19613. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19614. };
  19615. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  19616. const noext = qmarksTestNoExtDot([$0]);
  19617. if (!ext)
  19618. return noext;
  19619. ext = ext.toLowerCase();
  19620. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19621. };
  19622. const qmarksTestDot = ([$0, ext = '']) => {
  19623. const noext = qmarksTestNoExtDot([$0]);
  19624. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19625. };
  19626. const qmarksTest = ([$0, ext = '']) => {
  19627. const noext = qmarksTestNoExt([$0]);
  19628. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19629. };
  19630. const qmarksTestNoExt = ([$0]) => {
  19631. const len = $0.length;
  19632. return (f) => f.length === len && !f.startsWith('.');
  19633. };
  19634. const qmarksTestNoExtDot = ([$0]) => {
  19635. const len = $0.length;
  19636. return (f) => f.length === len && f !== '.' && f !== '..';
  19637. };
  19638. /* c8 ignore start */
  19639. const defaultPlatform = (typeof process === 'object' && process ?
  19640. (typeof process.env === 'object' &&
  19641. process.env &&
  19642. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  19643. process.platform
  19644. : 'posix');
  19645. const path = {
  19646. win32: { sep: '\\' },
  19647. posix: { sep: '/' },
  19648. };
  19649. /* c8 ignore stop */
  19650. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  19651. minimatch.sep = sep;
  19652. const GLOBSTAR = Symbol('globstar **');
  19653. minimatch.GLOBSTAR = GLOBSTAR;
  19654. // any single thing other than /
  19655. // don't need to escape / when using new RegExp()
  19656. const qmark = '[^/]';
  19657. // * => any number of characters
  19658. const star = qmark + '*?';
  19659. // ** when dots are allowed. Anything goes, except .. and .
  19660. // not (^ or / followed by one or two dots followed by $ or /),
  19661. // followed by anything, any number of times.
  19662. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  19663. // not a ^ or / followed by a dot,
  19664. // followed by anything, any number of times.
  19665. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  19666. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  19667. minimatch.filter = filter;
  19668. const ext = (a, b = {}) => Object.assign({}, a, b);
  19669. const defaults = (def) => {
  19670. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  19671. return minimatch;
  19672. }
  19673. const orig = minimatch;
  19674. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  19675. return Object.assign(m, {
  19676. Minimatch: class Minimatch extends orig.Minimatch {
  19677. constructor(pattern, options = {}) {
  19678. super(pattern, ext(def, options));
  19679. }
  19680. static defaults(options) {
  19681. return orig.defaults(ext(def, options)).Minimatch;
  19682. }
  19683. },
  19684. AST: class AST extends orig.AST {
  19685. /* c8 ignore start */
  19686. constructor(type, parent, options = {}) {
  19687. super(type, parent, ext(def, options));
  19688. }
  19689. /* c8 ignore stop */
  19690. static fromGlob(pattern, options = {}) {
  19691. return orig.AST.fromGlob(pattern, ext(def, options));
  19692. }
  19693. },
  19694. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  19695. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  19696. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  19697. defaults: (options) => orig.defaults(ext(def, options)),
  19698. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  19699. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  19700. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  19701. sep: orig.sep,
  19702. GLOBSTAR: GLOBSTAR,
  19703. });
  19704. };
  19705. minimatch.defaults = defaults;
  19706. // Brace expansion:
  19707. // a{b,c}d -> abd acd
  19708. // a{b,}c -> abc ac
  19709. // a{0..3}d -> a0d a1d a2d a3d
  19710. // a{b,c{d,e}f}g -> abg acdfg acefg
  19711. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19712. //
  19713. // Invalid sets are not expanded.
  19714. // a{2..}b -> a{2..}b
  19715. // a{b}c -> a{b}c
  19716. const braceExpand = (pattern, options = {}) => {
  19717. assertValidPattern(pattern);
  19718. // Thanks to Yeting Li <https://github.com/yetingli> for
  19719. // improving this regexp to avoid a ReDOS vulnerability.
  19720. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  19721. // shortcut. no need to expand.
  19722. return [pattern];
  19723. }
  19724. return expand(pattern, { max: options.braceExpandMax });
  19725. };
  19726. minimatch.braceExpand = braceExpand;
  19727. // parse a component of the expanded set.
  19728. // At this point, no pattern may contain "/" in it
  19729. // so we're going to return a 2d array, where each entry is the full
  19730. // pattern, split on '/', and then turned into a regular expression.
  19731. // A regexp is made at the end which joins each array with an
  19732. // escaped /, and another full one which joins each regexp with |.
  19733. //
  19734. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19735. // when it is the *only* thing in a path portion. Otherwise, any series
  19736. // of * is equivalent to a single *. Globstar behavior is enabled by
  19737. // default, and can be disabled by setting options.noglobstar.
  19738. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  19739. minimatch.makeRe = makeRe;
  19740. const match = (list, pattern, options = {}) => {
  19741. const mm = new Minimatch(pattern, options);
  19742. list = list.filter(f => mm.match(f));
  19743. if (mm.options.nonull && !list.length) {
  19744. list.push(pattern);
  19745. }
  19746. return list;
  19747. };
  19748. minimatch.match = match;
  19749. // replace stuff like \* with *
  19750. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  19751. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19752. class Minimatch {
  19753. options;
  19754. set;
  19755. pattern;
  19756. windowsPathsNoEscape;
  19757. nonegate;
  19758. negate;
  19759. comment;
  19760. empty;
  19761. preserveMultipleSlashes;
  19762. partial;
  19763. globSet;
  19764. globParts;
  19765. nocase;
  19766. isWindows;
  19767. platform;
  19768. windowsNoMagicRoot;
  19769. maxGlobstarRecursion;
  19770. regexp;
  19771. constructor(pattern, options = {}) {
  19772. assertValidPattern(pattern);
  19773. options = options || {};
  19774. this.options = options;
  19775. this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
  19776. this.pattern = pattern;
  19777. this.platform = options.platform || defaultPlatform;
  19778. this.isWindows = this.platform === 'win32';
  19779. // avoid the annoying deprecation flag lol
  19780. const awe = ('allowWindow' + 'sEscape');
  19781. this.windowsPathsNoEscape =
  19782. !!options.windowsPathsNoEscape || options[awe] === false;
  19783. if (this.windowsPathsNoEscape) {
  19784. this.pattern = this.pattern.replace(/\\/g, '/');
  19785. }
  19786. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  19787. this.regexp = null;
  19788. this.negate = false;
  19789. this.nonegate = !!options.nonegate;
  19790. this.comment = false;
  19791. this.empty = false;
  19792. this.partial = !!options.partial;
  19793. this.nocase = !!this.options.nocase;
  19794. this.windowsNoMagicRoot =
  19795. options.windowsNoMagicRoot !== undefined ?
  19796. options.windowsNoMagicRoot
  19797. : !!(this.isWindows && this.nocase);
  19798. this.globSet = [];
  19799. this.globParts = [];
  19800. this.set = [];
  19801. // make the set of regexps etc.
  19802. this.make();
  19803. }
  19804. hasMagic() {
  19805. if (this.options.magicalBraces && this.set.length > 1) {
  19806. return true;
  19807. }
  19808. for (const pattern of this.set) {
  19809. for (const part of pattern) {
  19810. if (typeof part !== 'string')
  19811. return true;
  19812. }
  19813. }
  19814. return false;
  19815. }
  19816. debug(..._) { }
  19817. make() {
  19818. const pattern = this.pattern;
  19819. const options = this.options;
  19820. // empty patterns and comments match nothing.
  19821. if (!options.nocomment && pattern.charAt(0) === '#') {
  19822. this.comment = true;
  19823. return;
  19824. }
  19825. if (!pattern) {
  19826. this.empty = true;
  19827. return;
  19828. }
  19829. // step 1: figure out negation, etc.
  19830. this.parseNegate();
  19831. // step 2: expand braces
  19832. this.globSet = [...new Set(this.braceExpand())];
  19833. if (options.debug) {
  19834. //oxlint-disable-next-line no-console
  19835. this.debug = (...args) => console.error(...args);
  19836. }
  19837. this.debug(this.pattern, this.globSet);
  19838. // step 3: now we have a set, so turn each one into a series of
  19839. // path-portion matching patterns.
  19840. // These will be regexps, except in the case of "**", which is
  19841. // set to the GLOBSTAR object for globstar behavior,
  19842. // and will not contain any / characters
  19843. //
  19844. // First, we preprocess to make the glob pattern sets a bit simpler
  19845. // and deduped. There are some perf-killing patterns that can cause
  19846. // problems with a glob walk, but we can simplify them down a bit.
  19847. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  19848. this.globParts = this.preprocess(rawGlobParts);
  19849. this.debug(this.pattern, this.globParts);
  19850. // glob --> regexps
  19851. let set = this.globParts.map((s, _, __) => {
  19852. if (this.isWindows && this.windowsNoMagicRoot) {
  19853. // check if it's a drive or unc path.
  19854. const isUNC = s[0] === '' &&
  19855. s[1] === '' &&
  19856. (s[2] === '?' || !globMagic.test(s[2])) &&
  19857. !globMagic.test(s[3]);
  19858. const isDrive = /^[a-z]:/i.test(s[0]);
  19859. if (isUNC) {
  19860. return [
  19861. ...s.slice(0, 4),
  19862. ...s.slice(4).map(ss => this.parse(ss)),
  19863. ];
  19864. }
  19865. else if (isDrive) {
  19866. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  19867. }
  19868. }
  19869. return s.map(ss => this.parse(ss));
  19870. });
  19871. this.debug(this.pattern, set);
  19872. // filter out everything that didn't compile properly.
  19873. this.set = set.filter(s => s.indexOf(false) === -1);
  19874. // do not treat the ? in UNC paths as magic
  19875. if (this.isWindows) {
  19876. for (let i = 0; i < this.set.length; i++) {
  19877. const p = this.set[i];
  19878. if (p[0] === '' &&
  19879. p[1] === '' &&
  19880. this.globParts[i][2] === '?' &&
  19881. typeof p[3] === 'string' &&
  19882. /^[a-z]:$/i.test(p[3])) {
  19883. p[2] = '?';
  19884. }
  19885. }
  19886. }
  19887. this.debug(this.pattern, this.set);
  19888. }
  19889. // various transforms to equivalent pattern sets that are
  19890. // faster to process in a filesystem walk. The goal is to
  19891. // eliminate what we can, and push all ** patterns as far
  19892. // to the right as possible, even if it increases the number
  19893. // of patterns that we have to process.
  19894. preprocess(globParts) {
  19895. // if we're not in globstar mode, then turn ** into *
  19896. if (this.options.noglobstar) {
  19897. for (const partset of globParts) {
  19898. for (let j = 0; j < partset.length; j++) {
  19899. if (partset[j] === '**') {
  19900. partset[j] = '*';
  19901. }
  19902. }
  19903. }
  19904. }
  19905. const { optimizationLevel = 1 } = this.options;
  19906. if (optimizationLevel >= 2) {
  19907. // aggressive optimization for the purpose of fs walking
  19908. globParts = this.firstPhasePreProcess(globParts);
  19909. globParts = this.secondPhasePreProcess(globParts);
  19910. }
  19911. else if (optimizationLevel >= 1) {
  19912. // just basic optimizations to remove some .. parts
  19913. globParts = this.levelOneOptimize(globParts);
  19914. }
  19915. else {
  19916. // just collapse multiple ** portions into one
  19917. globParts = this.adjascentGlobstarOptimize(globParts);
  19918. }
  19919. return globParts;
  19920. }
  19921. // just get rid of adjascent ** portions
  19922. adjascentGlobstarOptimize(globParts) {
  19923. return globParts.map(parts => {
  19924. let gs = -1;
  19925. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19926. let i = gs;
  19927. while (parts[i + 1] === '**') {
  19928. i++;
  19929. }
  19930. if (i !== gs) {
  19931. parts.splice(gs, i - gs);
  19932. }
  19933. }
  19934. return parts;
  19935. });
  19936. }
  19937. // get rid of adjascent ** and resolve .. portions
  19938. levelOneOptimize(globParts) {
  19939. return globParts.map(parts => {
  19940. parts = parts.reduce((set, part) => {
  19941. const prev = set[set.length - 1];
  19942. if (part === '**' && prev === '**') {
  19943. return set;
  19944. }
  19945. if (part === '..') {
  19946. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  19947. set.pop();
  19948. return set;
  19949. }
  19950. }
  19951. set.push(part);
  19952. return set;
  19953. }, []);
  19954. return parts.length === 0 ? [''] : parts;
  19955. });
  19956. }
  19957. levelTwoFileOptimize(parts) {
  19958. if (!Array.isArray(parts)) {
  19959. parts = this.slashSplit(parts);
  19960. }
  19961. let didSomething = false;
  19962. do {
  19963. didSomething = false;
  19964. // <pre>/<e>/<rest> -> <pre>/<rest>
  19965. if (!this.preserveMultipleSlashes) {
  19966. for (let i = 1; i < parts.length - 1; i++) {
  19967. const p = parts[i];
  19968. // don't squeeze out UNC patterns
  19969. if (i === 1 && p === '' && parts[0] === '')
  19970. continue;
  19971. if (p === '.' || p === '') {
  19972. didSomething = true;
  19973. parts.splice(i, 1);
  19974. i--;
  19975. }
  19976. }
  19977. if (parts[0] === '.' &&
  19978. parts.length === 2 &&
  19979. (parts[1] === '.' || parts[1] === '')) {
  19980. didSomething = true;
  19981. parts.pop();
  19982. }
  19983. }
  19984. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19985. let dd = 0;
  19986. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19987. const p = parts[dd - 1];
  19988. if (p &&
  19989. p !== '.' &&
  19990. p !== '..' &&
  19991. p !== '**' &&
  19992. !(this.isWindows && /^[a-z]:$/i.test(p))) {
  19993. didSomething = true;
  19994. parts.splice(dd - 1, 2);
  19995. dd -= 2;
  19996. }
  19997. }
  19998. } while (didSomething);
  19999. return parts.length === 0 ? [''] : parts;
  20000. }
  20001. // First phase: single-pattern processing
  20002. // <pre> is 1 or more portions
  20003. // <rest> is 1 or more portions
  20004. // <p> is any portion other than ., .., '', or **
  20005. // <e> is . or ''
  20006. //
  20007. // **/.. is *brutal* for filesystem walking performance, because
  20008. // it effectively resets the recursive walk each time it occurs,
  20009. // and ** cannot be reduced out by a .. pattern part like a regexp
  20010. // or most strings (other than .., ., and '') can be.
  20011. //
  20012. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  20013. // <pre>/<e>/<rest> -> <pre>/<rest>
  20014. // <pre>/<p>/../<rest> -> <pre>/<rest>
  20015. // **/**/<rest> -> **/<rest>
  20016. //
  20017. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  20018. // this WOULD be allowed if ** did follow symlinks, or * didn't
  20019. firstPhasePreProcess(globParts) {
  20020. let didSomething = false;
  20021. do {
  20022. didSomething = false;
  20023. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  20024. for (let parts of globParts) {
  20025. let gs = -1;
  20026. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  20027. let gss = gs;
  20028. while (parts[gss + 1] === '**') {
  20029. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  20030. gss++;
  20031. }
  20032. // eg, if gs is 2 and gss is 4, that means we have 3 **
  20033. // parts, and can remove 2 of them.
  20034. if (gss > gs) {
  20035. parts.splice(gs + 1, gss - gs);
  20036. }
  20037. let next = parts[gs + 1];
  20038. const p = parts[gs + 2];
  20039. const p2 = parts[gs + 3];
  20040. if (next !== '..')
  20041. continue;
  20042. if (!p ||
  20043. p === '.' ||
  20044. p === '..' ||
  20045. !p2 ||
  20046. p2 === '.' ||
  20047. p2 === '..') {
  20048. continue;
  20049. }
  20050. didSomething = true;
  20051. // edit parts in place, and push the new one
  20052. parts.splice(gs, 1);
  20053. const other = parts.slice(0);
  20054. other[gs] = '**';
  20055. globParts.push(other);
  20056. gs--;
  20057. }
  20058. // <pre>/<e>/<rest> -> <pre>/<rest>
  20059. if (!this.preserveMultipleSlashes) {
  20060. for (let i = 1; i < parts.length - 1; i++) {
  20061. const p = parts[i];
  20062. // don't squeeze out UNC patterns
  20063. if (i === 1 && p === '' && parts[0] === '')
  20064. continue;
  20065. if (p === '.' || p === '') {
  20066. didSomething = true;
  20067. parts.splice(i, 1);
  20068. i--;
  20069. }
  20070. }
  20071. if (parts[0] === '.' &&
  20072. parts.length === 2 &&
  20073. (parts[1] === '.' || parts[1] === '')) {
  20074. didSomething = true;
  20075. parts.pop();
  20076. }
  20077. }
  20078. // <pre>/<p>/../<rest> -> <pre>/<rest>
  20079. let dd = 0;
  20080. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  20081. const p = parts[dd - 1];
  20082. if (p && p !== '.' && p !== '..' && p !== '**') {
  20083. didSomething = true;
  20084. const needDot = dd === 1 && parts[dd + 1] === '**';
  20085. const splin = needDot ? ['.'] : [];
  20086. parts.splice(dd - 1, 2, ...splin);
  20087. if (parts.length === 0)
  20088. parts.push('');
  20089. dd -= 2;
  20090. }
  20091. }
  20092. }
  20093. } while (didSomething);
  20094. return globParts;
  20095. }
  20096. // second phase: multi-pattern dedupes
  20097. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  20098. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  20099. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  20100. //
  20101. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  20102. // ^-- not valid because ** doens't follow symlinks
  20103. secondPhasePreProcess(globParts) {
  20104. for (let i = 0; i < globParts.length - 1; i++) {
  20105. for (let j = i + 1; j < globParts.length; j++) {
  20106. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  20107. if (matched) {
  20108. globParts[i] = [];
  20109. globParts[j] = matched;
  20110. break;
  20111. }
  20112. }
  20113. }
  20114. return globParts.filter(gs => gs.length);
  20115. }
  20116. partsMatch(a, b, emptyGSMatch = false) {
  20117. let ai = 0;
  20118. let bi = 0;
  20119. let result = [];
  20120. let which = '';
  20121. while (ai < a.length && bi < b.length) {
  20122. if (a[ai] === b[bi]) {
  20123. result.push(which === 'b' ? b[bi] : a[ai]);
  20124. ai++;
  20125. bi++;
  20126. }
  20127. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  20128. result.push(a[ai]);
  20129. ai++;
  20130. }
  20131. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  20132. result.push(b[bi]);
  20133. bi++;
  20134. }
  20135. else if (a[ai] === '*' &&
  20136. b[bi] &&
  20137. (this.options.dot || !b[bi].startsWith('.')) &&
  20138. b[bi] !== '**') {
  20139. if (which === 'b')
  20140. return false;
  20141. which = 'a';
  20142. result.push(a[ai]);
  20143. ai++;
  20144. bi++;
  20145. }
  20146. else if (b[bi] === '*' &&
  20147. a[ai] &&
  20148. (this.options.dot || !a[ai].startsWith('.')) &&
  20149. a[ai] !== '**') {
  20150. if (which === 'a')
  20151. return false;
  20152. which = 'b';
  20153. result.push(b[bi]);
  20154. ai++;
  20155. bi++;
  20156. }
  20157. else {
  20158. return false;
  20159. }
  20160. }
  20161. // if we fall out of the loop, it means they two are identical
  20162. // as long as their lengths match
  20163. return a.length === b.length && result;
  20164. }
  20165. parseNegate() {
  20166. if (this.nonegate)
  20167. return;
  20168. const pattern = this.pattern;
  20169. let negate = false;
  20170. let negateOffset = 0;
  20171. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  20172. negate = !negate;
  20173. negateOffset++;
  20174. }
  20175. if (negateOffset)
  20176. this.pattern = pattern.slice(negateOffset);
  20177. this.negate = negate;
  20178. }
  20179. // set partial to true to test if, for example,
  20180. // "/a/b" matches the start of "/*/b/*/d"
  20181. // Partial means, if you run out of file before you run
  20182. // out of pattern, then that's fine, as long as all
  20183. // the parts match.
  20184. matchOne(file, pattern, partial = false) {
  20185. let fileStartIndex = 0;
  20186. let patternStartIndex = 0;
  20187. // UNC paths like //?/X:/... can match X:/... and vice versa
  20188. // Drive letters in absolute drive or unc paths are always compared
  20189. // case-insensitively.
  20190. if (this.isWindows) {
  20191. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  20192. const fileUNC = !fileDrive &&
  20193. file[0] === '' &&
  20194. file[1] === '' &&
  20195. file[2] === '?' &&
  20196. /^[a-z]:$/i.test(file[3]);
  20197. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  20198. const patternUNC = !patternDrive &&
  20199. pattern[0] === '' &&
  20200. pattern[1] === '' &&
  20201. pattern[2] === '?' &&
  20202. typeof pattern[3] === 'string' &&
  20203. /^[a-z]:$/i.test(pattern[3]);
  20204. const fdi = fileUNC ? 3
  20205. : fileDrive ? 0
  20206. : undefined;
  20207. const pdi = patternUNC ? 3
  20208. : patternDrive ? 0
  20209. : undefined;
  20210. if (typeof fdi === 'number' && typeof pdi === 'number') {
  20211. const [fd, pd] = [
  20212. file[fdi],
  20213. pattern[pdi],
  20214. ];
  20215. // start matching at the drive letter index of each
  20216. if (fd.toLowerCase() === pd.toLowerCase()) {
  20217. pattern[pdi] = fd;
  20218. patternStartIndex = pdi;
  20219. fileStartIndex = fdi;
  20220. }
  20221. }
  20222. }
  20223. // resolve and reduce . and .. portions in the file as well.
  20224. // don't need to do the second phase, because it's only one string[]
  20225. const { optimizationLevel = 1 } = this.options;
  20226. if (optimizationLevel >= 2) {
  20227. file = this.levelTwoFileOptimize(file);
  20228. }
  20229. if (pattern.includes(GLOBSTAR)) {
  20230. return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
  20231. }
  20232. return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
  20233. }
  20234. #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
  20235. // split the pattern into head, tail, and middle of ** delimited parts
  20236. const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
  20237. const lastgs = pattern.lastIndexOf(GLOBSTAR);
  20238. // split the pattern up into globstar-delimited sections
  20239. // the tail has to be at the end, and the others just have
  20240. // to be found in order from the head.
  20241. const [head, body, tail] = partial ?
  20242. [
  20243. pattern.slice(patternIndex, firstgs),
  20244. pattern.slice(firstgs + 1),
  20245. [],
  20246. ]
  20247. : [
  20248. pattern.slice(patternIndex, firstgs),
  20249. pattern.slice(firstgs + 1, lastgs),
  20250. pattern.slice(lastgs + 1),
  20251. ];
  20252. // check the head, from the current file/pattern index.
  20253. if (head.length) {
  20254. const fileHead = file.slice(fileIndex, fileIndex + head.length);
  20255. if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
  20256. return false;
  20257. }
  20258. fileIndex += head.length;
  20259. patternIndex += head.length;
  20260. }
  20261. // now we know the head matches!
  20262. // if the last portion is not empty, it MUST match the end
  20263. // check the tail
  20264. let fileTailMatch = 0;
  20265. if (tail.length) {
  20266. // if head + tail > file, then we cannot possibly match
  20267. if (tail.length + fileIndex > file.length)
  20268. return false;
  20269. // try to match the tail
  20270. let tailStart = file.length - tail.length;
  20271. if (this.#matchOne(file, tail, partial, tailStart, 0)) {
  20272. fileTailMatch = tail.length;
  20273. }
  20274. else {
  20275. // affordance for stuff like a/**/* matching a/b/
  20276. // if the last file portion is '', and there's more to the pattern
  20277. // then try without the '' bit.
  20278. if (file[file.length - 1] !== '' ||
  20279. fileIndex + tail.length === file.length) {
  20280. return false;
  20281. }
  20282. tailStart--;
  20283. if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
  20284. return false;
  20285. }
  20286. fileTailMatch = tail.length + 1;
  20287. }
  20288. }
  20289. // now we know the tail matches!
  20290. // the middle is zero or more portions wrapped in **, possibly
  20291. // containing more ** sections.
  20292. // so a/**/b/**/c/**/d has become **/b/**/c/**
  20293. // if it's empty, it means a/**/b, just verify we have no bad dots
  20294. // if there's no tail, so it ends on /**, then we must have *something*
  20295. // after the head, or it's not a matc
  20296. if (!body.length) {
  20297. let sawSome = !!fileTailMatch;
  20298. for (let i = fileIndex; i < file.length - fileTailMatch; i++) {
  20299. const f = String(file[i]);
  20300. sawSome = true;
  20301. if (f === '.' ||
  20302. f === '..' ||
  20303. (!this.options.dot && f.startsWith('.'))) {
  20304. return false;
  20305. }
  20306. }
  20307. // in partial mode, we just need to get past all file parts
  20308. return partial || sawSome;
  20309. }
  20310. // now we know that there's one or more body sections, which can
  20311. // be matched anywhere from the 0 index (because the head was pruned)
  20312. // through to the length-fileTailMatch index.
  20313. // split the body up into sections, and note the minimum index it can
  20314. // be found at (start with the length of all previous segments)
  20315. // [section, before, after]
  20316. const bodySegments = [[[], 0]];
  20317. let currentBody = bodySegments[0];
  20318. let nonGsParts = 0;
  20319. const nonGsPartsSums = [0];
  20320. for (const b of body) {
  20321. if (b === GLOBSTAR) {
  20322. nonGsPartsSums.push(nonGsParts);
  20323. currentBody = [[], 0];
  20324. bodySegments.push(currentBody);
  20325. }
  20326. else {
  20327. currentBody[0].push(b);
  20328. nonGsParts++;
  20329. }
  20330. }
  20331. let i = bodySegments.length - 1;
  20332. const fileLength = file.length - fileTailMatch;
  20333. for (const b of bodySegments) {
  20334. b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
  20335. }
  20336. return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
  20337. }
  20338. // return false for "nope, not matching"
  20339. // return null for "not matching, cannot keep trying"
  20340. #matchGlobStarBodySections(file,
  20341. // pattern section, last possible position for it
  20342. bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
  20343. // take the first body segment, and walk from fileIndex to its "after"
  20344. // value at the end
  20345. // If it doesn't match at that position, we increment, until we hit
  20346. // that final possible position, and give up.
  20347. // If it does match, then advance and try to rest.
  20348. // If any of them fail we keep walking forward.
  20349. // this is still a bit recursively painful, but it's more constrained
  20350. // than previous implementations, because we never test something that
  20351. // can't possibly be a valid matching condition.
  20352. const bs = bodySegments[bodyIndex];
  20353. if (!bs) {
  20354. // just make sure that there's no bad dots
  20355. for (let i = fileIndex; i < file.length; i++) {
  20356. sawTail = true;
  20357. const f = file[i];
  20358. if (f === '.' ||
  20359. f === '..' ||
  20360. (!this.options.dot && f.startsWith('.'))) {
  20361. return false;
  20362. }
  20363. }
  20364. return sawTail;
  20365. }
  20366. // have a non-globstar body section to test
  20367. const [body, after] = bs;
  20368. while (fileIndex <= after) {
  20369. const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
  20370. // if limit exceeded, no match. intentional false negative,
  20371. // acceptable break in correctness for security.
  20372. if (m && globStarDepth < this.maxGlobstarRecursion) {
  20373. // match! see if the rest match. if so, we're done!
  20374. const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
  20375. if (sub !== false) {
  20376. return sub;
  20377. }
  20378. }
  20379. const f = file[fileIndex];
  20380. if (f === '.' ||
  20381. f === '..' ||
  20382. (!this.options.dot && f.startsWith('.'))) {
  20383. return false;
  20384. }
  20385. fileIndex++;
  20386. }
  20387. // walked off. no point continuing
  20388. return partial || null;
  20389. }
  20390. #matchOne(file, pattern, partial, fileIndex, patternIndex) {
  20391. let fi;
  20392. let pi;
  20393. let pl;
  20394. let fl;
  20395. for (fi = fileIndex,
  20396. pi = patternIndex,
  20397. fl = file.length,
  20398. pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  20399. this.debug('matchOne loop');
  20400. let p = pattern[pi];
  20401. let f = file[fi];
  20402. this.debug(pattern, p, f);
  20403. // should be impossible.
  20404. // some invalid regexp stuff in the set.
  20405. /* c8 ignore start */
  20406. if (p === false || p === GLOBSTAR) {
  20407. return false;
  20408. }
  20409. /* c8 ignore stop */
  20410. // something other than **
  20411. // non-magic patterns just have to match exactly
  20412. // patterns with magic have been turned into regexps.
  20413. let hit;
  20414. if (typeof p === 'string') {
  20415. hit = f === p;
  20416. this.debug('string match', p, f, hit);
  20417. }
  20418. else {
  20419. hit = p.test(f);
  20420. this.debug('pattern match', p, f, hit);
  20421. }
  20422. if (!hit)
  20423. return false;
  20424. }
  20425. // Note: ending in / means that we'll get a final ""
  20426. // at the end of the pattern. This can only match a
  20427. // corresponding "" at the end of the file.
  20428. // If the file ends in /, then it can only match a
  20429. // a pattern that ends in /, unless the pattern just
  20430. // doesn't have any more for it. But, a/b/ should *not*
  20431. // match "a/b/*", even though "" matches against the
  20432. // [^/]*? pattern, except in partial mode, where it might
  20433. // simply not be reached yet.
  20434. // However, a/b/ should still satisfy a/*
  20435. // now either we fell off the end of the pattern, or we're done.
  20436. if (fi === fl && pi === pl) {
  20437. // ran out of pattern and filename at the same time.
  20438. // an exact hit!
  20439. return true;
  20440. }
  20441. else if (fi === fl) {
  20442. // ran out of file, but still had pattern left.
  20443. // this is ok if we're doing the match as part of
  20444. // a glob fs traversal.
  20445. return partial;
  20446. }
  20447. else if (pi === pl) {
  20448. // ran out of pattern, still have file left.
  20449. // this is only acceptable if we're on the very last
  20450. // empty segment of a file with a trailing slash.
  20451. // a/* should match a/b/
  20452. return fi === fl - 1 && file[fi] === '';
  20453. /* c8 ignore start */
  20454. }
  20455. else {
  20456. // should be unreachable.
  20457. throw new Error('wtf?');
  20458. }
  20459. /* c8 ignore stop */
  20460. }
  20461. braceExpand() {
  20462. return braceExpand(this.pattern, this.options);
  20463. }
  20464. parse(pattern) {
  20465. assertValidPattern(pattern);
  20466. const options = this.options;
  20467. // shortcuts
  20468. if (pattern === '**')
  20469. return GLOBSTAR;
  20470. if (pattern === '')
  20471. return '';
  20472. // far and away, the most common glob pattern parts are
  20473. // *, *.*, and *.<ext> Add a fast check method for those.
  20474. let m;
  20475. let fastTest = null;
  20476. if ((m = pattern.match(starRE))) {
  20477. fastTest = options.dot ? starTestDot : starTest;
  20478. }
  20479. else if ((m = pattern.match(starDotExtRE))) {
  20480. fastTest = (options.nocase ?
  20481. options.dot ?
  20482. starDotExtTestNocaseDot
  20483. : starDotExtTestNocase
  20484. : options.dot ? starDotExtTestDot
  20485. : starDotExtTest)(m[1]);
  20486. }
  20487. else if ((m = pattern.match(qmarksRE))) {
  20488. fastTest = (options.nocase ?
  20489. options.dot ?
  20490. qmarksTestNocaseDot
  20491. : qmarksTestNocase
  20492. : options.dot ? qmarksTestDot
  20493. : qmarksTest)(m);
  20494. }
  20495. else if ((m = pattern.match(starDotStarRE))) {
  20496. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  20497. }
  20498. else if ((m = pattern.match(dotStarRE))) {
  20499. fastTest = dotStarTest;
  20500. }
  20501. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  20502. if (fastTest && typeof re === 'object') {
  20503. // Avoids overriding in frozen environments
  20504. Reflect.defineProperty(re, 'test', { value: fastTest });
  20505. }
  20506. return re;
  20507. }
  20508. makeRe() {
  20509. if (this.regexp || this.regexp === false)
  20510. return this.regexp;
  20511. // at this point, this.set is a 2d array of partial
  20512. // pattern strings, or "**".
  20513. //
  20514. // It's better to use .match(). This function shouldn't
  20515. // be used, really, but it's pretty convenient sometimes,
  20516. // when you just want to work with a regex.
  20517. const set = this.set;
  20518. if (!set.length) {
  20519. this.regexp = false;
  20520. return this.regexp;
  20521. }
  20522. const options = this.options;
  20523. const twoStar = options.noglobstar ? star
  20524. : options.dot ? twoStarDot
  20525. : twoStarNoDot;
  20526. const flags = new Set(options.nocase ? ['i'] : []);
  20527. // regexpify non-globstar patterns
  20528. // if ** is only item, then we just do one twoStar
  20529. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  20530. // if ** is last, append (\/twoStar|) to previous
  20531. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  20532. // then filter out GLOBSTAR symbols
  20533. let re = set
  20534. .map(pattern => {
  20535. const pp = pattern.map(p => {
  20536. if (p instanceof RegExp) {
  20537. for (const f of p.flags.split(''))
  20538. flags.add(f);
  20539. }
  20540. return (typeof p === 'string' ? regExpEscape(p)
  20541. : p === GLOBSTAR ? GLOBSTAR
  20542. : p._src);
  20543. });
  20544. pp.forEach((p, i) => {
  20545. const next = pp[i + 1];
  20546. const prev = pp[i - 1];
  20547. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  20548. return;
  20549. }
  20550. if (prev === undefined) {
  20551. if (next !== undefined && next !== GLOBSTAR) {
  20552. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  20553. }
  20554. else {
  20555. pp[i] = twoStar;
  20556. }
  20557. }
  20558. else if (next === undefined) {
  20559. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
  20560. }
  20561. else if (next !== GLOBSTAR) {
  20562. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  20563. pp[i + 1] = GLOBSTAR;
  20564. }
  20565. });
  20566. const filtered = pp.filter(p => p !== GLOBSTAR);
  20567. // For partial matches, we need to make the pattern match
  20568. // any prefix of the full path. We do this by generating
  20569. // alternative patterns that match progressively longer prefixes.
  20570. if (this.partial && filtered.length >= 1) {
  20571. const prefixes = [];
  20572. for (let i = 1; i <= filtered.length; i++) {
  20573. prefixes.push(filtered.slice(0, i).join('/'));
  20574. }
  20575. return '(?:' + prefixes.join('|') + ')';
  20576. }
  20577. return filtered.join('/');
  20578. })
  20579. .join('|');
  20580. // need to wrap in parens if we had more than one thing with |,
  20581. // otherwise only the first will be anchored to ^ and the last to $
  20582. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  20583. // must match entire pattern
  20584. // ending in a * or ** will make it less strict.
  20585. re = '^' + open + re + close + '$';
  20586. // In partial mode, '/' should always match as it's a valid prefix for any pattern
  20587. if (this.partial) {
  20588. re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
  20589. }
  20590. // can match anything, as long as it's not this.
  20591. if (this.negate)
  20592. re = '^(?!' + re + ').+$';
  20593. try {
  20594. this.regexp = new RegExp(re, [...flags].join(''));
  20595. /* c8 ignore start */
  20596. }
  20597. catch {
  20598. // should be impossible
  20599. this.regexp = false;
  20600. }
  20601. /* c8 ignore stop */
  20602. return this.regexp;
  20603. }
  20604. slashSplit(p) {
  20605. // if p starts with // on windows, we preserve that
  20606. // so that UNC paths aren't broken. Otherwise, any number of
  20607. // / characters are coalesced into one, unless
  20608. // preserveMultipleSlashes is set to true.
  20609. if (this.preserveMultipleSlashes) {
  20610. return p.split('/');
  20611. }
  20612. else if (this.isWindows && /^\/\/[^/]+/.test(p)) {
  20613. // add an extra '' for the one we lose
  20614. return ['', ...p.split(/\/+/)];
  20615. }
  20616. else {
  20617. return p.split(/\/+/);
  20618. }
  20619. }
  20620. match(f, partial = this.partial) {
  20621. this.debug('match', f, this.pattern);
  20622. // short-circuit in the case of busted things.
  20623. // comments, etc.
  20624. if (this.comment) {
  20625. return false;
  20626. }
  20627. if (this.empty) {
  20628. return f === '';
  20629. }
  20630. if (f === '/' && partial) {
  20631. return true;
  20632. }
  20633. const options = this.options;
  20634. // windows: need to use /, not \
  20635. if (this.isWindows) {
  20636. f = f.split('\\').join('/');
  20637. }
  20638. // treat the test path as a set of pathparts.
  20639. const ff = this.slashSplit(f);
  20640. this.debug(this.pattern, 'split', ff);
  20641. // just ONE of the pattern sets in this.set needs to match
  20642. // in order for it to be valid. If negating, then just one
  20643. // match means that we have failed.
  20644. // Either way, return on the first hit.
  20645. const set = this.set;
  20646. this.debug(this.pattern, 'set', set);
  20647. // Find the basename of the path by looking for the last non-empty segment
  20648. let filename = ff[ff.length - 1];
  20649. if (!filename) {
  20650. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  20651. filename = ff[i];
  20652. }
  20653. }
  20654. for (const pattern of set) {
  20655. let file = ff;
  20656. if (options.matchBase && pattern.length === 1) {
  20657. file = [filename];
  20658. }
  20659. const hit = this.matchOne(file, pattern, partial);
  20660. if (hit) {
  20661. if (options.flipNegate) {
  20662. return true;
  20663. }
  20664. return !this.negate;
  20665. }
  20666. }
  20667. // didn't get any hits. this is success if it's a negative
  20668. // pattern, failure otherwise.
  20669. if (options.flipNegate) {
  20670. return false;
  20671. }
  20672. return this.negate;
  20673. }
  20674. static defaults(def) {
  20675. return minimatch.defaults(def).Minimatch;
  20676. }
  20677. }
  20678. /* c8 ignore stop */
  20679. minimatch.AST = AST;
  20680. minimatch.Minimatch = Minimatch;
  20681. minimatch.escape = escape;
  20682. minimatch.unescape = unescape;
  20683. class TypeScope {
  20684. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  20685. this.filename = filename;
  20686. this.source = source;
  20687. this.offset = offset;
  20688. this.imports = imports;
  20689. this.types = types;
  20690. this.declares = declares;
  20691. this.isGenericScope = false;
  20692. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  20693. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  20694. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  20695. }
  20696. }
  20697. function recordScopeDep(ctx, scope) {
  20698. if (scope && scope.filename !== ctx.filename) {
  20699. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(scope.filename);
  20700. }
  20701. }
  20702. function recordResolvedElementDeps(ctx, { props }) {
  20703. for (const key in props) {
  20704. recordScopeDep(ctx, props[key]._ownerScope);
  20705. }
  20706. }
  20707. function resolveTypeElements(ctx, node, scope, typeParameters) {
  20708. const canCache = !typeParameters;
  20709. if (canCache && node._resolvedElements) {
  20710. recordResolvedElementDeps(ctx, node._resolvedElements);
  20711. return node._resolvedElements;
  20712. }
  20713. const resolved = innerResolveTypeElements(
  20714. ctx,
  20715. node,
  20716. node._ownerScope || scope || ctxToScope(ctx),
  20717. typeParameters
  20718. );
  20719. return canCache ? node._resolvedElements = resolved : resolved;
  20720. }
  20721. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  20722. var _a, _b;
  20723. if (hasVueIgnore(node)) {
  20724. if ((node.type === "TSIntersectionType" || node.type === "TSUnionType") && node.types.length > 1) {
  20725. return mergeElements(
  20726. [
  20727. { props: {} },
  20728. ...node.types.slice(1).map((t) => resolveTypeElements(ctx, t, scope, typeParameters))
  20729. ],
  20730. node.type
  20731. );
  20732. }
  20733. return { props: {} };
  20734. }
  20735. switch (node.type) {
  20736. case "TSTypeLiteral":
  20737. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  20738. case "TSInterfaceDeclaration":
  20739. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  20740. case "TSTypeAliasDeclaration":
  20741. case "TSTypeAnnotation":
  20742. case "TSParenthesizedType":
  20743. return resolveTypeElements(
  20744. ctx,
  20745. node.typeAnnotation,
  20746. scope,
  20747. typeParameters
  20748. );
  20749. case "TSFunctionType": {
  20750. return { props: {}, calls: [node] };
  20751. }
  20752. case "TSUnionType":
  20753. case "TSIntersectionType":
  20754. return mergeElements(
  20755. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  20756. node.type
  20757. );
  20758. case "TSMappedType":
  20759. return resolveMappedType(ctx, node, scope, typeParameters);
  20760. case "TSIndexedAccessType": {
  20761. const types = resolveIndexType(ctx, node, scope);
  20762. return mergeElements(
  20763. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  20764. "TSUnionType"
  20765. );
  20766. }
  20767. case "TSExpressionWithTypeArguments":
  20768. // referenced by interface extends
  20769. case "TSTypeReference": {
  20770. const typeName = getReferenceName(node);
  20771. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  20772. return resolveExtractPropTypes(
  20773. resolveTypeElements(
  20774. ctx,
  20775. node.typeParameters.params[0],
  20776. scope,
  20777. typeParameters
  20778. ),
  20779. scope
  20780. );
  20781. }
  20782. const resolved = resolveTypeReference(ctx, node, scope);
  20783. if (resolved) {
  20784. let typeParams;
  20785. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  20786. typeParams = /* @__PURE__ */ Object.create(null);
  20787. resolved.typeParameters.params.forEach((p, i) => {
  20788. let param = typeParameters && typeParameters[p.name];
  20789. if (!param) param = node.typeParameters.params[i];
  20790. typeParams[p.name] = param;
  20791. });
  20792. }
  20793. return resolveTypeElements(
  20794. ctx,
  20795. resolved,
  20796. resolved._ownerScope,
  20797. typeParams
  20798. );
  20799. } else {
  20800. if (typeof typeName === "string") {
  20801. if (typeParameters && typeParameters[typeName]) {
  20802. return resolveTypeElements(
  20803. ctx,
  20804. typeParameters[typeName],
  20805. scope,
  20806. typeParameters
  20807. );
  20808. }
  20809. if (
  20810. // @ts-expect-error
  20811. SupportedBuiltinsSet.has(typeName)
  20812. ) {
  20813. return resolveBuiltin(
  20814. ctx,
  20815. node,
  20816. typeName,
  20817. scope,
  20818. typeParameters
  20819. );
  20820. } else if (typeName === "ReturnType" && node.typeParameters) {
  20821. const ret = resolveReturnType(
  20822. ctx,
  20823. node.typeParameters.params[0],
  20824. scope
  20825. );
  20826. if (ret) {
  20827. return resolveTypeElements(ctx, ret, scope);
  20828. }
  20829. }
  20830. }
  20831. return ctx.error(
  20832. `Unresolvable type reference or unsupported built-in utility type`,
  20833. node,
  20834. scope
  20835. );
  20836. }
  20837. }
  20838. case "TSImportType": {
  20839. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  20840. return resolveExtractPropTypes(
  20841. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  20842. scope
  20843. );
  20844. }
  20845. const sourceScope = importSourceToScope(
  20846. ctx,
  20847. node.argument,
  20848. scope,
  20849. node.argument.value
  20850. );
  20851. const resolved = resolveTypeReference(ctx, node, sourceScope);
  20852. if (resolved) {
  20853. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20854. }
  20855. break;
  20856. }
  20857. case "TSTypeQuery":
  20858. {
  20859. const resolved = resolveTypeReference(ctx, node, scope);
  20860. if (resolved) {
  20861. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20862. }
  20863. }
  20864. break;
  20865. }
  20866. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  20867. }
  20868. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  20869. const res = { props: {} };
  20870. for (const e of elements) {
  20871. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  20872. if (typeParameters) {
  20873. scope = createChildScope(scope);
  20874. scope.isGenericScope = true;
  20875. Object.assign(scope.types, typeParameters);
  20876. }
  20877. e._ownerScope = scope;
  20878. const name = getStringLiteralKey(e);
  20879. if (name !== null) {
  20880. res.props[name] = e;
  20881. } else {
  20882. ctx.error(
  20883. `Unsupported computed key in type referenced by a macro`,
  20884. e.key,
  20885. scope
  20886. );
  20887. }
  20888. } else if (e.type === "TSCallSignatureDeclaration") {
  20889. (res.calls || (res.calls = [])).push(e);
  20890. }
  20891. }
  20892. return res;
  20893. }
  20894. function hasVueIgnore(node) {
  20895. return !!(node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore")));
  20896. }
  20897. function mergeElements(maps, type) {
  20898. if (maps.length === 1) return maps[0];
  20899. const res = { props: {} };
  20900. const { props: baseProps } = res;
  20901. for (const { props, calls } of maps) {
  20902. for (const key in props) {
  20903. if (!shared.hasOwn(baseProps, key)) {
  20904. baseProps[key] = props[key];
  20905. } else {
  20906. baseProps[key] = createProperty(
  20907. baseProps[key].key,
  20908. {
  20909. type,
  20910. // @ts-expect-error
  20911. types: [baseProps[key], props[key]]
  20912. },
  20913. baseProps[key]._ownerScope,
  20914. baseProps[key].optional || props[key].optional
  20915. );
  20916. }
  20917. }
  20918. if (calls) {
  20919. (res.calls || (res.calls = [])).push(...calls);
  20920. }
  20921. }
  20922. return res;
  20923. }
  20924. function createProperty(key, typeAnnotation, scope, optional) {
  20925. return {
  20926. type: "TSPropertySignature",
  20927. key,
  20928. kind: "get",
  20929. optional,
  20930. typeAnnotation: {
  20931. type: "TSTypeAnnotation",
  20932. typeAnnotation
  20933. },
  20934. _ownerScope: scope
  20935. };
  20936. }
  20937. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  20938. const base = typeElementsToMap(
  20939. ctx,
  20940. node.body.body,
  20941. node._ownerScope,
  20942. typeParameters
  20943. );
  20944. if (node.extends) {
  20945. for (const ext of node.extends) {
  20946. try {
  20947. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  20948. for (const key in props) {
  20949. if (!shared.hasOwn(base.props, key)) {
  20950. base.props[key] = props[key];
  20951. }
  20952. }
  20953. if (calls) {
  20954. ;
  20955. (base.calls || (base.calls = [])).push(...calls);
  20956. }
  20957. } catch (e) {
  20958. if (!ctx.silentOnExtendsFailure) {
  20959. ctx.error(
  20960. `Failed to resolve extends base type.
  20961. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  20962. interface Props extends /* @vue-ignore */ Base {}
  20963. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  20964. ext,
  20965. scope
  20966. );
  20967. }
  20968. }
  20969. }
  20970. }
  20971. return base;
  20972. }
  20973. function resolveMappedType(ctx, node, scope, typeParameters) {
  20974. const res = { props: {} };
  20975. let keys;
  20976. if (node.nameType) {
  20977. const { name, constraint } = node.typeParameter;
  20978. scope = createChildScope(scope);
  20979. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  20980. keys = resolveStringType(ctx, node.nameType, scope);
  20981. } else {
  20982. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  20983. }
  20984. for (const key of keys) {
  20985. res.props[key] = createProperty(
  20986. {
  20987. type: "Identifier",
  20988. name: key
  20989. },
  20990. node.typeAnnotation,
  20991. scope,
  20992. !!node.optional
  20993. );
  20994. }
  20995. return res;
  20996. }
  20997. function resolveIndexType(ctx, node, scope) {
  20998. var _a, _b;
  20999. if (node.indexType.type === "TSNumberKeyword") {
  21000. return resolveArrayElementType(ctx, node.objectType, scope);
  21001. }
  21002. const { indexType, objectType } = node;
  21003. const types = [];
  21004. let keys;
  21005. let resolved;
  21006. if (indexType.type === "TSStringKeyword") {
  21007. resolved = resolveTypeElements(ctx, objectType, scope);
  21008. keys = Object.keys(resolved.props);
  21009. } else {
  21010. keys = resolveStringType(ctx, indexType, scope);
  21011. resolved = resolveTypeElements(ctx, objectType, scope);
  21012. }
  21013. for (const key of keys) {
  21014. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  21015. if (targetType) {
  21016. targetType._ownerScope = resolved.props[key]._ownerScope;
  21017. types.push(targetType);
  21018. }
  21019. }
  21020. return types;
  21021. }
  21022. function resolveArrayElementType(ctx, node, scope) {
  21023. if (node.type === "TSArrayType") {
  21024. return [node.elementType];
  21025. }
  21026. if (node.type === "TSTupleType") {
  21027. return node.elementTypes.map(
  21028. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  21029. );
  21030. }
  21031. if (node.type === "TSTypeReference") {
  21032. if (getReferenceName(node) === "Array" && node.typeParameters) {
  21033. return node.typeParameters.params;
  21034. } else {
  21035. const resolved = resolveTypeReference(ctx, node, scope);
  21036. if (resolved) {
  21037. return resolveArrayElementType(ctx, resolved, scope);
  21038. }
  21039. }
  21040. }
  21041. return ctx.error(
  21042. "Failed to resolve element type from target type",
  21043. node,
  21044. scope
  21045. );
  21046. }
  21047. function resolveStringType(ctx, node, scope, typeParameters) {
  21048. switch (node.type) {
  21049. case "StringLiteral":
  21050. return [node.value];
  21051. case "TSLiteralType":
  21052. return resolveStringType(ctx, node.literal, scope, typeParameters);
  21053. case "TSUnionType":
  21054. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  21055. case "TemplateLiteral": {
  21056. return resolveTemplateKeys(ctx, node, scope);
  21057. }
  21058. case "TSTypeReference": {
  21059. const resolved = resolveTypeReference(ctx, node, scope);
  21060. if (resolved) {
  21061. return resolveStringType(ctx, resolved, scope, typeParameters);
  21062. }
  21063. if (node.typeName.type === "Identifier") {
  21064. const name = node.typeName.name;
  21065. if (typeParameters && typeParameters[name]) {
  21066. return resolveStringType(
  21067. ctx,
  21068. typeParameters[name],
  21069. scope,
  21070. typeParameters
  21071. );
  21072. }
  21073. const getParam = (index = 0) => resolveStringType(
  21074. ctx,
  21075. node.typeParameters.params[index],
  21076. scope,
  21077. typeParameters
  21078. );
  21079. switch (name) {
  21080. case "Extract":
  21081. return getParam(1);
  21082. case "Exclude": {
  21083. const excluded = getParam(1);
  21084. return getParam().filter((s) => !excluded.includes(s));
  21085. }
  21086. case "Uppercase":
  21087. return getParam().map((s) => s.toUpperCase());
  21088. case "Lowercase":
  21089. return getParam().map((s) => s.toLowerCase());
  21090. case "Capitalize":
  21091. return getParam().map(shared.capitalize);
  21092. case "Uncapitalize":
  21093. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  21094. default:
  21095. ctx.error(
  21096. "Unsupported type when resolving index type",
  21097. node.typeName,
  21098. scope
  21099. );
  21100. }
  21101. }
  21102. }
  21103. }
  21104. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  21105. }
  21106. function resolveTemplateKeys(ctx, node, scope) {
  21107. if (!node.expressions.length) {
  21108. return [node.quasis[0].value.raw];
  21109. }
  21110. const res = [];
  21111. const e = node.expressions[0];
  21112. const q = node.quasis[0];
  21113. const leading = q ? q.value.raw : ``;
  21114. const resolved = resolveStringType(ctx, e, scope);
  21115. const restResolved = resolveTemplateKeys(
  21116. ctx,
  21117. {
  21118. ...node,
  21119. expressions: node.expressions.slice(1),
  21120. quasis: q ? node.quasis.slice(1) : node.quasis
  21121. },
  21122. scope
  21123. );
  21124. for (const r of resolved) {
  21125. for (const rr of restResolved) {
  21126. res.push(leading + r + rr);
  21127. }
  21128. }
  21129. return res;
  21130. }
  21131. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  21132. "Partial",
  21133. "Required",
  21134. "Readonly",
  21135. "Pick",
  21136. "Omit"
  21137. ]);
  21138. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  21139. const t = resolveTypeElements(
  21140. ctx,
  21141. node.typeParameters.params[0],
  21142. scope,
  21143. typeParameters
  21144. );
  21145. switch (name) {
  21146. case "Partial": {
  21147. const res2 = { props: {}, calls: t.calls };
  21148. Object.keys(t.props).forEach((key) => {
  21149. res2.props[key] = { ...t.props[key], optional: true };
  21150. });
  21151. return res2;
  21152. }
  21153. case "Required": {
  21154. const res2 = { props: {}, calls: t.calls };
  21155. Object.keys(t.props).forEach((key) => {
  21156. res2.props[key] = { ...t.props[key], optional: false };
  21157. });
  21158. return res2;
  21159. }
  21160. case "Readonly":
  21161. return t;
  21162. case "Pick": {
  21163. const picked = resolveStringType(
  21164. ctx,
  21165. node.typeParameters.params[1],
  21166. scope,
  21167. typeParameters
  21168. );
  21169. const res2 = { props: {}, calls: t.calls };
  21170. for (const key of picked) {
  21171. res2.props[key] = t.props[key];
  21172. }
  21173. return res2;
  21174. }
  21175. case "Omit":
  21176. const omitted = resolveStringType(
  21177. ctx,
  21178. node.typeParameters.params[1],
  21179. scope,
  21180. typeParameters
  21181. );
  21182. const res = { props: {}, calls: t.calls };
  21183. for (const key in t.props) {
  21184. if (!omitted.includes(key)) {
  21185. res.props[key] = t.props[key];
  21186. }
  21187. }
  21188. return res;
  21189. }
  21190. }
  21191. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  21192. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  21193. if (canCache && node._resolvedReference) {
  21194. recordScopeDep(ctx, node._resolvedReference._ownerScope);
  21195. return node._resolvedReference;
  21196. }
  21197. const resolved = innerResolveTypeReference(
  21198. ctx,
  21199. scope || ctxToScope(ctx),
  21200. name || getReferenceName(node),
  21201. node,
  21202. onlyExported
  21203. );
  21204. return canCache ? node._resolvedReference = resolved : resolved;
  21205. }
  21206. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  21207. if (typeof name === "string") {
  21208. if (scope.imports[name]) {
  21209. return resolveTypeFromImport(ctx, node, name, scope);
  21210. } else {
  21211. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  21212. if (lookupSource[name]) {
  21213. return lookupSource[name];
  21214. } else {
  21215. const globalScopes = resolveGlobalScope(ctx);
  21216. if (globalScopes) {
  21217. for (const s of globalScopes) {
  21218. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  21219. if (src[name]) {
  21220. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  21221. const resolved = src[name];
  21222. if (resolved._ownerScope && resolved._ownerScope !== s) {
  21223. ctx.deps.add(resolved._ownerScope.filename);
  21224. }
  21225. return resolved;
  21226. }
  21227. }
  21228. }
  21229. }
  21230. }
  21231. } else {
  21232. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  21233. if (ns) {
  21234. if (ns.type !== "TSModuleDeclaration") {
  21235. ns = ns._ns;
  21236. }
  21237. if (ns) {
  21238. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  21239. return innerResolveTypeReference(
  21240. ctx,
  21241. childScope,
  21242. name.length > 2 ? name.slice(1) : name[name.length - 1],
  21243. node,
  21244. !ns.declare
  21245. );
  21246. }
  21247. }
  21248. }
  21249. }
  21250. function getReferenceName(node) {
  21251. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  21252. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  21253. return ref.name;
  21254. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  21255. return qualifiedNameToPath(ref);
  21256. } else {
  21257. return "default";
  21258. }
  21259. }
  21260. function qualifiedNameToPath(node) {
  21261. if (node.type === "Identifier") {
  21262. return [node.name];
  21263. } else {
  21264. return [...qualifiedNameToPath(node.left), node.right.name];
  21265. }
  21266. }
  21267. function resolveGlobalScope(ctx) {
  21268. if (ctx.options.globalTypeFiles) {
  21269. const fs = resolveFS(ctx);
  21270. if (!fs) {
  21271. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  21272. }
  21273. return ctx.options.globalTypeFiles.map(
  21274. (file) => fileToScope(ctx, normalizePath(file), true)
  21275. );
  21276. }
  21277. }
  21278. let ts;
  21279. let loadTS;
  21280. function registerTS(_loadTS) {
  21281. loadTS = () => {
  21282. try {
  21283. return _loadTS();
  21284. } catch (err) {
  21285. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  21286. throw new Error(
  21287. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "TypeScript" is installed as a project dependency.'
  21288. );
  21289. } else {
  21290. throw new Error(
  21291. "Failed to load TypeScript for resolving imported types."
  21292. );
  21293. }
  21294. }
  21295. };
  21296. }
  21297. function resolveFS(ctx) {
  21298. if (ctx.fs) {
  21299. return ctx.fs;
  21300. }
  21301. if (!ts && loadTS) {
  21302. ts = loadTS();
  21303. }
  21304. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  21305. if (!fs) {
  21306. return;
  21307. }
  21308. return ctx.fs = {
  21309. fileExists(file) {
  21310. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21311. file = file.replace(/\.ts$/, "");
  21312. }
  21313. return fs.fileExists(file);
  21314. },
  21315. readFile(file) {
  21316. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21317. file = file.replace(/\.ts$/, "");
  21318. }
  21319. return fs.readFile(file);
  21320. },
  21321. realpath: fs.realpath
  21322. };
  21323. }
  21324. function resolveTypeFromImport(ctx, node, name, scope) {
  21325. const { source, imported } = scope.imports[name];
  21326. const sourceScope = importSourceToScope(ctx, node, scope, source);
  21327. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  21328. }
  21329. function importSourceToScope(ctx, node, scope, source, trackDep = true) {
  21330. let fs;
  21331. try {
  21332. fs = resolveFS(ctx);
  21333. } catch (err) {
  21334. return ctx.error(err.message, node, scope);
  21335. }
  21336. if (!fs) {
  21337. return ctx.error(
  21338. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  21339. node,
  21340. scope
  21341. );
  21342. }
  21343. let resolved = scope.resolvedImportSources[source];
  21344. if (!resolved) {
  21345. if (source.startsWith("..")) {
  21346. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  21347. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  21348. resolved = resolveExt(filename, fs);
  21349. } else if (source[0] === ".") {
  21350. const filename = joinPaths(path$1.dirname(scope.filename), source);
  21351. resolved = resolveExt(filename, fs);
  21352. } else {
  21353. if (!ts) {
  21354. if (loadTS) ts = loadTS();
  21355. if (!ts) {
  21356. return ctx.error(
  21357. `Failed to resolve import source ${JSON.stringify(source)}. TypeScript is required as a peer dep for vue in order to support resolving types from module imports.`,
  21358. node,
  21359. scope
  21360. );
  21361. }
  21362. }
  21363. resolved = resolveWithTS(scope.filename, source, ts, fs);
  21364. }
  21365. if (!resolved && source[0] === "." && true) {
  21366. if (!ts) {
  21367. if (loadTS) ts = loadTS();
  21368. }
  21369. if (ts) {
  21370. resolved = resolveWithTS(scope.filename, source, ts, fs);
  21371. }
  21372. }
  21373. if (resolved) {
  21374. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  21375. }
  21376. }
  21377. if (resolved) {
  21378. if (trackDep) {
  21379. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  21380. }
  21381. return fileToScope(ctx, resolved);
  21382. } else {
  21383. return ctx.error(
  21384. `Failed to resolve import source ${JSON.stringify(source)}.`,
  21385. node,
  21386. scope
  21387. );
  21388. }
  21389. }
  21390. function resolveExt(filename, fs) {
  21391. let moduleType = "u";
  21392. if (filename.endsWith(".mjs")) {
  21393. moduleType = "m";
  21394. } else if (filename.endsWith(".cjs")) {
  21395. moduleType = "c";
  21396. }
  21397. filename = filename.replace(/\.[cm]?jsx?$/, "");
  21398. const tryResolve = (filename2) => {
  21399. if (fs.fileExists(filename2)) return filename2;
  21400. };
  21401. const resolveTs = () => tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`);
  21402. const resolveMts = () => tryResolve(filename + `.mts`) || tryResolve(filename + `.d.mts`);
  21403. const resolveCts = () => tryResolve(filename + `.cts`) || tryResolve(filename + `.d.cts`);
  21404. return tryResolve(filename) || // For explicit .mjs/.cjs imports, prefer .mts/.cts declarations first.
  21405. (moduleType === "m" ? resolveMts() || resolveTs() : moduleType === "c" ? resolveCts() || resolveTs() : resolveTs() || resolveMts() || resolveCts()) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.tsx`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  21406. }
  21407. const tsConfigCache = createCache();
  21408. const tsConfigRefMap = /* @__PURE__ */ new Map();
  21409. function resolveWithTS(containingFile, source, ts2, fs) {
  21410. var _a, _b;
  21411. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  21412. let tsCompilerOptions;
  21413. let tsResolveCache;
  21414. if (configPath) {
  21415. let configs;
  21416. const normalizedConfigPath = normalizePath(configPath);
  21417. const cached = tsConfigCache.get(normalizedConfigPath);
  21418. if (!cached) {
  21419. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  21420. tsConfigCache.set(normalizedConfigPath, configs);
  21421. } else {
  21422. configs = cached;
  21423. }
  21424. let matchedConfig;
  21425. if (configs.length === 1) {
  21426. matchedConfig = configs[0];
  21427. } else {
  21428. const [major, minor] = ts2.versionMajorMinor.split(".").map(Number);
  21429. const getPattern = (base, p) => {
  21430. const supportsConfigDir = major > 5 || major === 5 && minor >= 5;
  21431. return p.startsWith("${configDir}") && supportsConfigDir ? normalizePath(p.replace("${configDir}", path$1.dirname(configPath))) : joinPaths(base, p);
  21432. };
  21433. for (const c of configs) {
  21434. const base = normalizePath(
  21435. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  21436. );
  21437. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  21438. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  21439. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, getPattern(base, p))))) {
  21440. if (excluded && excluded.some((p) => minimatch(containingFile, getPattern(base, p)))) {
  21441. continue;
  21442. }
  21443. matchedConfig = c;
  21444. break;
  21445. }
  21446. }
  21447. if (!matchedConfig) {
  21448. matchedConfig = configs[configs.length - 1];
  21449. }
  21450. }
  21451. tsCompilerOptions = matchedConfig.config.options;
  21452. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  21453. process__namespace.cwd(),
  21454. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  21455. tsCompilerOptions
  21456. ));
  21457. } else {
  21458. tsCompilerOptions = {};
  21459. }
  21460. const res = ts2.resolveModuleName(
  21461. source,
  21462. containingFile,
  21463. tsCompilerOptions,
  21464. fs,
  21465. tsResolveCache
  21466. );
  21467. if (res.resolvedModule) {
  21468. let filename = res.resolvedModule.resolvedFileName;
  21469. if (filename.endsWith(".vue.ts") && !filename.endsWith(".d.vue.ts")) {
  21470. filename = filename.replace(/\.ts$/, "");
  21471. }
  21472. return fs.realpath ? fs.realpath(filename) : filename;
  21473. }
  21474. }
  21475. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  21476. const parseConfigHost = ts2.sys;
  21477. const config = ts2.parseJsonConfigFileContent(
  21478. ts2.readConfigFile(configPath, fs.readFile).config,
  21479. parseConfigHost,
  21480. path$1.dirname(configPath),
  21481. void 0,
  21482. configPath
  21483. );
  21484. const res = [config];
  21485. visited.add(configPath);
  21486. if (config.projectReferences) {
  21487. for (const ref of config.projectReferences) {
  21488. const refPath = ts2.resolveProjectReferencePath(ref);
  21489. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  21490. continue;
  21491. }
  21492. tsConfigRefMap.set(refPath, configPath);
  21493. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  21494. }
  21495. }
  21496. return res;
  21497. }
  21498. const fileToScopeCache = createCache();
  21499. const fileToGlobalScopeCache = createCache();
  21500. function invalidateTypeCache(filename) {
  21501. filename = normalizePath(filename);
  21502. fileToScopeCache.delete(filename);
  21503. fileToGlobalScopeCache.delete(filename);
  21504. tsConfigCache.delete(filename);
  21505. const affectedConfig = tsConfigRefMap.get(filename);
  21506. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  21507. }
  21508. function fileToScope(ctx, filename, asGlobal = false) {
  21509. const cache = asGlobal ? fileToGlobalScopeCache : fileToScopeCache;
  21510. const cached = cache.get(filename);
  21511. if (cached) {
  21512. return cached;
  21513. }
  21514. const fs = resolveFS(ctx);
  21515. const source = fs.readFile(filename) || "";
  21516. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  21517. const scope = new TypeScope(filename, source, 0, recordImports(body));
  21518. recordTypes(ctx, body, scope, asGlobal);
  21519. cache.set(filename, scope);
  21520. return scope;
  21521. }
  21522. function parseFile(filename, content, fs, parserPlugins) {
  21523. const ext = path$1.extname(filename);
  21524. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".cts" || ext === ".mtsx") {
  21525. return parser$2.parse(content, {
  21526. plugins: resolveParserPlugins(
  21527. ext.slice(1),
  21528. parserPlugins,
  21529. /\.d\.[cm]?ts$/.test(filename)
  21530. ),
  21531. sourceType: "module"
  21532. }).program.body;
  21533. }
  21534. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  21535. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  21536. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  21537. if (hasArbitraryTypeDeclaration) {
  21538. return parser$2.parse(fs.readFile(arbitraryTypeSource), {
  21539. plugins: resolveParserPlugins("ts", parserPlugins, true),
  21540. sourceType: "module"
  21541. }).program.body;
  21542. }
  21543. if (ext === ".vue") {
  21544. const {
  21545. descriptor: { script, scriptSetup }
  21546. } = parse$1(content);
  21547. if (!script && !scriptSetup) {
  21548. return [];
  21549. }
  21550. const scriptOffset = script ? script.loc.start.offset : Infinity;
  21551. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  21552. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  21553. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  21554. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  21555. if (secondBlock) {
  21556. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  21557. }
  21558. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  21559. return parser$2.parse(scriptContent, {
  21560. plugins: resolveParserPlugins(lang, parserPlugins),
  21561. sourceType: "module"
  21562. }).program.body;
  21563. }
  21564. return [];
  21565. }
  21566. function ctxToScope(ctx) {
  21567. if (ctx.scope) {
  21568. return ctx.scope;
  21569. }
  21570. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  21571. const scope = new TypeScope(
  21572. ctx.filename,
  21573. ctx.source,
  21574. "startOffset" in ctx ? ctx.startOffset : 0,
  21575. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  21576. );
  21577. recordTypes(ctx, body, scope);
  21578. return ctx.scope = scope;
  21579. }
  21580. function moduleDeclToScope(ctx, node, parentScope) {
  21581. if (node._resolvedChildScope) {
  21582. return node._resolvedChildScope;
  21583. }
  21584. const scope = createChildScope(parentScope);
  21585. if (node.body.type === "TSModuleDeclaration") {
  21586. const decl = node.body;
  21587. decl._ownerScope = scope;
  21588. const id = getId(decl.id);
  21589. scope.types[id] = scope.exportedTypes[id] = decl;
  21590. } else {
  21591. recordTypes(ctx, node.body.body, scope);
  21592. }
  21593. return node._resolvedChildScope = scope;
  21594. }
  21595. function createChildScope(parentScope) {
  21596. return new TypeScope(
  21597. parentScope.filename,
  21598. parentScope.source,
  21599. parentScope.offset,
  21600. Object.create(parentScope.imports),
  21601. Object.create(parentScope.types),
  21602. Object.create(parentScope.declares)
  21603. );
  21604. }
  21605. const importExportRE = /^Import|^Export/;
  21606. function recordTypes(ctx, body, scope, asGlobal = false) {
  21607. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  21608. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  21609. for (const stmt of body) {
  21610. if (asGlobal) {
  21611. if (isAmbient) {
  21612. if (stmt.declare) {
  21613. recordType(stmt, types, declares);
  21614. }
  21615. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  21616. for (const s of stmt.body.body) {
  21617. if (s.type === "ExportNamedDeclaration") {
  21618. if (s.declaration) {
  21619. recordType(s.declaration, types, declares);
  21620. } else if (s.source) {
  21621. const sourceScope = importSourceToScope(
  21622. ctx,
  21623. s.source,
  21624. scope,
  21625. s.source.value,
  21626. false
  21627. );
  21628. for (const spec of s.specifiers) {
  21629. if (spec.type === "ExportSpecifier") {
  21630. const exported = getId(spec.exported);
  21631. const local = spec.local.name;
  21632. if (sourceScope.exportedTypes[local]) {
  21633. types[exported] = sourceScope.exportedTypes[local];
  21634. }
  21635. if (sourceScope.exportedDeclares[local]) {
  21636. declares[exported] = sourceScope.exportedDeclares[local];
  21637. }
  21638. }
  21639. }
  21640. }
  21641. } else if (s.type === "ExportAllDeclaration" && s.source) {
  21642. const sourceScope = importSourceToScope(
  21643. ctx,
  21644. s.source,
  21645. scope,
  21646. s.source.value,
  21647. false
  21648. );
  21649. Object.assign(types, sourceScope.exportedTypes);
  21650. Object.assign(declares, sourceScope.exportedDeclares);
  21651. } else {
  21652. recordType(s, types, declares);
  21653. }
  21654. }
  21655. }
  21656. } else {
  21657. recordType(stmt, types, declares);
  21658. }
  21659. }
  21660. if (!asGlobal) {
  21661. for (const stmt of body) {
  21662. if (stmt.type === "ExportNamedDeclaration") {
  21663. if (stmt.declaration) {
  21664. recordType(stmt.declaration, types, declares);
  21665. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  21666. } else {
  21667. for (const spec of stmt.specifiers) {
  21668. if (spec.type === "ExportSpecifier") {
  21669. const local = spec.local.name;
  21670. const exported = getId(spec.exported);
  21671. if (stmt.source) {
  21672. imports[exported] = {
  21673. source: stmt.source.value,
  21674. imported: local
  21675. };
  21676. exportedTypes[exported] = {
  21677. type: "TSTypeReference",
  21678. typeName: {
  21679. type: "Identifier",
  21680. name: local
  21681. },
  21682. _ownerScope: scope
  21683. };
  21684. } else if (types[local]) {
  21685. exportedTypes[exported] = types[local];
  21686. }
  21687. }
  21688. }
  21689. }
  21690. } else if (stmt.type === "ExportAllDeclaration") {
  21691. const sourceScope = importSourceToScope(
  21692. ctx,
  21693. stmt.source,
  21694. scope,
  21695. stmt.source.value
  21696. );
  21697. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  21698. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  21699. if (stmt.declaration.type !== "Identifier") {
  21700. recordType(stmt.declaration, types, declares, "default");
  21701. recordType(
  21702. stmt.declaration,
  21703. exportedTypes,
  21704. exportedDeclares,
  21705. "default"
  21706. );
  21707. } else if (types[stmt.declaration.name]) {
  21708. exportedTypes["default"] = types[stmt.declaration.name];
  21709. }
  21710. }
  21711. }
  21712. }
  21713. for (const key of Object.keys(types)) {
  21714. const node = types[key];
  21715. if (!node._ownerScope) node._ownerScope = scope;
  21716. if (node._ns && !node._ns._ownerScope) node._ns._ownerScope = scope;
  21717. }
  21718. for (const key of Object.keys(declares)) {
  21719. if (!declares[key]._ownerScope) declares[key]._ownerScope = scope;
  21720. }
  21721. }
  21722. function recordType(node, types, declares, overwriteId) {
  21723. switch (node.type) {
  21724. case "TSInterfaceDeclaration":
  21725. case "TSEnumDeclaration":
  21726. case "TSModuleDeclaration": {
  21727. if (node.type === "TSModuleDeclaration" && node.global) {
  21728. const body = node.body;
  21729. for (const s of body.body) {
  21730. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  21731. recordType(s.declaration, types, declares);
  21732. } else {
  21733. recordType(s, types, declares);
  21734. }
  21735. }
  21736. break;
  21737. }
  21738. const id = overwriteId || getId(node.id);
  21739. let existing = types[id];
  21740. if (existing) {
  21741. if (node.type === "TSModuleDeclaration") {
  21742. if (existing.type === "TSModuleDeclaration") {
  21743. mergeNamespaces(existing, node);
  21744. } else {
  21745. attachNamespace(existing, node);
  21746. }
  21747. break;
  21748. }
  21749. if (existing.type === "TSModuleDeclaration") {
  21750. types[id] = node;
  21751. attachNamespace(node, existing);
  21752. break;
  21753. }
  21754. if (existing.type !== node.type) {
  21755. break;
  21756. }
  21757. if (node.type === "TSInterfaceDeclaration") {
  21758. existing.body.body.push(...node.body.body);
  21759. } else {
  21760. existing.members.push(...node.members);
  21761. }
  21762. } else {
  21763. types[id] = node;
  21764. }
  21765. break;
  21766. }
  21767. case "ClassDeclaration":
  21768. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  21769. break;
  21770. case "TSTypeAliasDeclaration":
  21771. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  21772. break;
  21773. case "TSDeclareFunction":
  21774. if (node.id) declares[node.id.name] = node;
  21775. break;
  21776. case "VariableDeclaration": {
  21777. if (node.declare) {
  21778. for (const decl of node.declarations) {
  21779. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  21780. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  21781. }
  21782. }
  21783. }
  21784. break;
  21785. }
  21786. }
  21787. }
  21788. function mergeNamespaces(to, from) {
  21789. const toBody = to.body;
  21790. const fromBody = from.body;
  21791. if (toBody.type === "TSModuleDeclaration") {
  21792. if (fromBody.type === "TSModuleDeclaration") {
  21793. mergeNamespaces(toBody, fromBody);
  21794. } else {
  21795. fromBody.body.push({
  21796. type: "ExportNamedDeclaration",
  21797. declaration: toBody,
  21798. exportKind: "type",
  21799. specifiers: []
  21800. });
  21801. }
  21802. } else if (fromBody.type === "TSModuleDeclaration") {
  21803. toBody.body.push({
  21804. type: "ExportNamedDeclaration",
  21805. declaration: fromBody,
  21806. exportKind: "type",
  21807. specifiers: []
  21808. });
  21809. } else {
  21810. toBody.body.push(...fromBody.body);
  21811. }
  21812. }
  21813. function attachNamespace(to, ns) {
  21814. if (!to._ns) {
  21815. to._ns = ns;
  21816. } else {
  21817. mergeNamespaces(to._ns, ns);
  21818. }
  21819. }
  21820. function recordImports(body) {
  21821. const imports = /* @__PURE__ */ Object.create(null);
  21822. for (const s of body) {
  21823. recordImport(s, imports);
  21824. }
  21825. return imports;
  21826. }
  21827. function recordImport(node, imports) {
  21828. if (node.type !== "ImportDeclaration") {
  21829. return;
  21830. }
  21831. for (const s of node.specifiers) {
  21832. imports[s.local.name] = {
  21833. imported: getImportedName(s),
  21834. source: node.source.value
  21835. };
  21836. }
  21837. }
  21838. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, typeParameters) {
  21839. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  21840. return [UNKNOWN_TYPE];
  21841. }
  21842. const prevSilent = ctx.silentOnExtendsFailure;
  21843. ctx.silentOnExtendsFailure = true;
  21844. try {
  21845. switch (node.type) {
  21846. case "TSStringKeyword":
  21847. return ["String"];
  21848. case "TSNumberKeyword":
  21849. return ["Number"];
  21850. case "TSBooleanKeyword":
  21851. return ["Boolean"];
  21852. case "TSObjectKeyword":
  21853. return ["Object"];
  21854. case "TSNullKeyword":
  21855. return ["null"];
  21856. case "TSTypeLiteral":
  21857. case "TSInterfaceDeclaration": {
  21858. const types = /* @__PURE__ */ new Set();
  21859. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  21860. for (const m of members) {
  21861. if (isKeyOf) {
  21862. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  21863. types.add("Number");
  21864. } else if (m.type === "TSIndexSignature") {
  21865. const annotation = m.parameters[0].typeAnnotation;
  21866. if (annotation && annotation.type !== "Noop") {
  21867. const type = inferRuntimeType(
  21868. ctx,
  21869. annotation.typeAnnotation,
  21870. scope
  21871. )[0];
  21872. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  21873. types.add(type);
  21874. }
  21875. } else {
  21876. types.add("String");
  21877. }
  21878. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  21879. types.add("Function");
  21880. } else {
  21881. types.add("Object");
  21882. }
  21883. }
  21884. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  21885. }
  21886. case "TSPropertySignature":
  21887. if (node.typeAnnotation) {
  21888. return inferRuntimeType(
  21889. ctx,
  21890. node.typeAnnotation.typeAnnotation,
  21891. scope
  21892. );
  21893. }
  21894. break;
  21895. case "TSMethodSignature":
  21896. case "TSFunctionType":
  21897. return ["Function"];
  21898. case "TSArrayType":
  21899. case "TSTupleType":
  21900. return ["Array"];
  21901. case "TSLiteralType":
  21902. switch (node.literal.type) {
  21903. case "StringLiteral":
  21904. return ["String"];
  21905. case "BooleanLiteral":
  21906. return ["Boolean"];
  21907. case "NumericLiteral":
  21908. case "BigIntLiteral":
  21909. return ["Number"];
  21910. default:
  21911. return [UNKNOWN_TYPE];
  21912. }
  21913. case "TSTypeReference": {
  21914. let resolved;
  21915. try {
  21916. resolved = resolveTypeReference(ctx, node, scope);
  21917. } catch {
  21918. }
  21919. if (resolved) {
  21920. if (resolved.type === "TSTypeAliasDeclaration") {
  21921. if (resolved.typeAnnotation.type === "TSFunctionType") {
  21922. return ["Function"];
  21923. }
  21924. if (node.typeParameters) {
  21925. const typeParams = /* @__PURE__ */ Object.create(null);
  21926. if (resolved.typeParameters) {
  21927. resolved.typeParameters.params.forEach((p, i) => {
  21928. typeParams[p.name] = node.typeParameters.params[i];
  21929. });
  21930. }
  21931. return inferRuntimeType(
  21932. ctx,
  21933. resolved.typeAnnotation,
  21934. resolved._ownerScope,
  21935. isKeyOf,
  21936. typeParams
  21937. );
  21938. }
  21939. }
  21940. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  21941. }
  21942. if (node.typeName.type === "Identifier") {
  21943. if (typeParameters && typeParameters[node.typeName.name]) {
  21944. return inferRuntimeType(
  21945. ctx,
  21946. typeParameters[node.typeName.name],
  21947. scope,
  21948. isKeyOf,
  21949. typeParameters
  21950. );
  21951. }
  21952. if (isKeyOf) {
  21953. switch (node.typeName.name) {
  21954. case "String":
  21955. case "Array":
  21956. case "ArrayLike":
  21957. case "Parameters":
  21958. case "ConstructorParameters":
  21959. case "ReadonlyArray":
  21960. return ["String", "Number"];
  21961. // TS built-in utility types
  21962. case "Record":
  21963. case "Partial":
  21964. case "Required":
  21965. case "Readonly":
  21966. if (node.typeParameters && node.typeParameters.params[0]) {
  21967. return inferRuntimeType(
  21968. ctx,
  21969. node.typeParameters.params[0],
  21970. scope,
  21971. true
  21972. );
  21973. }
  21974. break;
  21975. case "Pick":
  21976. case "Extract":
  21977. if (node.typeParameters && node.typeParameters.params[1]) {
  21978. return inferRuntimeType(
  21979. ctx,
  21980. node.typeParameters.params[1],
  21981. scope
  21982. );
  21983. }
  21984. break;
  21985. case "Function":
  21986. case "Object":
  21987. case "Set":
  21988. case "Map":
  21989. case "WeakSet":
  21990. case "WeakMap":
  21991. case "Date":
  21992. case "Promise":
  21993. case "Error":
  21994. case "Uppercase":
  21995. case "Lowercase":
  21996. case "Capitalize":
  21997. case "Uncapitalize":
  21998. case "ReadonlyMap":
  21999. case "ReadonlySet":
  22000. return ["String"];
  22001. }
  22002. } else {
  22003. switch (node.typeName.name) {
  22004. case "Array":
  22005. case "Function":
  22006. case "Object":
  22007. case "Set":
  22008. case "Map":
  22009. case "WeakSet":
  22010. case "WeakMap":
  22011. case "Date":
  22012. case "Promise":
  22013. case "Error":
  22014. return [node.typeName.name];
  22015. // TS built-in utility types
  22016. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  22017. case "Partial":
  22018. case "Required":
  22019. case "Readonly":
  22020. case "Record":
  22021. case "Pick":
  22022. case "Omit":
  22023. case "InstanceType":
  22024. return ["Object"];
  22025. case "Uppercase":
  22026. case "Lowercase":
  22027. case "Capitalize":
  22028. case "Uncapitalize":
  22029. return ["String"];
  22030. case "Parameters":
  22031. case "ConstructorParameters":
  22032. case "ReadonlyArray":
  22033. return ["Array"];
  22034. case "ReadonlyMap":
  22035. return ["Map"];
  22036. case "ReadonlySet":
  22037. return ["Set"];
  22038. // Vue ref wrapper types — handled here so that runtime type
  22039. // inference still works when `vue` types cannot be resolved
  22040. // (e.g. consumed as built artifacts in another package). #14729
  22041. case "Ref":
  22042. case "ShallowRef":
  22043. case "ComputedRef":
  22044. case "WritableComputedRef":
  22045. return ["Object"];
  22046. case "MaybeRef":
  22047. case "MaybeRefOrGetter": {
  22048. const types = /* @__PURE__ */ new Set(["Object"]);
  22049. if (node.typeName.name === "MaybeRefOrGetter") {
  22050. types.add("Function");
  22051. }
  22052. if (node.typeParameters && node.typeParameters.params[0]) {
  22053. for (const t of inferRuntimeType(
  22054. ctx,
  22055. node.typeParameters.params[0],
  22056. scope,
  22057. false,
  22058. typeParameters
  22059. )) {
  22060. types.add(t);
  22061. }
  22062. }
  22063. return Array.from(types);
  22064. }
  22065. case "NonNullable":
  22066. if (node.typeParameters && node.typeParameters.params[0]) {
  22067. return inferRuntimeType(
  22068. ctx,
  22069. node.typeParameters.params[0],
  22070. scope
  22071. ).filter((t) => t !== "null");
  22072. }
  22073. break;
  22074. case "Extract":
  22075. if (node.typeParameters && node.typeParameters.params[1]) {
  22076. return inferRuntimeType(
  22077. ctx,
  22078. node.typeParameters.params[1],
  22079. scope
  22080. );
  22081. }
  22082. break;
  22083. case "Exclude":
  22084. case "OmitThisParameter":
  22085. if (node.typeParameters && node.typeParameters.params[0]) {
  22086. return inferRuntimeType(
  22087. ctx,
  22088. node.typeParameters.params[0],
  22089. scope
  22090. );
  22091. }
  22092. break;
  22093. }
  22094. }
  22095. }
  22096. break;
  22097. }
  22098. case "TSParenthesizedType":
  22099. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  22100. case "TSUnionType":
  22101. return flattenTypes(ctx, node.types, scope, isKeyOf, typeParameters);
  22102. case "TSIntersectionType": {
  22103. return flattenTypes(
  22104. ctx,
  22105. node.types,
  22106. scope,
  22107. isKeyOf,
  22108. typeParameters
  22109. ).filter((t) => t !== UNKNOWN_TYPE);
  22110. }
  22111. case "TSMappedType": {
  22112. const { typeAnnotation, typeParameter } = node;
  22113. if (typeAnnotation && typeAnnotation.type === "TSIndexedAccessType" && typeParameter && typeParameter.constraint && typeParameters) {
  22114. const constraint = typeParameter.constraint;
  22115. if (constraint.type === "TSTypeOperator" && constraint.operator === "keyof" && constraint.typeAnnotation && constraint.typeAnnotation.type === "TSTypeReference" && constraint.typeAnnotation.typeName.type === "Identifier") {
  22116. const typeName = constraint.typeAnnotation.typeName.name;
  22117. const index = typeAnnotation.indexType;
  22118. const obj = typeAnnotation.objectType;
  22119. if (obj && obj.type === "TSTypeReference" && obj.typeName.type === "Identifier" && obj.typeName.name === typeName && index && index.type === "TSTypeReference" && index.typeName.type === "Identifier" && index.typeName.name === typeParameter.name) {
  22120. const targetType = typeParameters[typeName];
  22121. if (targetType) {
  22122. return inferRuntimeType(ctx, targetType, scope);
  22123. }
  22124. }
  22125. }
  22126. }
  22127. return [UNKNOWN_TYPE];
  22128. }
  22129. case "TSEnumDeclaration":
  22130. return inferEnumType(node);
  22131. case "TSSymbolKeyword":
  22132. return ["Symbol"];
  22133. case "TSIndexedAccessType": {
  22134. const types = resolveIndexType(ctx, node, scope);
  22135. return flattenTypes(ctx, types, scope, isKeyOf);
  22136. }
  22137. case "ClassDeclaration":
  22138. return ["Object"];
  22139. case "TSImportType": {
  22140. const sourceScope = importSourceToScope(
  22141. ctx,
  22142. node.argument,
  22143. scope,
  22144. node.argument.value
  22145. );
  22146. const resolved = resolveTypeReference(ctx, node, sourceScope);
  22147. if (resolved) {
  22148. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  22149. }
  22150. break;
  22151. }
  22152. case "TSTypeQuery": {
  22153. const id = node.exprName;
  22154. if (id.type === "Identifier") {
  22155. const matched = scope.declares[id.name];
  22156. if (matched) {
  22157. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  22158. }
  22159. }
  22160. break;
  22161. }
  22162. // e.g. readonly
  22163. case "TSTypeOperator": {
  22164. return inferRuntimeType(
  22165. ctx,
  22166. node.typeAnnotation,
  22167. scope,
  22168. node.operator === "keyof"
  22169. );
  22170. }
  22171. case "TSAnyKeyword": {
  22172. if (isKeyOf) {
  22173. return ["String", "Number", "Symbol"];
  22174. }
  22175. break;
  22176. }
  22177. }
  22178. } catch (e) {
  22179. } finally {
  22180. ctx.silentOnExtendsFailure = prevSilent;
  22181. }
  22182. return [UNKNOWN_TYPE];
  22183. }
  22184. function flattenTypes(ctx, types, scope, isKeyOf = false, typeParameters = void 0) {
  22185. if (types.length === 1) {
  22186. return inferRuntimeType(
  22187. ctx,
  22188. types[0],
  22189. types[0]._ownerScope || scope,
  22190. isKeyOf,
  22191. typeParameters
  22192. );
  22193. }
  22194. return [
  22195. ...new Set(
  22196. [].concat(
  22197. ...types.map(
  22198. (t) => inferRuntimeType(
  22199. ctx,
  22200. t,
  22201. t._ownerScope || scope,
  22202. isKeyOf,
  22203. typeParameters
  22204. )
  22205. )
  22206. )
  22207. )
  22208. ];
  22209. }
  22210. function inferEnumType(node) {
  22211. const types = /* @__PURE__ */ new Set();
  22212. for (const m of node.members) {
  22213. if (m.initializer) {
  22214. switch (m.initializer.type) {
  22215. case "StringLiteral":
  22216. types.add("String");
  22217. break;
  22218. case "NumericLiteral":
  22219. types.add("Number");
  22220. break;
  22221. }
  22222. }
  22223. }
  22224. return types.size ? [...types] : ["Number"];
  22225. }
  22226. function resolveExtractPropTypes({ props }, scope) {
  22227. const res = { props: {} };
  22228. for (const key in props) {
  22229. const raw = props[key];
  22230. res.props[key] = reverseInferType(
  22231. raw.key,
  22232. raw.typeAnnotation.typeAnnotation,
  22233. scope
  22234. );
  22235. }
  22236. return res;
  22237. }
  22238. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  22239. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  22240. const typeType = findStaticPropertyType(node, "type");
  22241. if (typeType) {
  22242. const requiredType = findStaticPropertyType(node, "required");
  22243. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  22244. return reverseInferType(key, typeType, scope, optional2, false);
  22245. }
  22246. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  22247. if (node.typeName.name.endsWith("Constructor")) {
  22248. return createProperty(
  22249. key,
  22250. ctorToType(node.typeName.name),
  22251. scope,
  22252. optional
  22253. );
  22254. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  22255. return createProperty(key, node.typeParameters.params[0], scope, optional);
  22256. }
  22257. }
  22258. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  22259. for (const t of node.typeParameters.params) {
  22260. const inferred = reverseInferType(key, t, scope, optional);
  22261. if (inferred) return inferred;
  22262. }
  22263. }
  22264. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  22265. }
  22266. function ctorToType(ctorType) {
  22267. const ctor = ctorType.slice(0, -11);
  22268. switch (ctor) {
  22269. case "String":
  22270. case "Number":
  22271. case "Boolean":
  22272. return { type: `TS${ctor}Keyword` };
  22273. case "Array":
  22274. case "Function":
  22275. case "Object":
  22276. case "Set":
  22277. case "Map":
  22278. case "WeakSet":
  22279. case "WeakMap":
  22280. case "Date":
  22281. case "Promise":
  22282. return {
  22283. type: "TSTypeReference",
  22284. typeName: { type: "Identifier", name: ctor }
  22285. };
  22286. }
  22287. return { type: `TSNullKeyword` };
  22288. }
  22289. function findStaticPropertyType(node, key) {
  22290. const prop = node.members.find(
  22291. (m) => m.type === "TSPropertySignature" && getStringLiteralKey(m) === key && m.typeAnnotation
  22292. );
  22293. return prop && prop.typeAnnotation.typeAnnotation;
  22294. }
  22295. function resolveReturnType(ctx, arg, scope) {
  22296. var _a;
  22297. let resolved = arg;
  22298. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  22299. resolved = resolveTypeReference(ctx, arg, scope);
  22300. }
  22301. if (!resolved) return;
  22302. if (resolved.type === "TSFunctionType") {
  22303. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  22304. }
  22305. if (resolved.type === "TSDeclareFunction") {
  22306. return resolved.returnType;
  22307. }
  22308. }
  22309. function resolveUnionType(ctx, node, scope) {
  22310. if (node.type === "TSTypeReference") {
  22311. const resolved = resolveTypeReference(ctx, node, scope);
  22312. if (resolved) node = resolved;
  22313. }
  22314. let types;
  22315. if (node.type === "TSUnionType") {
  22316. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  22317. } else {
  22318. types = [node];
  22319. }
  22320. return types;
  22321. }
  22322. const DEFINE_MODEL = "defineModel";
  22323. function processDefineModel(ctx, node, declId) {
  22324. if (!isCallOf(node, DEFINE_MODEL)) {
  22325. return false;
  22326. }
  22327. ctx.hasDefineModelCall = true;
  22328. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  22329. let modelName;
  22330. let options;
  22331. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  22332. const hasName = arg0 && (arg0.type === "StringLiteral" || arg0.type === "TemplateLiteral" && arg0.expressions.length === 0);
  22333. if (hasName) {
  22334. modelName = arg0.type === "StringLiteral" ? arg0.value : arg0.quasis[0].value.cooked;
  22335. options = node.arguments[1];
  22336. } else {
  22337. modelName = "modelValue";
  22338. options = arg0;
  22339. }
  22340. if (ctx.modelDecls[modelName]) {
  22341. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  22342. }
  22343. let optionsString = options && ctx.getString(options);
  22344. let optionsRemoved = !options;
  22345. const runtimeOptionNodes = [];
  22346. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  22347. let removed = 0;
  22348. for (let i = options.properties.length - 1; i >= 0; i--) {
  22349. const p = options.properties[i];
  22350. const next = options.properties[i + 1];
  22351. const start = p.start;
  22352. const end = next ? next.start : options.end - 1;
  22353. if ((p.type === "ObjectProperty" || p.type === "ObjectMethod") && (p.key.type === "Identifier" && (p.key.name === "get" || p.key.name === "set") || p.key.type === "StringLiteral" && (p.key.value === "get" || p.key.value === "set"))) {
  22354. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  22355. } else {
  22356. removed++;
  22357. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  22358. runtimeOptionNodes.push(p);
  22359. }
  22360. }
  22361. if (removed === options.properties.length) {
  22362. optionsRemoved = true;
  22363. ctx.s.remove(
  22364. ctx.startOffset + (hasName ? arg0.end : options.start),
  22365. ctx.startOffset + options.end
  22366. );
  22367. }
  22368. }
  22369. ctx.modelDecls[modelName] = {
  22370. type,
  22371. options: optionsString,
  22372. runtimeOptionNodes,
  22373. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  22374. };
  22375. ctx.bindingMetadata[modelName] = "props";
  22376. ctx.s.overwrite(
  22377. ctx.startOffset + node.callee.start,
  22378. ctx.startOffset + node.callee.end,
  22379. ctx.helper("useModel")
  22380. );
  22381. ctx.s.appendLeft(
  22382. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  22383. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  22384. );
  22385. return true;
  22386. }
  22387. function genModelProps(ctx) {
  22388. if (!ctx.hasDefineModelCall) return;
  22389. const isProd = !!ctx.options.isProd;
  22390. let modelPropsDecl = "";
  22391. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  22392. ctx.modelDecls
  22393. )) {
  22394. let skipCheck = false;
  22395. let codegenOptions = ``;
  22396. let runtimeTypes = type && inferRuntimeType(ctx, type);
  22397. if (runtimeTypes) {
  22398. const hasBoolean = runtimeTypes.includes("Boolean");
  22399. const hasFunction = runtimeTypes.includes("Function");
  22400. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  22401. if (hasUnknownType) {
  22402. if (hasBoolean || hasFunction) {
  22403. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  22404. skipCheck = true;
  22405. } else {
  22406. runtimeTypes = ["null"];
  22407. }
  22408. }
  22409. if (!isProd) {
  22410. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  22411. } else if (hasBoolean || runtimeOptions && hasFunction) {
  22412. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  22413. } else ;
  22414. }
  22415. let decl;
  22416. if (codegenOptions && runtimeOptions) {
  22417. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  22418. } else if (codegenOptions) {
  22419. decl = `{ ${codegenOptions} }`;
  22420. } else if (runtimeOptions) {
  22421. decl = runtimeOptions;
  22422. } else {
  22423. decl = `{}`;
  22424. }
  22425. modelPropsDecl += `
  22426. ${JSON.stringify(name)}: ${decl},`;
  22427. const modifierPropName = JSON.stringify(
  22428. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  22429. );
  22430. modelPropsDecl += `
  22431. ${modifierPropName}: {},`;
  22432. }
  22433. return `{${modelPropsDecl}
  22434. }`;
  22435. }
  22436. const DEFINE_PROPS = "defineProps";
  22437. const WITH_DEFAULTS = "withDefaults";
  22438. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  22439. if (!isCallOf(node, DEFINE_PROPS)) {
  22440. return processWithDefaults(ctx, node, declId);
  22441. }
  22442. if (ctx.hasDefinePropsCall) {
  22443. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  22444. }
  22445. ctx.hasDefinePropsCall = true;
  22446. ctx.propsRuntimeDecl = node.arguments[0];
  22447. if (ctx.propsRuntimeDecl) {
  22448. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  22449. if (!(key in ctx.bindingMetadata)) {
  22450. ctx.bindingMetadata[key] = "props";
  22451. }
  22452. }
  22453. }
  22454. if (node.typeParameters) {
  22455. if (ctx.propsRuntimeDecl) {
  22456. ctx.error(
  22457. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22458. node
  22459. );
  22460. }
  22461. ctx.propsTypeDecl = node.typeParameters.params[0];
  22462. }
  22463. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  22464. processPropsDestructure(ctx, declId);
  22465. }
  22466. ctx.propsCall = node;
  22467. ctx.propsDecl = declId;
  22468. return true;
  22469. }
  22470. function processWithDefaults(ctx, node, declId) {
  22471. if (!isCallOf(node, WITH_DEFAULTS)) {
  22472. return false;
  22473. }
  22474. if (!processDefineProps(
  22475. ctx,
  22476. node.arguments[0],
  22477. declId,
  22478. true
  22479. )) {
  22480. ctx.error(
  22481. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  22482. node.arguments[0] || node
  22483. );
  22484. }
  22485. if (ctx.propsRuntimeDecl) {
  22486. ctx.error(
  22487. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  22488. node
  22489. );
  22490. }
  22491. if (declId && declId.type === "ObjectPattern") {
  22492. ctx.warn(
  22493. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  22494. Reactive destructure will be disabled when using withDefaults().
  22495. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  22496. node.callee
  22497. );
  22498. }
  22499. ctx.propsRuntimeDefaults = node.arguments[1];
  22500. if (!ctx.propsRuntimeDefaults) {
  22501. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  22502. }
  22503. ctx.propsCall = node;
  22504. return true;
  22505. }
  22506. function genRuntimeProps(ctx) {
  22507. let propsDecls;
  22508. if (ctx.propsRuntimeDecl) {
  22509. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  22510. if (ctx.propsDestructureDecl) {
  22511. const defaults = [];
  22512. for (const key in ctx.propsDestructuredBindings) {
  22513. const d = genDestructuredDefaultValue(ctx, key);
  22514. const finalKey = getEscapedPropName(key);
  22515. if (d)
  22516. defaults.push(
  22517. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  22518. );
  22519. }
  22520. if (defaults.length) {
  22521. propsDecls = `/*@__PURE__*/${ctx.helper(
  22522. `mergeDefaults`
  22523. )}(${propsDecls}, {
  22524. ${defaults.join(",\n ")}
  22525. })`;
  22526. }
  22527. }
  22528. } else if (ctx.propsTypeDecl) {
  22529. propsDecls = extractRuntimeProps(ctx);
  22530. }
  22531. const modelsDecls = genModelProps(ctx);
  22532. if (propsDecls && modelsDecls) {
  22533. return `/*@__PURE__*/${ctx.helper(
  22534. "mergeModels"
  22535. )}(${propsDecls}, ${modelsDecls})`;
  22536. } else {
  22537. return modelsDecls || propsDecls;
  22538. }
  22539. }
  22540. function extractRuntimeProps(ctx) {
  22541. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  22542. if (!props.length) {
  22543. return;
  22544. }
  22545. const propStrings = [];
  22546. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  22547. for (const prop of props) {
  22548. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  22549. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  22550. ctx.bindingMetadata[prop.key] = "props";
  22551. }
  22552. }
  22553. let propsDecls = `{
  22554. ${propStrings.join(",\n ")}
  22555. }`;
  22556. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  22557. propsDecls = `/*@__PURE__*/${ctx.helper(
  22558. "mergeDefaults"
  22559. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  22560. }
  22561. return propsDecls;
  22562. }
  22563. function resolveRuntimePropsFromType(ctx, node) {
  22564. const props = [];
  22565. const elements = resolveTypeElements(ctx, node);
  22566. for (const key in elements.props) {
  22567. const e = elements.props[key];
  22568. let type = inferRuntimeType(ctx, e);
  22569. let skipCheck = false;
  22570. if (type.includes(UNKNOWN_TYPE)) {
  22571. if (type.includes("Boolean") || type.includes("Function")) {
  22572. type = type.filter((t) => t !== UNKNOWN_TYPE);
  22573. skipCheck = true;
  22574. } else {
  22575. type = ["null"];
  22576. }
  22577. }
  22578. props.push({
  22579. key,
  22580. required: !e.optional,
  22581. type: type || [`null`],
  22582. skipCheck
  22583. });
  22584. }
  22585. return props;
  22586. }
  22587. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  22588. let defaultString;
  22589. const destructured = genDestructuredDefaultValue(ctx, key, type);
  22590. if (destructured) {
  22591. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  22592. } else if (hasStaticDefaults) {
  22593. const prop = ctx.propsRuntimeDefaults.properties.find(
  22594. (node) => {
  22595. if (node.type === "SpreadElement") return false;
  22596. return resolveObjectKey(node.key, node.computed) === key;
  22597. }
  22598. );
  22599. if (prop) {
  22600. if (prop.type === "ObjectProperty") {
  22601. defaultString = `default: ${ctx.getString(prop.value)}`;
  22602. } else {
  22603. let paramsString = "";
  22604. if (prop.params.length) {
  22605. const start = prop.params[0].start;
  22606. const end = prop.params[prop.params.length - 1].end;
  22607. paramsString = ctx.getString({ start, end });
  22608. }
  22609. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default(${paramsString}) ${ctx.getString(prop.body)}`;
  22610. }
  22611. }
  22612. }
  22613. const finalKey = getEscapedPropName(key);
  22614. if (!ctx.options.isProd) {
  22615. return `${finalKey}: { ${concatStrings([
  22616. `type: ${toRuntimeTypeString(type)}`,
  22617. `required: ${required}`,
  22618. skipCheck && "skipCheck: true",
  22619. defaultString
  22620. ])} }`;
  22621. } else if (type.some(
  22622. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  22623. )) {
  22624. return `${finalKey}: { ${concatStrings([
  22625. `type: ${toRuntimeTypeString(type)}`,
  22626. defaultString
  22627. ])} }`;
  22628. } else {
  22629. if (ctx.isCE) {
  22630. if (defaultString) {
  22631. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  22632. type
  22633. )} }`}`;
  22634. } else {
  22635. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  22636. }
  22637. }
  22638. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  22639. }
  22640. }
  22641. function hasStaticWithDefaults(ctx) {
  22642. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  22643. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  22644. ));
  22645. }
  22646. function genDestructuredDefaultValue(ctx, key, inferredType) {
  22647. const destructured = ctx.propsDestructuredBindings[key];
  22648. const defaultVal = destructured && destructured.default;
  22649. if (defaultVal) {
  22650. const value = ctx.getString(defaultVal);
  22651. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  22652. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  22653. const valueType = inferValueType(unwrapped);
  22654. if (valueType && !inferredType.includes(valueType)) {
  22655. ctx.error(
  22656. `Default value of prop "${key}" does not match declared type.`,
  22657. unwrapped
  22658. );
  22659. }
  22660. }
  22661. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  22662. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  22663. return {
  22664. valueString: needFactoryWrap ? `() => (${value})` : value,
  22665. needSkipFactory
  22666. };
  22667. }
  22668. }
  22669. function inferValueType(node) {
  22670. switch (node.type) {
  22671. case "StringLiteral":
  22672. return "String";
  22673. case "NumericLiteral":
  22674. return "Number";
  22675. case "BooleanLiteral":
  22676. return "Boolean";
  22677. case "ObjectExpression":
  22678. return "Object";
  22679. case "ArrayExpression":
  22680. return "Array";
  22681. case "FunctionExpression":
  22682. case "ArrowFunctionExpression":
  22683. return "Function";
  22684. }
  22685. }
  22686. function processPropsDestructure(ctx, declId) {
  22687. if (ctx.options.propsDestructure === "error") {
  22688. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  22689. } else if (ctx.options.propsDestructure === false) {
  22690. return;
  22691. }
  22692. ctx.propsDestructureDecl = declId;
  22693. const registerBinding = (key, local, defaultValue) => {
  22694. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  22695. if (local !== key) {
  22696. ctx.bindingMetadata[local] = "props-aliased";
  22697. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  22698. }
  22699. };
  22700. for (const prop of declId.properties) {
  22701. if (prop.type === "ObjectProperty") {
  22702. const propKey = resolveObjectKey(prop.key, prop.computed);
  22703. if (!propKey) {
  22704. ctx.error(
  22705. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  22706. prop.key
  22707. );
  22708. }
  22709. if (prop.value.type === "AssignmentPattern") {
  22710. const { left, right } = prop.value;
  22711. if (left.type !== "Identifier") {
  22712. ctx.error(
  22713. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22714. left
  22715. );
  22716. }
  22717. registerBinding(propKey, left.name, right);
  22718. } else if (prop.value.type === "Identifier") {
  22719. registerBinding(propKey, prop.value.name);
  22720. } else {
  22721. ctx.error(
  22722. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22723. prop.value
  22724. );
  22725. }
  22726. } else {
  22727. ctx.propsDestructureRestId = prop.argument.name;
  22728. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  22729. }
  22730. }
  22731. }
  22732. function transformDestructuredProps(ctx, vueImportAliases) {
  22733. if (ctx.options.propsDestructure === false) {
  22734. return;
  22735. }
  22736. const rootScope = /* @__PURE__ */ Object.create(null);
  22737. const scopeStack = [rootScope];
  22738. const functionScopeStack = [rootScope];
  22739. let currentScope = rootScope;
  22740. const excludedIds = /* @__PURE__ */ new WeakSet();
  22741. const parentStack = [];
  22742. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  22743. for (const key in ctx.propsDestructuredBindings) {
  22744. const { local } = ctx.propsDestructuredBindings[key];
  22745. rootScope[local] = true;
  22746. propsLocalToPublicMap[local] = key;
  22747. }
  22748. function pushScope(isFunctionScope = false) {
  22749. const scope = currentScope = Object.create(currentScope);
  22750. scopeStack.push(scope);
  22751. if (isFunctionScope) {
  22752. functionScopeStack.push(scope);
  22753. }
  22754. }
  22755. function popScope(isFunctionScope = false) {
  22756. scopeStack.pop();
  22757. if (isFunctionScope) {
  22758. functionScopeStack.pop();
  22759. }
  22760. currentScope = scopeStack[scopeStack.length - 1] || null;
  22761. }
  22762. function registerLocalBinding(id, scope = currentScope) {
  22763. excludedIds.add(id);
  22764. if (scope) {
  22765. scope[id.name] = false;
  22766. } else {
  22767. ctx.error(
  22768. "registerBinding called without active scope, something is wrong.",
  22769. id
  22770. );
  22771. }
  22772. }
  22773. function walkScope(node, isRoot = false) {
  22774. for (const stmt of node.body) {
  22775. if (stmt.type === "VariableDeclaration") {
  22776. walkVariableDeclaration(stmt, isRoot);
  22777. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  22778. if (stmt.declare || !stmt.id) continue;
  22779. registerLocalBinding(stmt.id);
  22780. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  22781. walkVariableDeclaration(stmt.declaration, isRoot);
  22782. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  22783. walkVariableDeclaration(stmt.body, isRoot);
  22784. }
  22785. }
  22786. }
  22787. function walkVariableDeclaration(stmt, isRoot = false, scope = stmt.kind === "var" ? functionScopeStack[functionScopeStack.length - 1] : currentScope) {
  22788. if (stmt.declare) {
  22789. return;
  22790. }
  22791. for (const decl of stmt.declarations) {
  22792. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  22793. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  22794. if (isDefineProps) {
  22795. excludedIds.add(id);
  22796. } else {
  22797. registerLocalBinding(id, scope);
  22798. }
  22799. }
  22800. }
  22801. }
  22802. function walkFunctionScopeVarDeclarations(scopeNode, isRoot = false) {
  22803. const scope = functionScopeStack[functionScopeStack.length - 1];
  22804. estreeWalker.walk(scopeNode, {
  22805. enter(node, parent) {
  22806. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  22807. return this.skip();
  22808. }
  22809. if (CompilerDOM.isFunctionType(node) || node.type === "ClassDeclaration" || node.type === "ClassExpression") {
  22810. return this.skip();
  22811. }
  22812. if (node.type === "VariableDeclaration" && node.kind === "var") {
  22813. walkVariableDeclaration(node, isRoot && parent === scopeNode, scope);
  22814. }
  22815. }
  22816. });
  22817. }
  22818. function rewriteId(id, parent, parentStack2) {
  22819. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  22820. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  22821. }
  22822. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  22823. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  22824. ctx.s.appendLeft(
  22825. id.end + ctx.startOffset,
  22826. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  22827. );
  22828. }
  22829. } else {
  22830. ctx.s.overwrite(
  22831. id.start + ctx.startOffset,
  22832. id.end + ctx.startOffset,
  22833. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  22834. );
  22835. }
  22836. }
  22837. function checkUsage(node, method, alias = method) {
  22838. if (isCallOf(node, alias)) {
  22839. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22840. if (arg.type === "Identifier" && currentScope[arg.name]) {
  22841. ctx.error(
  22842. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  22843. arg
  22844. );
  22845. }
  22846. }
  22847. }
  22848. const ast = ctx.scriptSetupAst;
  22849. walkFunctionScopeVarDeclarations(ast, true);
  22850. walkScope(ast, true);
  22851. estreeWalker.walk(ast, {
  22852. enter(node, parent) {
  22853. parent && parentStack.push(parent);
  22854. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  22855. return this.skip();
  22856. }
  22857. checkUsage(node, "watch", vueImportAliases.watch);
  22858. checkUsage(node, "toRef", vueImportAliases.toRef);
  22859. if (CompilerDOM.isFunctionType(node)) {
  22860. pushScope(true);
  22861. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  22862. if (node.body.type === "BlockStatement") {
  22863. walkFunctionScopeVarDeclarations(node.body);
  22864. walkScope(node.body);
  22865. }
  22866. return;
  22867. }
  22868. if (node.type === "CatchClause") {
  22869. pushScope();
  22870. if (node.param && node.param.type === "Identifier") {
  22871. registerLocalBinding(node.param);
  22872. }
  22873. walkScope(node.body);
  22874. return;
  22875. }
  22876. if (node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22877. pushScope();
  22878. const varDecl = node.type === "ForStatement" ? node.init : node.left;
  22879. if (varDecl && varDecl.type === "VariableDeclaration") {
  22880. walkVariableDeclaration(varDecl);
  22881. }
  22882. if (node.body.type === "BlockStatement") {
  22883. walkScope(node.body);
  22884. }
  22885. return;
  22886. }
  22887. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  22888. pushScope();
  22889. walkScope(node);
  22890. return;
  22891. }
  22892. if (node.type === "Identifier") {
  22893. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  22894. if (currentScope[node.name]) {
  22895. rewriteId(node, parent, parentStack);
  22896. }
  22897. }
  22898. }
  22899. },
  22900. leave(node, parent) {
  22901. parent && parentStack.pop();
  22902. if (CompilerDOM.isFunctionType(node)) {
  22903. popScope(true);
  22904. } else if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  22905. popScope();
  22906. } else if (node.type === "CatchClause" || node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22907. popScope();
  22908. }
  22909. }
  22910. });
  22911. }
  22912. const DEFINE_EMITS = "defineEmits";
  22913. function processDefineEmits(ctx, node, declId) {
  22914. if (!isCallOf(node, DEFINE_EMITS)) {
  22915. return false;
  22916. }
  22917. if (ctx.hasDefineEmitCall) {
  22918. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  22919. }
  22920. ctx.hasDefineEmitCall = true;
  22921. ctx.emitsRuntimeDecl = node.arguments[0];
  22922. if (node.typeParameters) {
  22923. if (ctx.emitsRuntimeDecl) {
  22924. ctx.error(
  22925. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22926. node
  22927. );
  22928. }
  22929. ctx.emitsTypeDecl = node.typeParameters.params[0];
  22930. }
  22931. ctx.emitDecl = declId;
  22932. return true;
  22933. }
  22934. function genRuntimeEmits(ctx) {
  22935. let emitsDecl = "";
  22936. if (ctx.emitsRuntimeDecl) {
  22937. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  22938. } else if (ctx.emitsTypeDecl) {
  22939. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  22940. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  22941. }
  22942. if (ctx.hasDefineModelCall) {
  22943. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  22944. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  22945. "mergeModels"
  22946. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  22947. }
  22948. return emitsDecl;
  22949. }
  22950. function extractRuntimeEmits(ctx) {
  22951. const emits = /* @__PURE__ */ new Set();
  22952. const node = ctx.emitsTypeDecl;
  22953. if (node.type === "TSFunctionType") {
  22954. extractEventNames(ctx, node.parameters[0], emits);
  22955. return emits;
  22956. }
  22957. const { props, calls } = resolveTypeElements(ctx, node);
  22958. let hasProperty = false;
  22959. for (const key in props) {
  22960. emits.add(key);
  22961. hasProperty = true;
  22962. }
  22963. if (calls) {
  22964. if (hasProperty) {
  22965. ctx.error(
  22966. `defineEmits() type cannot mixed call signature and property syntax.`,
  22967. node
  22968. );
  22969. }
  22970. for (const call of calls) {
  22971. extractEventNames(ctx, call.parameters[0], emits);
  22972. }
  22973. }
  22974. return emits;
  22975. }
  22976. function extractEventNames(ctx, eventName, emits) {
  22977. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  22978. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  22979. for (const type of types) {
  22980. if (type.type === "TSLiteralType") {
  22981. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  22982. emits.add(String(type.literal.value));
  22983. }
  22984. }
  22985. }
  22986. }
  22987. }
  22988. const DEFINE_EXPOSE = "defineExpose";
  22989. function processDefineExpose(ctx, node) {
  22990. if (isCallOf(node, DEFINE_EXPOSE)) {
  22991. if (ctx.hasDefineExposeCall) {
  22992. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  22993. }
  22994. ctx.hasDefineExposeCall = true;
  22995. return true;
  22996. }
  22997. return false;
  22998. }
  22999. const DEFINE_SLOTS = "defineSlots";
  23000. function processDefineSlots(ctx, node, declId) {
  23001. if (!isCallOf(node, DEFINE_SLOTS)) {
  23002. return false;
  23003. }
  23004. if (ctx.hasDefineSlotsCall) {
  23005. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  23006. }
  23007. ctx.hasDefineSlotsCall = true;
  23008. if (node.arguments.length > 0) {
  23009. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  23010. }
  23011. if (declId) {
  23012. ctx.s.overwrite(
  23013. ctx.startOffset + node.start,
  23014. ctx.startOffset + node.end,
  23015. `${ctx.helper("useSlots")}()`
  23016. );
  23017. }
  23018. return true;
  23019. }
  23020. const DEFINE_OPTIONS = "defineOptions";
  23021. function processDefineOptions(ctx, node) {
  23022. if (!isCallOf(node, DEFINE_OPTIONS)) {
  23023. return false;
  23024. }
  23025. if (ctx.hasDefineOptionsCall) {
  23026. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  23027. }
  23028. if (node.typeParameters) {
  23029. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  23030. }
  23031. if (!node.arguments[0]) return true;
  23032. ctx.hasDefineOptionsCall = true;
  23033. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  23034. let propsOption = void 0;
  23035. let emitsOption = void 0;
  23036. let exposeOption = void 0;
  23037. let slotsOption = void 0;
  23038. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  23039. for (const prop of ctx.optionsRuntimeDecl.properties) {
  23040. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  23041. switch (prop.key.name) {
  23042. case "props":
  23043. propsOption = prop;
  23044. break;
  23045. case "emits":
  23046. emitsOption = prop;
  23047. break;
  23048. case "expose":
  23049. exposeOption = prop;
  23050. break;
  23051. case "slots":
  23052. slotsOption = prop;
  23053. break;
  23054. }
  23055. }
  23056. }
  23057. }
  23058. if (propsOption) {
  23059. ctx.error(
  23060. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  23061. propsOption
  23062. );
  23063. }
  23064. if (emitsOption) {
  23065. ctx.error(
  23066. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  23067. emitsOption
  23068. );
  23069. }
  23070. if (exposeOption) {
  23071. ctx.error(
  23072. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  23073. exposeOption
  23074. );
  23075. }
  23076. if (slotsOption) {
  23077. ctx.error(
  23078. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  23079. slotsOption
  23080. );
  23081. }
  23082. return true;
  23083. }
  23084. function processAwait(ctx, node, needSemi, isStatement) {
  23085. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  23086. const startOffset = ctx.startOffset;
  23087. const argumentStr = ctx.descriptor.source.slice(
  23088. argumentStart + startOffset,
  23089. node.argument.end + startOffset
  23090. );
  23091. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  23092. ctx.s.overwrite(
  23093. node.start + startOffset,
  23094. argumentStart + startOffset,
  23095. `${needSemi ? `;` : ``}(
  23096. ([__temp,__restore] = ${ctx.helper(
  23097. `withAsyncContext`
  23098. )}(${containsNestedAwait ? `async ` : ``}() => `
  23099. );
  23100. ctx.s.appendLeft(
  23101. node.end + startOffset,
  23102. `)),
  23103. ${isStatement ? `` : `__temp = `}await __temp,
  23104. __restore()${isStatement ? `` : `,
  23105. __temp`}
  23106. )`
  23107. );
  23108. }
  23109. const MACROS = [
  23110. DEFINE_PROPS,
  23111. DEFINE_EMITS,
  23112. DEFINE_EXPOSE,
  23113. DEFINE_OPTIONS,
  23114. DEFINE_SLOTS,
  23115. DEFINE_MODEL,
  23116. WITH_DEFAULTS
  23117. ];
  23118. function compileScript(sfc, options) {
  23119. var _a, _b, _c;
  23120. if (!options.id) {
  23121. warnOnce(
  23122. `compileScript now requires passing the \`id\` option.
  23123. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  23124. );
  23125. }
  23126. const { script, scriptSetup, source, filename } = sfc;
  23127. const hoistStatic = options.hoistStatic !== false && !script;
  23128. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  23129. const scriptLang = script && script.lang;
  23130. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  23131. const isJSOrTS = isJS(scriptLang, scriptSetupLang) || isTS(scriptLang, scriptSetupLang);
  23132. if (script && scriptSetup && scriptLang !== scriptSetupLang) {
  23133. throw new Error(
  23134. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  23135. );
  23136. }
  23137. if (!scriptSetup) {
  23138. if (!script) {
  23139. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  23140. }
  23141. if (script.lang && !isJSOrTS) {
  23142. return script;
  23143. }
  23144. const ctx2 = new ScriptCompileContext(sfc, options);
  23145. return processNormalScript(ctx2, scopeId);
  23146. }
  23147. if (scriptSetupLang && !isJSOrTS) {
  23148. return scriptSetup;
  23149. }
  23150. const ctx = new ScriptCompileContext(sfc, options);
  23151. const scriptBindings = /* @__PURE__ */ Object.create(null);
  23152. const setupBindings = /* @__PURE__ */ Object.create(null);
  23153. let defaultExport;
  23154. let hasAwait = false;
  23155. let hasInlinedSsrRenderFn = false;
  23156. const startOffset = ctx.startOffset;
  23157. const endOffset = ctx.endOffset;
  23158. const scriptStartOffset = script && script.loc.start.offset;
  23159. const scriptEndOffset = script && script.loc.end.offset;
  23160. function hoistNode(node) {
  23161. const start = node.start + startOffset;
  23162. let end = node.end + startOffset;
  23163. if (node.trailingComments && node.trailingComments.length > 0) {
  23164. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  23165. end = lastCommentNode.end + startOffset;
  23166. }
  23167. while (end <= source.length) {
  23168. if (!/\s/.test(source.charAt(end))) {
  23169. break;
  23170. }
  23171. end++;
  23172. }
  23173. ctx.s.move(start, end, 0);
  23174. }
  23175. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  23176. let isUsedInTemplate = needTemplateUsageCheck;
  23177. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  23178. isUsedInTemplate = isImportUsed(local, sfc);
  23179. }
  23180. ctx.userImports[local] = {
  23181. isType,
  23182. imported,
  23183. local,
  23184. source: source2,
  23185. isFromSetup,
  23186. isUsedInTemplate
  23187. };
  23188. }
  23189. function checkInvalidScopeReference(node, method) {
  23190. if (!node) return;
  23191. CompilerDOM.walkIdentifiers(node, (id) => {
  23192. const binding = setupBindings[id.name];
  23193. if (binding && binding !== "literal-const") {
  23194. ctx.error(
  23195. `\`${method}()\` in <script setup> cannot reference locally declared variables because it will be hoisted outside of the setup() function. If your component options require initialization in the module scope, use a separate normal <script> to export the options instead.`,
  23196. id
  23197. );
  23198. }
  23199. });
  23200. }
  23201. const scriptAst = ctx.scriptAst;
  23202. const scriptSetupAst = ctx.scriptSetupAst;
  23203. if (scriptAst) {
  23204. for (const node of scriptAst.body) {
  23205. if (node.type === "ImportDeclaration") {
  23206. for (const specifier of node.specifiers) {
  23207. const imported = getImportedName(specifier);
  23208. registerUserImport(
  23209. node.source.value,
  23210. specifier.local.name,
  23211. imported,
  23212. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  23213. false,
  23214. !options.inlineTemplate
  23215. );
  23216. }
  23217. }
  23218. }
  23219. }
  23220. for (const node of scriptSetupAst.body) {
  23221. if (node.type === "ImportDeclaration") {
  23222. hoistNode(node);
  23223. let removed = 0;
  23224. const removeSpecifier = (i) => {
  23225. const removeLeft = i > removed;
  23226. removed++;
  23227. const current = node.specifiers[i];
  23228. const next = node.specifiers[i + 1];
  23229. ctx.s.remove(
  23230. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  23231. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  23232. );
  23233. };
  23234. for (let i = 0; i < node.specifiers.length; i++) {
  23235. const specifier = node.specifiers[i];
  23236. const local = specifier.local.name;
  23237. const imported = getImportedName(specifier);
  23238. const source2 = node.source.value;
  23239. const existing = ctx.userImports[local];
  23240. if (source2 === "vue" && MACROS.includes(imported)) {
  23241. if (local === imported) {
  23242. warnOnce(
  23243. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  23244. );
  23245. } else {
  23246. ctx.error(
  23247. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  23248. specifier
  23249. );
  23250. }
  23251. removeSpecifier(i);
  23252. } else if (existing) {
  23253. if (existing.source === source2 && existing.imported === imported) {
  23254. removeSpecifier(i);
  23255. } else {
  23256. ctx.error(
  23257. `different imports aliased to same local name.`,
  23258. specifier
  23259. );
  23260. }
  23261. } else {
  23262. registerUserImport(
  23263. source2,
  23264. local,
  23265. imported,
  23266. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  23267. true,
  23268. !options.inlineTemplate
  23269. );
  23270. }
  23271. }
  23272. if (node.specifiers.length && removed === node.specifiers.length) {
  23273. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23274. }
  23275. }
  23276. }
  23277. const vueImportAliases = {};
  23278. for (const key in ctx.userImports) {
  23279. const { source: source2, imported, local } = ctx.userImports[key];
  23280. if (source2 === "vue") vueImportAliases[imported] = local;
  23281. }
  23282. if (script && scriptAst) {
  23283. for (const node of scriptAst.body) {
  23284. if (node.type === "ExportDefaultDeclaration") {
  23285. defaultExport = node;
  23286. let optionProperties;
  23287. if (defaultExport.declaration.type === "ObjectExpression") {
  23288. optionProperties = defaultExport.declaration.properties;
  23289. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  23290. optionProperties = defaultExport.declaration.arguments[0].properties;
  23291. }
  23292. if (optionProperties) {
  23293. for (const p of optionProperties) {
  23294. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  23295. ctx.hasDefaultExportName = true;
  23296. }
  23297. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  23298. ctx.hasDefaultExportRender = true;
  23299. }
  23300. }
  23301. }
  23302. const start = node.start + scriptStartOffset;
  23303. const end = node.declaration.start + scriptStartOffset;
  23304. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  23305. } else if (node.type === "ExportNamedDeclaration") {
  23306. const defaultSpecifier = node.specifiers.find(
  23307. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  23308. );
  23309. if (defaultSpecifier) {
  23310. defaultExport = node;
  23311. if (node.specifiers.length > 1) {
  23312. ctx.s.remove(
  23313. defaultSpecifier.start + scriptStartOffset,
  23314. defaultSpecifier.end + scriptStartOffset
  23315. );
  23316. } else {
  23317. ctx.s.remove(
  23318. node.start + scriptStartOffset,
  23319. node.end + scriptStartOffset
  23320. );
  23321. }
  23322. if (node.source) {
  23323. ctx.s.prepend(
  23324. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  23325. `
  23326. );
  23327. } else {
  23328. ctx.s.appendLeft(
  23329. scriptEndOffset,
  23330. `
  23331. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  23332. `
  23333. );
  23334. }
  23335. }
  23336. if (node.declaration) {
  23337. walkDeclaration(
  23338. "script",
  23339. node.declaration,
  23340. scriptBindings,
  23341. vueImportAliases,
  23342. hoistStatic
  23343. );
  23344. }
  23345. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23346. walkDeclaration(
  23347. "script",
  23348. node,
  23349. scriptBindings,
  23350. vueImportAliases,
  23351. hoistStatic
  23352. );
  23353. }
  23354. }
  23355. if (scriptStartOffset > startOffset) {
  23356. if (!/\n$/.test(script.content.trim())) {
  23357. ctx.s.appendLeft(scriptEndOffset, `
  23358. `);
  23359. }
  23360. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  23361. }
  23362. }
  23363. for (const node of scriptSetupAst.body) {
  23364. if (node.type === "ExpressionStatement") {
  23365. const expr = CompilerDOM.unwrapTSNode(node.expression);
  23366. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  23367. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23368. } else if (processDefineExpose(ctx, expr)) {
  23369. const callee = expr.callee;
  23370. ctx.s.overwrite(
  23371. callee.start + startOffset,
  23372. callee.end + startOffset,
  23373. "__expose"
  23374. );
  23375. } else {
  23376. processDefineModel(ctx, expr);
  23377. }
  23378. }
  23379. if (node.type === "VariableDeclaration" && !node.declare) {
  23380. const total = node.declarations.length;
  23381. let left = total;
  23382. let lastNonRemoved;
  23383. for (let i = 0; i < total; i++) {
  23384. const decl = node.declarations[i];
  23385. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  23386. if (init) {
  23387. if (processDefineOptions(ctx, init)) {
  23388. ctx.error(
  23389. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  23390. node
  23391. );
  23392. }
  23393. const isDefineProps = processDefineProps(ctx, init, decl.id);
  23394. if (ctx.propsDestructureRestId) {
  23395. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  23396. }
  23397. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  23398. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  23399. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  23400. if (left === 1) {
  23401. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23402. } else {
  23403. let start = decl.start + startOffset;
  23404. let end = decl.end + startOffset;
  23405. if (i === total - 1) {
  23406. start = node.declarations[lastNonRemoved].end + startOffset;
  23407. } else {
  23408. end = node.declarations[i + 1].start + startOffset;
  23409. }
  23410. ctx.s.remove(start, end);
  23411. left--;
  23412. }
  23413. } else if (isDefineEmits) {
  23414. ctx.s.overwrite(
  23415. startOffset + init.start,
  23416. startOffset + init.end,
  23417. "__emit"
  23418. );
  23419. } else {
  23420. lastNonRemoved = i;
  23421. }
  23422. }
  23423. }
  23424. }
  23425. let isAllLiteral = false;
  23426. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23427. isAllLiteral = walkDeclaration(
  23428. "scriptSetup",
  23429. node,
  23430. setupBindings,
  23431. vueImportAliases,
  23432. hoistStatic,
  23433. !!ctx.propsDestructureDecl
  23434. );
  23435. }
  23436. if (hoistStatic && isAllLiteral) {
  23437. hoistNode(node);
  23438. }
  23439. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  23440. const scope = [scriptSetupAst.body];
  23441. estreeWalker.walk(node, {
  23442. enter(child, parent) {
  23443. if (CompilerDOM.isFunctionType(child)) {
  23444. this.skip();
  23445. }
  23446. if (child.type === "BlockStatement") {
  23447. scope.push(child.body);
  23448. }
  23449. if (child.type === "AwaitExpression") {
  23450. hasAwait = true;
  23451. const currentScope = scope[scope.length - 1];
  23452. const needsSemi = currentScope.some((n, i) => {
  23453. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  23454. });
  23455. processAwait(
  23456. ctx,
  23457. child,
  23458. needsSemi,
  23459. parent.type === "ExpressionStatement"
  23460. );
  23461. }
  23462. },
  23463. exit(node2) {
  23464. if (node2.type === "BlockStatement") scope.pop();
  23465. }
  23466. });
  23467. }
  23468. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  23469. ctx.error(
  23470. `<script setup> cannot contain ES module exports. If you are using a previous version of <script setup>, please consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`,
  23471. node
  23472. );
  23473. }
  23474. if (ctx.isTS) {
  23475. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  23476. if (node.type !== "TSEnumDeclaration") {
  23477. hoistNode(node);
  23478. }
  23479. }
  23480. }
  23481. }
  23482. if (ctx.propsDestructureDecl) {
  23483. transformDestructuredProps(ctx, vueImportAliases);
  23484. }
  23485. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  23486. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  23487. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  23488. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  23489. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  23490. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  23491. for (const node of runtimeOptionNodes) {
  23492. checkInvalidScopeReference(node, DEFINE_MODEL);
  23493. }
  23494. }
  23495. if (script) {
  23496. if (startOffset < scriptStartOffset) {
  23497. ctx.s.remove(0, startOffset);
  23498. ctx.s.remove(endOffset, scriptStartOffset);
  23499. ctx.s.remove(scriptEndOffset, source.length);
  23500. } else {
  23501. ctx.s.remove(0, scriptStartOffset);
  23502. ctx.s.remove(scriptEndOffset, startOffset);
  23503. ctx.s.remove(endOffset, source.length);
  23504. }
  23505. } else {
  23506. ctx.s.remove(0, startOffset);
  23507. ctx.s.remove(endOffset, source.length);
  23508. }
  23509. if (scriptAst) {
  23510. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  23511. }
  23512. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  23513. ctx.userImports
  23514. )) {
  23515. if (isType) continue;
  23516. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  23517. }
  23518. for (const key in scriptBindings) {
  23519. ctx.bindingMetadata[key] = scriptBindings[key];
  23520. }
  23521. for (const key in setupBindings) {
  23522. ctx.bindingMetadata[key] = setupBindings[key];
  23523. }
  23524. if (sfc.template && !sfc.template.src && sfc.template.ast) {
  23525. const vModelIds = resolveTemplateVModelIdentifiers(sfc);
  23526. if (vModelIds.size) {
  23527. const toDemote = /* @__PURE__ */ new Set();
  23528. for (const id of vModelIds) {
  23529. if (setupBindings[id] === "setup-reactive-const") {
  23530. toDemote.add(id);
  23531. }
  23532. }
  23533. if (toDemote.size) {
  23534. for (const node of scriptSetupAst.body) {
  23535. if (node.type === "VariableDeclaration" && node.kind === "const" && !node.declare) {
  23536. const demotedInDecl = [];
  23537. for (const decl of node.declarations) {
  23538. if (decl.id.type === "Identifier" && toDemote.has(decl.id.name)) {
  23539. demotedInDecl.push(decl.id.name);
  23540. }
  23541. }
  23542. if (demotedInDecl.length) {
  23543. ctx.s.overwrite(
  23544. node.start + startOffset,
  23545. node.start + startOffset + "const".length,
  23546. "let"
  23547. );
  23548. for (const id of demotedInDecl) {
  23549. setupBindings[id] = "setup-let";
  23550. ctx.bindingMetadata[id] = "setup-let";
  23551. warnOnce(
  23552. `\`v-model\` cannot update a \`const\` reactive binding \`${id}\`. The compiler has transformed it to \`let\` to make the update work.`
  23553. );
  23554. }
  23555. }
  23556. }
  23557. }
  23558. }
  23559. }
  23560. }
  23561. if (sfc.cssVars.length && // no need to do this when targeting SSR
  23562. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  23563. ctx.helperImports.add(CSS_VARS_HELPER);
  23564. ctx.helperImports.add("unref");
  23565. ctx.s.prependLeft(
  23566. startOffset,
  23567. `
  23568. ${genCssVarsCode(
  23569. sfc.cssVars,
  23570. ctx.bindingMetadata,
  23571. scopeId,
  23572. !!options.isProd
  23573. )}
  23574. `
  23575. );
  23576. }
  23577. let args = `__props`;
  23578. if (ctx.propsTypeDecl) {
  23579. args += `: any`;
  23580. }
  23581. if (ctx.propsDecl) {
  23582. if (ctx.propsDestructureRestId) {
  23583. ctx.s.overwrite(
  23584. startOffset + ctx.propsCall.start,
  23585. startOffset + ctx.propsCall.end,
  23586. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  23587. Object.keys(ctx.propsDestructuredBindings)
  23588. )})`
  23589. );
  23590. ctx.s.overwrite(
  23591. startOffset + ctx.propsDestructureDecl.start,
  23592. startOffset + ctx.propsDestructureDecl.end,
  23593. ctx.propsDestructureRestId
  23594. );
  23595. } else if (!ctx.propsDestructureDecl) {
  23596. ctx.s.overwrite(
  23597. startOffset + ctx.propsCall.start,
  23598. startOffset + ctx.propsCall.end,
  23599. "__props"
  23600. );
  23601. }
  23602. }
  23603. if (hasAwait) {
  23604. const any = ctx.isTS ? `: any` : ``;
  23605. ctx.s.prependLeft(startOffset, `
  23606. let __temp${any}, __restore${any}
  23607. `);
  23608. }
  23609. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  23610. if (ctx.emitDecl) {
  23611. destructureElements.push(`emit: __emit`);
  23612. }
  23613. if (destructureElements.length) {
  23614. args += `, { ${destructureElements.join(", ")} }`;
  23615. }
  23616. let templateMap;
  23617. let returned;
  23618. const propsDecl = genRuntimeProps(ctx);
  23619. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  23620. const allBindings = {
  23621. ...scriptBindings,
  23622. ...setupBindings
  23623. };
  23624. for (const key in ctx.userImports) {
  23625. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  23626. allBindings[key] = true;
  23627. }
  23628. }
  23629. returned = `{ `;
  23630. for (const key in allBindings) {
  23631. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  23632. returned += `get ${key}() { return ${key} }, `;
  23633. } else if (ctx.bindingMetadata[key] === "setup-let") {
  23634. const setArg = key === "v" ? `_v` : `v`;
  23635. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  23636. } else {
  23637. returned += `${key}, `;
  23638. }
  23639. }
  23640. returned = returned.replace(/, $/, "") + ` }`;
  23641. } else {
  23642. if (sfc.template && !sfc.template.src) {
  23643. if (options.templateOptions && options.templateOptions.ssr) {
  23644. hasInlinedSsrRenderFn = true;
  23645. }
  23646. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate({
  23647. filename,
  23648. ast: sfc.template.ast,
  23649. source: sfc.template.content,
  23650. inMap: sfc.template.map,
  23651. ...options.templateOptions,
  23652. id: scopeId,
  23653. scoped: sfc.styles.some((s) => s.scoped),
  23654. isProd: options.isProd,
  23655. ssrCssVars: sfc.cssVars,
  23656. compilerOptions: {
  23657. ...options.templateOptions && options.templateOptions.compilerOptions,
  23658. inline: true,
  23659. isTS: ctx.isTS,
  23660. bindingMetadata: ctx.bindingMetadata
  23661. }
  23662. });
  23663. templateMap = map2;
  23664. if (tips.length) {
  23665. tips.forEach(warnOnce);
  23666. }
  23667. const err = errors[0];
  23668. if (typeof err === "string") {
  23669. throw new Error(err);
  23670. } else if (err) {
  23671. if (err.loc) {
  23672. err.message += `
  23673. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  23674. source,
  23675. err.loc.start.offset,
  23676. err.loc.end.offset
  23677. ) + `
  23678. `;
  23679. }
  23680. throw err;
  23681. }
  23682. if (preamble) {
  23683. ctx.s.prepend(preamble);
  23684. }
  23685. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  23686. ctx.helperImports.delete("unref");
  23687. }
  23688. returned = code;
  23689. } else {
  23690. returned = `() => {}`;
  23691. }
  23692. }
  23693. if (!options.inlineTemplate && true) {
  23694. ctx.s.appendRight(
  23695. endOffset,
  23696. `
  23697. const __returned__ = ${returned}
  23698. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  23699. return __returned__
  23700. }
  23701. `
  23702. );
  23703. } else {
  23704. ctx.s.appendRight(endOffset, `
  23705. return ${returned}
  23706. }
  23707. `);
  23708. }
  23709. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  23710. let runtimeOptions = ``;
  23711. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  23712. const match = filename.match(/([^/\\]+)\.\w+$/);
  23713. if (match) {
  23714. runtimeOptions += `
  23715. __name: '${match[1]}',`;
  23716. }
  23717. }
  23718. if (hasInlinedSsrRenderFn) {
  23719. runtimeOptions += `
  23720. __ssrInlineRender: true,`;
  23721. }
  23722. if (propsDecl) runtimeOptions += `
  23723. props: ${propsDecl},`;
  23724. const emitsDecl = genRuntimeEmits(ctx);
  23725. if (emitsDecl) runtimeOptions += `
  23726. emits: ${emitsDecl},`;
  23727. let definedOptions = "";
  23728. if (ctx.optionsRuntimeDecl) {
  23729. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  23730. }
  23731. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  23732. `;
  23733. if (ctx.isTS) {
  23734. const def = (defaultExport ? `
  23735. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  23736. ...${definedOptions},` : "");
  23737. ctx.s.prependLeft(
  23738. startOffset,
  23739. `
  23740. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  23741. `defineComponent`
  23742. )}({${def}${runtimeOptions}
  23743. ${hasAwait ? `async ` : ``}setup(${args}) {
  23744. ${exposeCall}`
  23745. );
  23746. ctx.s.appendRight(endOffset, `})`);
  23747. } else {
  23748. if (defaultExport || definedOptions) {
  23749. ctx.s.prependLeft(
  23750. startOffset,
  23751. `
  23752. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  23753. ${hasAwait ? `async ` : ``}setup(${args}) {
  23754. ${exposeCall}`
  23755. );
  23756. ctx.s.appendRight(endOffset, `})`);
  23757. } else {
  23758. ctx.s.prependLeft(
  23759. startOffset,
  23760. `
  23761. ${genDefaultAs} {${runtimeOptions}
  23762. ${hasAwait ? `async ` : ``}setup(${args}) {
  23763. ${exposeCall}`
  23764. );
  23765. ctx.s.appendRight(endOffset, `}`);
  23766. }
  23767. }
  23768. if (ctx.helperImports.size > 0) {
  23769. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  23770. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  23771. ctx.s.prepend(
  23772. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  23773. `
  23774. );
  23775. }
  23776. const content = ctx.s.toString();
  23777. let map = options.sourceMap !== false ? ctx.s.generateMap({
  23778. source: filename,
  23779. hires: true,
  23780. includeContent: true
  23781. }) : void 0;
  23782. if (templateMap && map) {
  23783. const offset = content.indexOf(returned);
  23784. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  23785. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  23786. }
  23787. return {
  23788. ...scriptSetup,
  23789. bindings: ctx.bindingMetadata,
  23790. imports: ctx.userImports,
  23791. content,
  23792. map,
  23793. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  23794. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  23795. deps: ctx.deps ? [...ctx.deps] : void 0
  23796. };
  23797. }
  23798. function registerBinding(bindings, node, type) {
  23799. bindings[node.name] = type;
  23800. }
  23801. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  23802. let isAllLiteral = false;
  23803. if (node.type === "VariableDeclaration") {
  23804. const isConst = node.kind === "const";
  23805. isAllLiteral = isConst && node.declarations.every(
  23806. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  23807. );
  23808. for (const { id, init: _init } of node.declarations) {
  23809. const init = _init && CompilerDOM.unwrapTSNode(_init);
  23810. const isConstMacroCall = isConst && isCallOf(
  23811. init,
  23812. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  23813. );
  23814. if (id.type === "Identifier") {
  23815. let bindingType;
  23816. const userReactiveBinding = userImportAliases["reactive"];
  23817. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  23818. bindingType = "literal-const";
  23819. } else if (isCallOf(init, userReactiveBinding)) {
  23820. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  23821. } else if (
  23822. // if a declaration is a const literal, we can mark it so that
  23823. // the generated render fn code doesn't need to unref() it
  23824. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  23825. ) {
  23826. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  23827. } else if (isConst) {
  23828. if (isCallOf(
  23829. init,
  23830. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  23831. )) {
  23832. bindingType = "setup-ref";
  23833. } else {
  23834. bindingType = "setup-maybe-ref";
  23835. }
  23836. } else {
  23837. bindingType = "setup-let";
  23838. }
  23839. registerBinding(bindings, id, bindingType);
  23840. } else {
  23841. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  23842. continue;
  23843. }
  23844. if (id.type === "ObjectPattern") {
  23845. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  23846. } else if (id.type === "ArrayPattern") {
  23847. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  23848. }
  23849. }
  23850. }
  23851. } else if (node.type === "TSEnumDeclaration") {
  23852. isAllLiteral = node.members.every(
  23853. (member) => !member.initializer || isStaticNode(member.initializer)
  23854. );
  23855. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  23856. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  23857. bindings[node.id.name] = "setup-const";
  23858. }
  23859. return isAllLiteral;
  23860. }
  23861. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  23862. for (const p of node.properties) {
  23863. if (p.type === "ObjectProperty") {
  23864. if (p.key.type === "Identifier" && p.key === p.value) {
  23865. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23866. registerBinding(bindings, p.key, type);
  23867. } else {
  23868. walkPattern(p.value, bindings, isConst, isDefineCall);
  23869. }
  23870. } else {
  23871. const type = isConst ? "setup-const" : "setup-let";
  23872. registerBinding(bindings, p.argument, type);
  23873. }
  23874. }
  23875. }
  23876. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  23877. for (const e of node.elements) {
  23878. e && walkPattern(e, bindings, isConst, isDefineCall);
  23879. }
  23880. }
  23881. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  23882. if (node.type === "Identifier") {
  23883. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23884. registerBinding(bindings, node, type);
  23885. } else if (node.type === "RestElement") {
  23886. const type = isConst ? "setup-const" : "setup-let";
  23887. registerBinding(bindings, node.argument, type);
  23888. } else if (node.type === "ObjectPattern") {
  23889. walkObjectPattern(node, bindings, isConst);
  23890. } else if (node.type === "ArrayPattern") {
  23891. walkArrayPattern(node, bindings, isConst);
  23892. } else if (node.type === "AssignmentPattern") {
  23893. if (node.left.type === "Identifier") {
  23894. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23895. registerBinding(bindings, node.left, type);
  23896. } else {
  23897. walkPattern(node.left, bindings, isConst);
  23898. }
  23899. }
  23900. }
  23901. function canNeverBeRef(node, userReactiveImport) {
  23902. if (isCallOf(node, userReactiveImport)) {
  23903. return true;
  23904. }
  23905. switch (node.type) {
  23906. case "UnaryExpression":
  23907. case "BinaryExpression":
  23908. case "ArrayExpression":
  23909. case "ObjectExpression":
  23910. case "FunctionExpression":
  23911. case "ArrowFunctionExpression":
  23912. case "UpdateExpression":
  23913. case "ClassExpression":
  23914. case "TaggedTemplateExpression":
  23915. return true;
  23916. case "SequenceExpression":
  23917. return canNeverBeRef(
  23918. node.expressions[node.expressions.length - 1],
  23919. userReactiveImport
  23920. );
  23921. default:
  23922. if (isLiteralNode(node)) {
  23923. return true;
  23924. }
  23925. return false;
  23926. }
  23927. }
  23928. function isStaticNode(node) {
  23929. node = CompilerDOM.unwrapTSNode(node);
  23930. switch (node.type) {
  23931. case "UnaryExpression":
  23932. return isStaticNode(node.argument);
  23933. case "LogicalExpression":
  23934. // 1 > 2
  23935. case "BinaryExpression":
  23936. return isStaticNode(node.left) && isStaticNode(node.right);
  23937. case "ConditionalExpression": {
  23938. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  23939. }
  23940. case "SequenceExpression":
  23941. // (1, 2)
  23942. case "TemplateLiteral":
  23943. return node.expressions.every((expr) => isStaticNode(expr));
  23944. case "ParenthesizedExpression":
  23945. return isStaticNode(node.expression);
  23946. case "StringLiteral":
  23947. case "NumericLiteral":
  23948. case "BooleanLiteral":
  23949. case "NullLiteral":
  23950. case "BigIntLiteral":
  23951. return true;
  23952. }
  23953. return false;
  23954. }
  23955. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  23956. const generator = new sourceMapJs.SourceMapGenerator();
  23957. const addMapping = (map, lineOffset = 0) => {
  23958. const consumer = new sourceMapJs.SourceMapConsumer(map);
  23959. consumer.sources.forEach((sourceFile) => {
  23960. generator._sources.add(sourceFile);
  23961. const sourceContent = consumer.sourceContentFor(sourceFile);
  23962. if (sourceContent != null) {
  23963. generator.setSourceContent(sourceFile, sourceContent);
  23964. }
  23965. });
  23966. consumer.eachMapping((m) => {
  23967. if (m.originalLine == null) return;
  23968. generator.addMapping({
  23969. generated: {
  23970. line: m.generatedLine + lineOffset,
  23971. column: m.generatedColumn
  23972. },
  23973. original: {
  23974. line: m.originalLine,
  23975. column: m.originalColumn
  23976. },
  23977. source: m.source,
  23978. name: m.name
  23979. });
  23980. });
  23981. };
  23982. addMapping(scriptMap);
  23983. addMapping(templateMap, templateLineOffset);
  23984. generator._sourceRoot = scriptMap.sourceRoot;
  23985. generator._file = scriptMap.file;
  23986. return generator.toJSON();
  23987. }
  23988. const version = "3.5.38";
  23989. const parseCache = parseCache$1;
  23990. const errorMessages = {
  23991. ...CompilerDOM.errorMessages,
  23992. ...CompilerDOM.DOMErrorMessages
  23993. };
  23994. const walk = estreeWalker.walk;
  23995. const shouldTransformRef = () => false;
  23996. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  23997. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  23998. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  23999. exports.isStaticProperty = compilerCore.isStaticProperty;
  24000. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  24001. exports.MagicString = MagicString;
  24002. exports.babelParse = parser$2.parse;
  24003. exports.compileScript = compileScript;
  24004. exports.compileStyle = compileStyle;
  24005. exports.compileStyleAsync = compileStyleAsync;
  24006. exports.compileTemplate = compileTemplate;
  24007. exports.errorMessages = errorMessages;
  24008. exports.extractRuntimeEmits = extractRuntimeEmits;
  24009. exports.extractRuntimeProps = extractRuntimeProps;
  24010. exports.inferRuntimeType = inferRuntimeType;
  24011. exports.invalidateTypeCache = invalidateTypeCache;
  24012. exports.parse = parse$1;
  24013. exports.parseCache = parseCache;
  24014. exports.registerTS = registerTS;
  24015. exports.resolveTypeElements = resolveTypeElements;
  24016. exports.rewriteDefault = rewriteDefault;
  24017. exports.rewriteDefaultAST = rewriteDefaultAST;
  24018. exports.shouldTransformRef = shouldTransformRef;
  24019. exports.version = version;
  24020. exports.walk = walk;