Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compiler-sfc.cjs.js 658KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893
  1. /**
  2. * @vue/compiler-sfc v3.4.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 path$3 = require('path');
  12. var shared = require('@vue/shared');
  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$1 = 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. const UNKNOWN_TYPE = "Unknown";
  36. function resolveObjectKey(node, computed) {
  37. switch (node.type) {
  38. case "StringLiteral":
  39. case "NumericLiteral":
  40. return String(node.value);
  41. case "Identifier":
  42. if (!computed) return node.name;
  43. }
  44. return void 0;
  45. }
  46. function concatStrings(strs) {
  47. return strs.filter((s) => !!s).join(", ");
  48. }
  49. function isLiteralNode(node) {
  50. return node.type.endsWith("Literal");
  51. }
  52. function isCallOf(node, test) {
  53. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  54. }
  55. function toRuntimeTypeString(types) {
  56. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  57. }
  58. function getImportedName(specifier) {
  59. if (specifier.type === "ImportSpecifier")
  60. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  61. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  62. return "default";
  63. }
  64. function getId(node) {
  65. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  66. }
  67. const identity = (str) => str;
  68. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  69. const toLowerCase = (str) => str.toLowerCase();
  70. function toFileNameLowerCase(x) {
  71. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  72. }
  73. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  74. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  75. }
  76. const normalize = (path$3.posix || path$3).normalize;
  77. const windowsSlashRE = /\\/g;
  78. function normalizePath(p) {
  79. return normalize(p.replace(windowsSlashRE, "/"));
  80. }
  81. const joinPaths = (path$3.posix || path$3).join;
  82. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  83. function getEscapedPropName(key) {
  84. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  85. }
  86. const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g;
  87. function getEscapedCssVarName(key, doubleEscape) {
  88. return key.replace(
  89. cssVarNameEscapeSymbolsRE,
  90. (s) => doubleEscape ? `\\\\${s}` : `\\${s}`
  91. );
  92. }
  93. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  94. function getDefaultExportFromCjs (x) {
  95. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  96. }
  97. function pad (hash, len) {
  98. while (hash.length < len) {
  99. hash = '0' + hash;
  100. }
  101. return hash;
  102. }
  103. function fold (hash, text) {
  104. var i;
  105. var chr;
  106. var len;
  107. if (text.length === 0) {
  108. return hash;
  109. }
  110. for (i = 0, len = text.length; i < len; i++) {
  111. chr = text.charCodeAt(i);
  112. hash = ((hash << 5) - hash) + chr;
  113. hash |= 0;
  114. }
  115. return hash < 0 ? hash * -2 : hash;
  116. }
  117. function foldObject (hash, o, seen) {
  118. return Object.keys(o).sort().reduce(foldKey, hash);
  119. function foldKey (hash, key) {
  120. return foldValue(hash, o[key], key, seen);
  121. }
  122. }
  123. function foldValue (input, value, key, seen) {
  124. var hash = fold(fold(fold(input, key), toString$1(value)), typeof value);
  125. if (value === null) {
  126. return fold(hash, 'null');
  127. }
  128. if (value === undefined) {
  129. return fold(hash, 'undefined');
  130. }
  131. if (typeof value === 'object' || typeof value === 'function') {
  132. if (seen.indexOf(value) !== -1) {
  133. return fold(hash, '[Circular]' + key);
  134. }
  135. seen.push(value);
  136. var objHash = foldObject(hash, value, seen);
  137. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  138. return objHash;
  139. }
  140. try {
  141. return fold(objHash, String(value.valueOf()))
  142. } catch (err) {
  143. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  144. }
  145. }
  146. return fold(hash, value.toString());
  147. }
  148. function toString$1 (o) {
  149. return Object.prototype.toString.call(o);
  150. }
  151. function sum (o) {
  152. return pad(foldValue(0, o, '', []).toString(16), 8);
  153. }
  154. var hashSum = sum;
  155. var hash$1 = /*@__PURE__*/getDefaultExportFromCjs(hashSum);
  156. const CSS_VARS_HELPER = `useCssVars`;
  157. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  158. return `{
  159. ${vars.map(
  160. (key) => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  161. ).join(",\n ")}
  162. }`;
  163. }
  164. function genVarName(id, raw, isProd, isSSR = false) {
  165. if (isProd) {
  166. return hash$1(id + raw);
  167. } else {
  168. return `${id}-${getEscapedCssVarName(raw, isSSR)}`;
  169. }
  170. }
  171. function normalizeExpression(exp) {
  172. exp = exp.trim();
  173. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  174. return exp.slice(1, -1);
  175. }
  176. return exp;
  177. }
  178. const vBindRE = /v-bind\s*\(/g;
  179. function parseCssVars(sfc) {
  180. const vars = [];
  181. sfc.styles.forEach((style) => {
  182. let match;
  183. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  184. while (match = vBindRE.exec(content)) {
  185. const start = match.index + match[0].length;
  186. const end = lexBinding(content, start);
  187. if (end !== null) {
  188. const variable = normalizeExpression(content.slice(start, end));
  189. if (!vars.includes(variable)) {
  190. vars.push(variable);
  191. }
  192. }
  193. }
  194. });
  195. return vars;
  196. }
  197. function lexBinding(content, start) {
  198. let state = 0 /* inParens */;
  199. let parenDepth = 0;
  200. for (let i = start; i < content.length; i++) {
  201. const char = content.charAt(i);
  202. switch (state) {
  203. case 0 /* inParens */:
  204. if (char === `'`) {
  205. state = 1 /* inSingleQuoteString */;
  206. } else if (char === `"`) {
  207. state = 2 /* inDoubleQuoteString */;
  208. } else if (char === `(`) {
  209. parenDepth++;
  210. } else if (char === `)`) {
  211. if (parenDepth > 0) {
  212. parenDepth--;
  213. } else {
  214. return i;
  215. }
  216. }
  217. break;
  218. case 1 /* inSingleQuoteString */:
  219. if (char === `'`) {
  220. state = 0 /* inParens */;
  221. }
  222. break;
  223. case 2 /* inDoubleQuoteString */:
  224. if (char === `"`) {
  225. state = 0 /* inParens */;
  226. }
  227. break;
  228. }
  229. }
  230. return null;
  231. }
  232. const cssVarsPlugin = (opts) => {
  233. const { id, isProd } = opts;
  234. return {
  235. postcssPlugin: "vue-sfc-vars",
  236. Declaration(decl) {
  237. const value = decl.value;
  238. if (vBindRE.test(value)) {
  239. vBindRE.lastIndex = 0;
  240. let transformed = "";
  241. let lastIndex = 0;
  242. let match;
  243. while (match = vBindRE.exec(value)) {
  244. const start = match.index + match[0].length;
  245. const end = lexBinding(value, start);
  246. if (end !== null) {
  247. const variable = normalizeExpression(value.slice(start, end));
  248. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  249. lastIndex = end + 1;
  250. }
  251. }
  252. decl.value = transformed + value.slice(lastIndex);
  253. }
  254. }
  255. };
  256. };
  257. cssVarsPlugin.postcss = true;
  258. function genCssVarsCode(vars, bindings, id, isProd) {
  259. const varsExp = genCssVarsFromList(vars, id, isProd);
  260. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  261. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  262. prefixIdentifiers: true,
  263. inline: true,
  264. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  265. });
  266. const transformed = CompilerDOM.processExpression(exp, context);
  267. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  268. return typeof c === "string" ? c : c.content;
  269. }).join("");
  270. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  271. }
  272. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  273. return `
  274. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  275. const __injectCSSVars__ = () => {
  276. ${genCssVarsCode(
  277. cssVars,
  278. bindings,
  279. id,
  280. isProd
  281. )}}
  282. const __setup__ = ${defaultVar}.setup
  283. ${defaultVar}.setup = __setup__
  284. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  285. : __injectCSSVars__
  286. `;
  287. }
  288. /**
  289. * @module LRUCache
  290. */
  291. const perf = typeof performance === 'object' &&
  292. performance &&
  293. typeof performance.now === 'function'
  294. ? performance
  295. : Date;
  296. const warned = new Set();
  297. /* c8 ignore start */
  298. const PROCESS = (typeof process === 'object' && !!process ? process : {});
  299. /* c8 ignore start */
  300. const emitWarning = (msg, type, code, fn) => {
  301. typeof PROCESS.emitWarning === 'function'
  302. ? PROCESS.emitWarning(msg, type, code, fn)
  303. : console.error(`[${code}] ${type}: ${msg}`);
  304. };
  305. let AC = globalThis.AbortController;
  306. let AS = globalThis.AbortSignal;
  307. /* c8 ignore start */
  308. if (typeof AC === 'undefined') {
  309. //@ts-ignore
  310. AS = class AbortSignal {
  311. onabort;
  312. _onabort = [];
  313. reason;
  314. aborted = false;
  315. addEventListener(_, fn) {
  316. this._onabort.push(fn);
  317. }
  318. };
  319. //@ts-ignore
  320. AC = class AbortController {
  321. constructor() {
  322. warnACPolyfill();
  323. }
  324. signal = new AS();
  325. abort(reason) {
  326. if (this.signal.aborted)
  327. return;
  328. //@ts-ignore
  329. this.signal.reason = reason;
  330. //@ts-ignore
  331. this.signal.aborted = true;
  332. //@ts-ignore
  333. for (const fn of this.signal._onabort) {
  334. fn(reason);
  335. }
  336. this.signal.onabort?.(reason);
  337. }
  338. };
  339. let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
  340. const warnACPolyfill = () => {
  341. if (!printACPolyfillWarning)
  342. return;
  343. printACPolyfillWarning = false;
  344. emitWarning('AbortController is not defined. If using lru-cache in ' +
  345. 'node 14, load an AbortController polyfill from the ' +
  346. '`node-abort-controller` package. A minimal polyfill is ' +
  347. 'provided for use by LRUCache.fetch(), but it should not be ' +
  348. 'relied upon in other contexts (eg, passing it to other APIs that ' +
  349. 'use AbortController/AbortSignal might have undesirable effects). ' +
  350. 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
  351. };
  352. }
  353. /* c8 ignore stop */
  354. const shouldWarn = (code) => !warned.has(code);
  355. const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
  356. /* c8 ignore start */
  357. // This is a little bit ridiculous, tbh.
  358. // The maximum array length is 2^32-1 or thereabouts on most JS impls.
  359. // And well before that point, you're caching the entire world, I mean,
  360. // that's ~32GB of just integers for the next/prev links, plus whatever
  361. // else to hold that many keys and values. Just filling the memory with
  362. // zeroes at init time is brutal when you get that big.
  363. // But why not be complete?
  364. // Maybe in the future, these limits will have expanded.
  365. const getUintArray = (max) => !isPosInt(max)
  366. ? null
  367. : max <= Math.pow(2, 8)
  368. ? Uint8Array
  369. : max <= Math.pow(2, 16)
  370. ? Uint16Array
  371. : max <= Math.pow(2, 32)
  372. ? Uint32Array
  373. : max <= Number.MAX_SAFE_INTEGER
  374. ? ZeroArray
  375. : null;
  376. /* c8 ignore stop */
  377. class ZeroArray extends Array {
  378. constructor(size) {
  379. super(size);
  380. this.fill(0);
  381. }
  382. }
  383. class Stack {
  384. heap;
  385. length;
  386. // private constructor
  387. static #constructing = false;
  388. static create(max) {
  389. const HeapCls = getUintArray(max);
  390. if (!HeapCls)
  391. return [];
  392. Stack.#constructing = true;
  393. const s = new Stack(max, HeapCls);
  394. Stack.#constructing = false;
  395. return s;
  396. }
  397. constructor(max, HeapCls) {
  398. /* c8 ignore start */
  399. if (!Stack.#constructing) {
  400. throw new TypeError('instantiate Stack using Stack.create(n)');
  401. }
  402. /* c8 ignore stop */
  403. this.heap = new HeapCls(max);
  404. this.length = 0;
  405. }
  406. push(n) {
  407. this.heap[this.length++] = n;
  408. }
  409. pop() {
  410. return this.heap[--this.length];
  411. }
  412. }
  413. /**
  414. * Default export, the thing you're using this module to get.
  415. *
  416. * All properties from the options object (with the exception of
  417. * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
  418. * normal public members. (`max` and `maxBase` are read-only getters.)
  419. * Changing any of these will alter the defaults for subsequent method calls,
  420. * but is otherwise safe.
  421. */
  422. class LRUCache {
  423. // properties coming in from the options of these, only max and maxSize
  424. // really *need* to be protected. The rest can be modified, as they just
  425. // set defaults for various methods.
  426. #max;
  427. #maxSize;
  428. #dispose;
  429. #disposeAfter;
  430. #fetchMethod;
  431. /**
  432. * {@link LRUCache.OptionsBase.ttl}
  433. */
  434. ttl;
  435. /**
  436. * {@link LRUCache.OptionsBase.ttlResolution}
  437. */
  438. ttlResolution;
  439. /**
  440. * {@link LRUCache.OptionsBase.ttlAutopurge}
  441. */
  442. ttlAutopurge;
  443. /**
  444. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  445. */
  446. updateAgeOnGet;
  447. /**
  448. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  449. */
  450. updateAgeOnHas;
  451. /**
  452. * {@link LRUCache.OptionsBase.allowStale}
  453. */
  454. allowStale;
  455. /**
  456. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  457. */
  458. noDisposeOnSet;
  459. /**
  460. * {@link LRUCache.OptionsBase.noUpdateTTL}
  461. */
  462. noUpdateTTL;
  463. /**
  464. * {@link LRUCache.OptionsBase.maxEntrySize}
  465. */
  466. maxEntrySize;
  467. /**
  468. * {@link LRUCache.OptionsBase.sizeCalculation}
  469. */
  470. sizeCalculation;
  471. /**
  472. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  473. */
  474. noDeleteOnFetchRejection;
  475. /**
  476. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  477. */
  478. noDeleteOnStaleGet;
  479. /**
  480. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  481. */
  482. allowStaleOnFetchAbort;
  483. /**
  484. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  485. */
  486. allowStaleOnFetchRejection;
  487. /**
  488. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  489. */
  490. ignoreFetchAbort;
  491. // computed properties
  492. #size;
  493. #calculatedSize;
  494. #keyMap;
  495. #keyList;
  496. #valList;
  497. #next;
  498. #prev;
  499. #head;
  500. #tail;
  501. #free;
  502. #disposed;
  503. #sizes;
  504. #starts;
  505. #ttls;
  506. #hasDispose;
  507. #hasFetchMethod;
  508. #hasDisposeAfter;
  509. /**
  510. * Do not call this method unless you need to inspect the
  511. * inner workings of the cache. If anything returned by this
  512. * object is modified in any way, strange breakage may occur.
  513. *
  514. * These fields are private for a reason!
  515. *
  516. * @internal
  517. */
  518. static unsafeExposeInternals(c) {
  519. return {
  520. // properties
  521. starts: c.#starts,
  522. ttls: c.#ttls,
  523. sizes: c.#sizes,
  524. keyMap: c.#keyMap,
  525. keyList: c.#keyList,
  526. valList: c.#valList,
  527. next: c.#next,
  528. prev: c.#prev,
  529. get head() {
  530. return c.#head;
  531. },
  532. get tail() {
  533. return c.#tail;
  534. },
  535. free: c.#free,
  536. // methods
  537. isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
  538. backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
  539. moveToTail: (index) => c.#moveToTail(index),
  540. indexes: (options) => c.#indexes(options),
  541. rindexes: (options) => c.#rindexes(options),
  542. isStale: (index) => c.#isStale(index),
  543. };
  544. }
  545. // Protected read-only members
  546. /**
  547. * {@link LRUCache.OptionsBase.max} (read-only)
  548. */
  549. get max() {
  550. return this.#max;
  551. }
  552. /**
  553. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  554. */
  555. get maxSize() {
  556. return this.#maxSize;
  557. }
  558. /**
  559. * The total computed size of items in the cache (read-only)
  560. */
  561. get calculatedSize() {
  562. return this.#calculatedSize;
  563. }
  564. /**
  565. * The number of items stored in the cache (read-only)
  566. */
  567. get size() {
  568. return this.#size;
  569. }
  570. /**
  571. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  572. */
  573. get fetchMethod() {
  574. return this.#fetchMethod;
  575. }
  576. /**
  577. * {@link LRUCache.OptionsBase.dispose} (read-only)
  578. */
  579. get dispose() {
  580. return this.#dispose;
  581. }
  582. /**
  583. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  584. */
  585. get disposeAfter() {
  586. return this.#disposeAfter;
  587. }
  588. constructor(options) {
  589. 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;
  590. if (max !== 0 && !isPosInt(max)) {
  591. throw new TypeError('max option must be a nonnegative integer');
  592. }
  593. const UintArray = max ? getUintArray(max) : Array;
  594. if (!UintArray) {
  595. throw new Error('invalid max value: ' + max);
  596. }
  597. this.#max = max;
  598. this.#maxSize = maxSize;
  599. this.maxEntrySize = maxEntrySize || this.#maxSize;
  600. this.sizeCalculation = sizeCalculation;
  601. if (this.sizeCalculation) {
  602. if (!this.#maxSize && !this.maxEntrySize) {
  603. throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
  604. }
  605. if (typeof this.sizeCalculation !== 'function') {
  606. throw new TypeError('sizeCalculation set to non-function');
  607. }
  608. }
  609. if (fetchMethod !== undefined &&
  610. typeof fetchMethod !== 'function') {
  611. throw new TypeError('fetchMethod must be a function if specified');
  612. }
  613. this.#fetchMethod = fetchMethod;
  614. this.#hasFetchMethod = !!fetchMethod;
  615. this.#keyMap = new Map();
  616. this.#keyList = new Array(max).fill(undefined);
  617. this.#valList = new Array(max).fill(undefined);
  618. this.#next = new UintArray(max);
  619. this.#prev = new UintArray(max);
  620. this.#head = 0;
  621. this.#tail = 0;
  622. this.#free = Stack.create(max);
  623. this.#size = 0;
  624. this.#calculatedSize = 0;
  625. if (typeof dispose === 'function') {
  626. this.#dispose = dispose;
  627. }
  628. if (typeof disposeAfter === 'function') {
  629. this.#disposeAfter = disposeAfter;
  630. this.#disposed = [];
  631. }
  632. else {
  633. this.#disposeAfter = undefined;
  634. this.#disposed = undefined;
  635. }
  636. this.#hasDispose = !!this.#dispose;
  637. this.#hasDisposeAfter = !!this.#disposeAfter;
  638. this.noDisposeOnSet = !!noDisposeOnSet;
  639. this.noUpdateTTL = !!noUpdateTTL;
  640. this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
  641. this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
  642. this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
  643. this.ignoreFetchAbort = !!ignoreFetchAbort;
  644. // NB: maxEntrySize is set to maxSize if it's set
  645. if (this.maxEntrySize !== 0) {
  646. if (this.#maxSize !== 0) {
  647. if (!isPosInt(this.#maxSize)) {
  648. throw new TypeError('maxSize must be a positive integer if specified');
  649. }
  650. }
  651. if (!isPosInt(this.maxEntrySize)) {
  652. throw new TypeError('maxEntrySize must be a positive integer if specified');
  653. }
  654. this.#initializeSizeTracking();
  655. }
  656. this.allowStale = !!allowStale;
  657. this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
  658. this.updateAgeOnGet = !!updateAgeOnGet;
  659. this.updateAgeOnHas = !!updateAgeOnHas;
  660. this.ttlResolution =
  661. isPosInt(ttlResolution) || ttlResolution === 0
  662. ? ttlResolution
  663. : 1;
  664. this.ttlAutopurge = !!ttlAutopurge;
  665. this.ttl = ttl || 0;
  666. if (this.ttl) {
  667. if (!isPosInt(this.ttl)) {
  668. throw new TypeError('ttl must be a positive integer if specified');
  669. }
  670. this.#initializeTTLTracking();
  671. }
  672. // do not allow completely unbounded caches
  673. if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
  674. throw new TypeError('At least one of max, maxSize, or ttl is required');
  675. }
  676. if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
  677. const code = 'LRU_CACHE_UNBOUNDED';
  678. if (shouldWarn(code)) {
  679. warned.add(code);
  680. const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
  681. 'result in unbounded memory consumption.';
  682. emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
  683. }
  684. }
  685. }
  686. /**
  687. * Return the remaining TTL time for a given entry key
  688. */
  689. getRemainingTTL(key) {
  690. return this.#keyMap.has(key) ? Infinity : 0;
  691. }
  692. #initializeTTLTracking() {
  693. const ttls = new ZeroArray(this.#max);
  694. const starts = new ZeroArray(this.#max);
  695. this.#ttls = ttls;
  696. this.#starts = starts;
  697. this.#setItemTTL = (index, ttl, start = perf.now()) => {
  698. starts[index] = ttl !== 0 ? start : 0;
  699. ttls[index] = ttl;
  700. if (ttl !== 0 && this.ttlAutopurge) {
  701. const t = setTimeout(() => {
  702. if (this.#isStale(index)) {
  703. this.delete(this.#keyList[index]);
  704. }
  705. }, ttl + 1);
  706. // unref() not supported on all platforms
  707. /* c8 ignore start */
  708. if (t.unref) {
  709. t.unref();
  710. }
  711. /* c8 ignore stop */
  712. }
  713. };
  714. this.#updateItemAge = index => {
  715. starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  716. };
  717. this.#statusTTL = (status, index) => {
  718. if (ttls[index]) {
  719. const ttl = ttls[index];
  720. const start = starts[index];
  721. /* c8 ignore next */
  722. if (!ttl || !start)
  723. return;
  724. status.ttl = ttl;
  725. status.start = start;
  726. status.now = cachedNow || getNow();
  727. const age = status.now - start;
  728. status.remainingTTL = ttl - age;
  729. }
  730. };
  731. // debounce calls to perf.now() to 1s so we're not hitting
  732. // that costly call repeatedly.
  733. let cachedNow = 0;
  734. const getNow = () => {
  735. const n = perf.now();
  736. if (this.ttlResolution > 0) {
  737. cachedNow = n;
  738. const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
  739. // not available on all platforms
  740. /* c8 ignore start */
  741. if (t.unref) {
  742. t.unref();
  743. }
  744. /* c8 ignore stop */
  745. }
  746. return n;
  747. };
  748. this.getRemainingTTL = key => {
  749. const index = this.#keyMap.get(key);
  750. if (index === undefined) {
  751. return 0;
  752. }
  753. const ttl = ttls[index];
  754. const start = starts[index];
  755. if (!ttl || !start) {
  756. return Infinity;
  757. }
  758. const age = (cachedNow || getNow()) - start;
  759. return ttl - age;
  760. };
  761. this.#isStale = index => {
  762. const s = starts[index];
  763. const t = ttls[index];
  764. return !!t && !!s && (cachedNow || getNow()) - s > t;
  765. };
  766. }
  767. // conditionally set private methods related to TTL
  768. #updateItemAge = () => { };
  769. #statusTTL = () => { };
  770. #setItemTTL = () => { };
  771. /* c8 ignore stop */
  772. #isStale = () => false;
  773. #initializeSizeTracking() {
  774. const sizes = new ZeroArray(this.#max);
  775. this.#calculatedSize = 0;
  776. this.#sizes = sizes;
  777. this.#removeItemSize = index => {
  778. this.#calculatedSize -= sizes[index];
  779. sizes[index] = 0;
  780. };
  781. this.#requireSize = (k, v, size, sizeCalculation) => {
  782. // provisionally accept background fetches.
  783. // actual value size will be checked when they return.
  784. if (this.#isBackgroundFetch(v)) {
  785. return 0;
  786. }
  787. if (!isPosInt(size)) {
  788. if (sizeCalculation) {
  789. if (typeof sizeCalculation !== 'function') {
  790. throw new TypeError('sizeCalculation must be a function');
  791. }
  792. size = sizeCalculation(v, k);
  793. if (!isPosInt(size)) {
  794. throw new TypeError('sizeCalculation return invalid (expect positive integer)');
  795. }
  796. }
  797. else {
  798. throw new TypeError('invalid size value (must be positive integer). ' +
  799. 'When maxSize or maxEntrySize is used, sizeCalculation ' +
  800. 'or size must be set.');
  801. }
  802. }
  803. return size;
  804. };
  805. this.#addItemSize = (index, size, status) => {
  806. sizes[index] = size;
  807. if (this.#maxSize) {
  808. const maxSize = this.#maxSize - sizes[index];
  809. while (this.#calculatedSize > maxSize) {
  810. this.#evict(true);
  811. }
  812. }
  813. this.#calculatedSize += sizes[index];
  814. if (status) {
  815. status.entrySize = size;
  816. status.totalCalculatedSize = this.#calculatedSize;
  817. }
  818. };
  819. }
  820. #removeItemSize = _i => { };
  821. #addItemSize = (_i, _s, _st) => { };
  822. #requireSize = (_k, _v, size, sizeCalculation) => {
  823. if (size || sizeCalculation) {
  824. throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
  825. }
  826. return 0;
  827. };
  828. *#indexes({ allowStale = this.allowStale } = {}) {
  829. if (this.#size) {
  830. for (let i = this.#tail; true;) {
  831. if (!this.#isValidIndex(i)) {
  832. break;
  833. }
  834. if (allowStale || !this.#isStale(i)) {
  835. yield i;
  836. }
  837. if (i === this.#head) {
  838. break;
  839. }
  840. else {
  841. i = this.#prev[i];
  842. }
  843. }
  844. }
  845. }
  846. *#rindexes({ allowStale = this.allowStale } = {}) {
  847. if (this.#size) {
  848. for (let i = this.#head; true;) {
  849. if (!this.#isValidIndex(i)) {
  850. break;
  851. }
  852. if (allowStale || !this.#isStale(i)) {
  853. yield i;
  854. }
  855. if (i === this.#tail) {
  856. break;
  857. }
  858. else {
  859. i = this.#next[i];
  860. }
  861. }
  862. }
  863. }
  864. #isValidIndex(index) {
  865. return (index !== undefined &&
  866. this.#keyMap.get(this.#keyList[index]) === index);
  867. }
  868. /**
  869. * Return a generator yielding `[key, value]` pairs,
  870. * in order from most recently used to least recently used.
  871. */
  872. *entries() {
  873. for (const i of this.#indexes()) {
  874. if (this.#valList[i] !== undefined &&
  875. this.#keyList[i] !== undefined &&
  876. !this.#isBackgroundFetch(this.#valList[i])) {
  877. yield [this.#keyList[i], this.#valList[i]];
  878. }
  879. }
  880. }
  881. /**
  882. * Inverse order version of {@link LRUCache.entries}
  883. *
  884. * Return a generator yielding `[key, value]` pairs,
  885. * in order from least recently used to most recently used.
  886. */
  887. *rentries() {
  888. for (const i of this.#rindexes()) {
  889. if (this.#valList[i] !== undefined &&
  890. this.#keyList[i] !== undefined &&
  891. !this.#isBackgroundFetch(this.#valList[i])) {
  892. yield [this.#keyList[i], this.#valList[i]];
  893. }
  894. }
  895. }
  896. /**
  897. * Return a generator yielding the keys in the cache,
  898. * in order from most recently used to least recently used.
  899. */
  900. *keys() {
  901. for (const i of this.#indexes()) {
  902. const k = this.#keyList[i];
  903. if (k !== undefined &&
  904. !this.#isBackgroundFetch(this.#valList[i])) {
  905. yield k;
  906. }
  907. }
  908. }
  909. /**
  910. * Inverse order version of {@link LRUCache.keys}
  911. *
  912. * Return a generator yielding the keys in the cache,
  913. * in order from least recently used to most recently used.
  914. */
  915. *rkeys() {
  916. for (const i of this.#rindexes()) {
  917. const k = this.#keyList[i];
  918. if (k !== undefined &&
  919. !this.#isBackgroundFetch(this.#valList[i])) {
  920. yield k;
  921. }
  922. }
  923. }
  924. /**
  925. * Return a generator yielding the values in the cache,
  926. * in order from most recently used to least recently used.
  927. */
  928. *values() {
  929. for (const i of this.#indexes()) {
  930. const v = this.#valList[i];
  931. if (v !== undefined &&
  932. !this.#isBackgroundFetch(this.#valList[i])) {
  933. yield this.#valList[i];
  934. }
  935. }
  936. }
  937. /**
  938. * Inverse order version of {@link LRUCache.values}
  939. *
  940. * Return a generator yielding the values in the cache,
  941. * in order from least recently used to most recently used.
  942. */
  943. *rvalues() {
  944. for (const i of this.#rindexes()) {
  945. const v = this.#valList[i];
  946. if (v !== undefined &&
  947. !this.#isBackgroundFetch(this.#valList[i])) {
  948. yield this.#valList[i];
  949. }
  950. }
  951. }
  952. /**
  953. * Iterating over the cache itself yields the same results as
  954. * {@link LRUCache.entries}
  955. */
  956. [Symbol.iterator]() {
  957. return this.entries();
  958. }
  959. /**
  960. * Find a value for which the supplied fn method returns a truthy value,
  961. * similar to Array.find(). fn is called as fn(value, key, cache).
  962. */
  963. find(fn, getOptions = {}) {
  964. for (const i of this.#indexes()) {
  965. const v = this.#valList[i];
  966. const value = this.#isBackgroundFetch(v)
  967. ? v.__staleWhileFetching
  968. : v;
  969. if (value === undefined)
  970. continue;
  971. if (fn(value, this.#keyList[i], this)) {
  972. return this.get(this.#keyList[i], getOptions);
  973. }
  974. }
  975. }
  976. /**
  977. * Call the supplied function on each item in the cache, in order from
  978. * most recently used to least recently used. fn is called as
  979. * fn(value, key, cache). Does not update age or recenty of use.
  980. * Does not iterate over stale values.
  981. */
  982. forEach(fn, thisp = this) {
  983. for (const i of this.#indexes()) {
  984. const v = this.#valList[i];
  985. const value = this.#isBackgroundFetch(v)
  986. ? v.__staleWhileFetching
  987. : v;
  988. if (value === undefined)
  989. continue;
  990. fn.call(thisp, value, this.#keyList[i], this);
  991. }
  992. }
  993. /**
  994. * The same as {@link LRUCache.forEach} but items are iterated over in
  995. * reverse order. (ie, less recently used items are iterated over first.)
  996. */
  997. rforEach(fn, thisp = this) {
  998. for (const i of this.#rindexes()) {
  999. const v = this.#valList[i];
  1000. const value = this.#isBackgroundFetch(v)
  1001. ? v.__staleWhileFetching
  1002. : v;
  1003. if (value === undefined)
  1004. continue;
  1005. fn.call(thisp, value, this.#keyList[i], this);
  1006. }
  1007. }
  1008. /**
  1009. * Delete any stale entries. Returns true if anything was removed,
  1010. * false otherwise.
  1011. */
  1012. purgeStale() {
  1013. let deleted = false;
  1014. for (const i of this.#rindexes({ allowStale: true })) {
  1015. if (this.#isStale(i)) {
  1016. this.delete(this.#keyList[i]);
  1017. deleted = true;
  1018. }
  1019. }
  1020. return deleted;
  1021. }
  1022. /**
  1023. * Get the extended info about a given entry, to get its value, size, and
  1024. * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a
  1025. * single key. Always returns stale values, if their info is found in the
  1026. * cache, so be sure to check for expired TTLs if relevant.
  1027. */
  1028. info(key) {
  1029. const i = this.#keyMap.get(key);
  1030. if (i === undefined)
  1031. return undefined;
  1032. const v = this.#valList[i];
  1033. const value = this.#isBackgroundFetch(v)
  1034. ? v.__staleWhileFetching
  1035. : v;
  1036. if (value === undefined)
  1037. return undefined;
  1038. const entry = { value };
  1039. if (this.#ttls && this.#starts) {
  1040. const ttl = this.#ttls[i];
  1041. const start = this.#starts[i];
  1042. if (ttl && start) {
  1043. const remain = ttl - (perf.now() - start);
  1044. entry.ttl = remain;
  1045. entry.start = Date.now();
  1046. }
  1047. }
  1048. if (this.#sizes) {
  1049. entry.size = this.#sizes[i];
  1050. }
  1051. return entry;
  1052. }
  1053. /**
  1054. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  1055. * passed to cache.load()
  1056. */
  1057. dump() {
  1058. const arr = [];
  1059. for (const i of this.#indexes({ allowStale: true })) {
  1060. const key = this.#keyList[i];
  1061. const v = this.#valList[i];
  1062. const value = this.#isBackgroundFetch(v)
  1063. ? v.__staleWhileFetching
  1064. : v;
  1065. if (value === undefined || key === undefined)
  1066. continue;
  1067. const entry = { value };
  1068. if (this.#ttls && this.#starts) {
  1069. entry.ttl = this.#ttls[i];
  1070. // always dump the start relative to a portable timestamp
  1071. // it's ok for this to be a bit slow, it's a rare operation.
  1072. const age = perf.now() - this.#starts[i];
  1073. entry.start = Math.floor(Date.now() - age);
  1074. }
  1075. if (this.#sizes) {
  1076. entry.size = this.#sizes[i];
  1077. }
  1078. arr.unshift([key, entry]);
  1079. }
  1080. return arr;
  1081. }
  1082. /**
  1083. * Reset the cache and load in the items in entries in the order listed.
  1084. * Note that the shape of the resulting cache may be different if the
  1085. * same options are not used in both caches.
  1086. */
  1087. load(arr) {
  1088. this.clear();
  1089. for (const [key, entry] of arr) {
  1090. if (entry.start) {
  1091. // entry.start is a portable timestamp, but we may be using
  1092. // node's performance.now(), so calculate the offset, so that
  1093. // we get the intended remaining TTL, no matter how long it's
  1094. // been on ice.
  1095. //
  1096. // it's ok for this to be a bit slow, it's a rare operation.
  1097. const age = Date.now() - entry.start;
  1098. entry.start = perf.now() - age;
  1099. }
  1100. this.set(key, entry.value, entry);
  1101. }
  1102. }
  1103. /**
  1104. * Add a value to the cache.
  1105. *
  1106. * Note: if `undefined` is specified as a value, this is an alias for
  1107. * {@link LRUCache#delete}
  1108. */
  1109. set(k, v, setOptions = {}) {
  1110. if (v === undefined) {
  1111. this.delete(k);
  1112. return this;
  1113. }
  1114. const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
  1115. let { noUpdateTTL = this.noUpdateTTL } = setOptions;
  1116. const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
  1117. // if the item doesn't fit, don't do anything
  1118. // NB: maxEntrySize set to maxSize by default
  1119. if (this.maxEntrySize && size > this.maxEntrySize) {
  1120. if (status) {
  1121. status.set = 'miss';
  1122. status.maxEntrySizeExceeded = true;
  1123. }
  1124. // have to delete, in case something is there already.
  1125. this.delete(k);
  1126. return this;
  1127. }
  1128. let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
  1129. if (index === undefined) {
  1130. // addition
  1131. index = (this.#size === 0
  1132. ? this.#tail
  1133. : this.#free.length !== 0
  1134. ? this.#free.pop()
  1135. : this.#size === this.#max
  1136. ? this.#evict(false)
  1137. : this.#size);
  1138. this.#keyList[index] = k;
  1139. this.#valList[index] = v;
  1140. this.#keyMap.set(k, index);
  1141. this.#next[this.#tail] = index;
  1142. this.#prev[index] = this.#tail;
  1143. this.#tail = index;
  1144. this.#size++;
  1145. this.#addItemSize(index, size, status);
  1146. if (status)
  1147. status.set = 'add';
  1148. noUpdateTTL = false;
  1149. }
  1150. else {
  1151. // update
  1152. this.#moveToTail(index);
  1153. const oldVal = this.#valList[index];
  1154. if (v !== oldVal) {
  1155. if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
  1156. oldVal.__abortController.abort(new Error('replaced'));
  1157. const { __staleWhileFetching: s } = oldVal;
  1158. if (s !== undefined && !noDisposeOnSet) {
  1159. if (this.#hasDispose) {
  1160. this.#dispose?.(s, k, 'set');
  1161. }
  1162. if (this.#hasDisposeAfter) {
  1163. this.#disposed?.push([s, k, 'set']);
  1164. }
  1165. }
  1166. }
  1167. else if (!noDisposeOnSet) {
  1168. if (this.#hasDispose) {
  1169. this.#dispose?.(oldVal, k, 'set');
  1170. }
  1171. if (this.#hasDisposeAfter) {
  1172. this.#disposed?.push([oldVal, k, 'set']);
  1173. }
  1174. }
  1175. this.#removeItemSize(index);
  1176. this.#addItemSize(index, size, status);
  1177. this.#valList[index] = v;
  1178. if (status) {
  1179. status.set = 'replace';
  1180. const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
  1181. ? oldVal.__staleWhileFetching
  1182. : oldVal;
  1183. if (oldValue !== undefined)
  1184. status.oldValue = oldValue;
  1185. }
  1186. }
  1187. else if (status) {
  1188. status.set = 'update';
  1189. }
  1190. }
  1191. if (ttl !== 0 && !this.#ttls) {
  1192. this.#initializeTTLTracking();
  1193. }
  1194. if (this.#ttls) {
  1195. if (!noUpdateTTL) {
  1196. this.#setItemTTL(index, ttl, start);
  1197. }
  1198. if (status)
  1199. this.#statusTTL(status, index);
  1200. }
  1201. if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
  1202. const dt = this.#disposed;
  1203. let task;
  1204. while ((task = dt?.shift())) {
  1205. this.#disposeAfter?.(...task);
  1206. }
  1207. }
  1208. return this;
  1209. }
  1210. /**
  1211. * Evict the least recently used item, returning its value or
  1212. * `undefined` if cache is empty.
  1213. */
  1214. pop() {
  1215. try {
  1216. while (this.#size) {
  1217. const val = this.#valList[this.#head];
  1218. this.#evict(true);
  1219. if (this.#isBackgroundFetch(val)) {
  1220. if (val.__staleWhileFetching) {
  1221. return val.__staleWhileFetching;
  1222. }
  1223. }
  1224. else if (val !== undefined) {
  1225. return val;
  1226. }
  1227. }
  1228. }
  1229. finally {
  1230. if (this.#hasDisposeAfter && this.#disposed) {
  1231. const dt = this.#disposed;
  1232. let task;
  1233. while ((task = dt?.shift())) {
  1234. this.#disposeAfter?.(...task);
  1235. }
  1236. }
  1237. }
  1238. }
  1239. #evict(free) {
  1240. const head = this.#head;
  1241. const k = this.#keyList[head];
  1242. const v = this.#valList[head];
  1243. if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
  1244. v.__abortController.abort(new Error('evicted'));
  1245. }
  1246. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1247. if (this.#hasDispose) {
  1248. this.#dispose?.(v, k, 'evict');
  1249. }
  1250. if (this.#hasDisposeAfter) {
  1251. this.#disposed?.push([v, k, 'evict']);
  1252. }
  1253. }
  1254. this.#removeItemSize(head);
  1255. // if we aren't about to use the index, then null these out
  1256. if (free) {
  1257. this.#keyList[head] = undefined;
  1258. this.#valList[head] = undefined;
  1259. this.#free.push(head);
  1260. }
  1261. if (this.#size === 1) {
  1262. this.#head = this.#tail = 0;
  1263. this.#free.length = 0;
  1264. }
  1265. else {
  1266. this.#head = this.#next[head];
  1267. }
  1268. this.#keyMap.delete(k);
  1269. this.#size--;
  1270. return head;
  1271. }
  1272. /**
  1273. * Check if a key is in the cache, without updating the recency of use.
  1274. * Will return false if the item is stale, even though it is technically
  1275. * in the cache.
  1276. *
  1277. * Will not update item age unless
  1278. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  1279. */
  1280. has(k, hasOptions = {}) {
  1281. const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
  1282. const index = this.#keyMap.get(k);
  1283. if (index !== undefined) {
  1284. const v = this.#valList[index];
  1285. if (this.#isBackgroundFetch(v) &&
  1286. v.__staleWhileFetching === undefined) {
  1287. return false;
  1288. }
  1289. if (!this.#isStale(index)) {
  1290. if (updateAgeOnHas) {
  1291. this.#updateItemAge(index);
  1292. }
  1293. if (status) {
  1294. status.has = 'hit';
  1295. this.#statusTTL(status, index);
  1296. }
  1297. return true;
  1298. }
  1299. else if (status) {
  1300. status.has = 'stale';
  1301. this.#statusTTL(status, index);
  1302. }
  1303. }
  1304. else if (status) {
  1305. status.has = 'miss';
  1306. }
  1307. return false;
  1308. }
  1309. /**
  1310. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  1311. * items.
  1312. *
  1313. * Returns `undefined` if the item is stale, unless
  1314. * {@link LRUCache.OptionsBase.allowStale} is set.
  1315. */
  1316. peek(k, peekOptions = {}) {
  1317. const { allowStale = this.allowStale } = peekOptions;
  1318. const index = this.#keyMap.get(k);
  1319. if (index === undefined ||
  1320. (!allowStale && this.#isStale(index))) {
  1321. return;
  1322. }
  1323. const v = this.#valList[index];
  1324. // either stale and allowed, or forcing a refresh of non-stale value
  1325. return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  1326. }
  1327. #backgroundFetch(k, index, options, context) {
  1328. const v = index === undefined ? undefined : this.#valList[index];
  1329. if (this.#isBackgroundFetch(v)) {
  1330. return v;
  1331. }
  1332. const ac = new AC();
  1333. const { signal } = options;
  1334. // when/if our AC signals, then stop listening to theirs.
  1335. signal?.addEventListener('abort', () => ac.abort(signal.reason), {
  1336. signal: ac.signal,
  1337. });
  1338. const fetchOpts = {
  1339. signal: ac.signal,
  1340. options,
  1341. context,
  1342. };
  1343. const cb = (v, updateCache = false) => {
  1344. const { aborted } = ac.signal;
  1345. const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
  1346. if (options.status) {
  1347. if (aborted && !updateCache) {
  1348. options.status.fetchAborted = true;
  1349. options.status.fetchError = ac.signal.reason;
  1350. if (ignoreAbort)
  1351. options.status.fetchAbortIgnored = true;
  1352. }
  1353. else {
  1354. options.status.fetchResolved = true;
  1355. }
  1356. }
  1357. if (aborted && !ignoreAbort && !updateCache) {
  1358. return fetchFail(ac.signal.reason);
  1359. }
  1360. // either we didn't abort, and are still here, or we did, and ignored
  1361. const bf = p;
  1362. if (this.#valList[index] === p) {
  1363. if (v === undefined) {
  1364. if (bf.__staleWhileFetching) {
  1365. this.#valList[index] = bf.__staleWhileFetching;
  1366. }
  1367. else {
  1368. this.delete(k);
  1369. }
  1370. }
  1371. else {
  1372. if (options.status)
  1373. options.status.fetchUpdated = true;
  1374. this.set(k, v, fetchOpts.options);
  1375. }
  1376. }
  1377. return v;
  1378. };
  1379. const eb = (er) => {
  1380. if (options.status) {
  1381. options.status.fetchRejected = true;
  1382. options.status.fetchError = er;
  1383. }
  1384. return fetchFail(er);
  1385. };
  1386. const fetchFail = (er) => {
  1387. const { aborted } = ac.signal;
  1388. const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
  1389. const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
  1390. const noDelete = allowStale || options.noDeleteOnFetchRejection;
  1391. const bf = p;
  1392. if (this.#valList[index] === p) {
  1393. // if we allow stale on fetch rejections, then we need to ensure that
  1394. // the stale value is not removed from the cache when the fetch fails.
  1395. const del = !noDelete || bf.__staleWhileFetching === undefined;
  1396. if (del) {
  1397. this.delete(k);
  1398. }
  1399. else if (!allowStaleAborted) {
  1400. // still replace the *promise* with the stale value,
  1401. // since we are done with the promise at this point.
  1402. // leave it untouched if we're still waiting for an
  1403. // aborted background fetch that hasn't yet returned.
  1404. this.#valList[index] = bf.__staleWhileFetching;
  1405. }
  1406. }
  1407. if (allowStale) {
  1408. if (options.status && bf.__staleWhileFetching !== undefined) {
  1409. options.status.returnedStale = true;
  1410. }
  1411. return bf.__staleWhileFetching;
  1412. }
  1413. else if (bf.__returned === bf) {
  1414. throw er;
  1415. }
  1416. };
  1417. const pcall = (res, rej) => {
  1418. const fmp = this.#fetchMethod?.(k, v, fetchOpts);
  1419. if (fmp && fmp instanceof Promise) {
  1420. fmp.then(v => res(v === undefined ? undefined : v), rej);
  1421. }
  1422. // ignored, we go until we finish, regardless.
  1423. // defer check until we are actually aborting,
  1424. // so fetchMethod can override.
  1425. ac.signal.addEventListener('abort', () => {
  1426. if (!options.ignoreFetchAbort ||
  1427. options.allowStaleOnFetchAbort) {
  1428. res(undefined);
  1429. // when it eventually resolves, update the cache.
  1430. if (options.allowStaleOnFetchAbort) {
  1431. res = v => cb(v, true);
  1432. }
  1433. }
  1434. });
  1435. };
  1436. if (options.status)
  1437. options.status.fetchDispatched = true;
  1438. const p = new Promise(pcall).then(cb, eb);
  1439. const bf = Object.assign(p, {
  1440. __abortController: ac,
  1441. __staleWhileFetching: v,
  1442. __returned: undefined,
  1443. });
  1444. if (index === undefined) {
  1445. // internal, don't expose status.
  1446. this.set(k, bf, { ...fetchOpts.options, status: undefined });
  1447. index = this.#keyMap.get(k);
  1448. }
  1449. else {
  1450. this.#valList[index] = bf;
  1451. }
  1452. return bf;
  1453. }
  1454. #isBackgroundFetch(p) {
  1455. if (!this.#hasFetchMethod)
  1456. return false;
  1457. const b = p;
  1458. return (!!b &&
  1459. b instanceof Promise &&
  1460. b.hasOwnProperty('__staleWhileFetching') &&
  1461. b.__abortController instanceof AC);
  1462. }
  1463. async fetch(k, fetchOptions = {}) {
  1464. const {
  1465. // get options
  1466. allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
  1467. // set options
  1468. ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
  1469. // fetch exclusive options
  1470. noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
  1471. if (!this.#hasFetchMethod) {
  1472. if (status)
  1473. status.fetch = 'get';
  1474. return this.get(k, {
  1475. allowStale,
  1476. updateAgeOnGet,
  1477. noDeleteOnStaleGet,
  1478. status,
  1479. });
  1480. }
  1481. const options = {
  1482. allowStale,
  1483. updateAgeOnGet,
  1484. noDeleteOnStaleGet,
  1485. ttl,
  1486. noDisposeOnSet,
  1487. size,
  1488. sizeCalculation,
  1489. noUpdateTTL,
  1490. noDeleteOnFetchRejection,
  1491. allowStaleOnFetchRejection,
  1492. allowStaleOnFetchAbort,
  1493. ignoreFetchAbort,
  1494. status,
  1495. signal,
  1496. };
  1497. let index = this.#keyMap.get(k);
  1498. if (index === undefined) {
  1499. if (status)
  1500. status.fetch = 'miss';
  1501. const p = this.#backgroundFetch(k, index, options, context);
  1502. return (p.__returned = p);
  1503. }
  1504. else {
  1505. // in cache, maybe already fetching
  1506. const v = this.#valList[index];
  1507. if (this.#isBackgroundFetch(v)) {
  1508. const stale = allowStale && v.__staleWhileFetching !== undefined;
  1509. if (status) {
  1510. status.fetch = 'inflight';
  1511. if (stale)
  1512. status.returnedStale = true;
  1513. }
  1514. return stale ? v.__staleWhileFetching : (v.__returned = v);
  1515. }
  1516. // if we force a refresh, that means do NOT serve the cached value,
  1517. // unless we are already in the process of refreshing the cache.
  1518. const isStale = this.#isStale(index);
  1519. if (!forceRefresh && !isStale) {
  1520. if (status)
  1521. status.fetch = 'hit';
  1522. this.#moveToTail(index);
  1523. if (updateAgeOnGet) {
  1524. this.#updateItemAge(index);
  1525. }
  1526. if (status)
  1527. this.#statusTTL(status, index);
  1528. return v;
  1529. }
  1530. // ok, it is stale or a forced refresh, and not already fetching.
  1531. // refresh the cache.
  1532. const p = this.#backgroundFetch(k, index, options, context);
  1533. const hasStale = p.__staleWhileFetching !== undefined;
  1534. const staleVal = hasStale && allowStale;
  1535. if (status) {
  1536. status.fetch = isStale ? 'stale' : 'refresh';
  1537. if (staleVal && isStale)
  1538. status.returnedStale = true;
  1539. }
  1540. return staleVal ? p.__staleWhileFetching : (p.__returned = p);
  1541. }
  1542. }
  1543. /**
  1544. * Return a value from the cache. Will update the recency of the cache
  1545. * entry found.
  1546. *
  1547. * If the key is not found, get() will return `undefined`.
  1548. */
  1549. get(k, getOptions = {}) {
  1550. const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
  1551. const index = this.#keyMap.get(k);
  1552. if (index !== undefined) {
  1553. const value = this.#valList[index];
  1554. const fetching = this.#isBackgroundFetch(value);
  1555. if (status)
  1556. this.#statusTTL(status, index);
  1557. if (this.#isStale(index)) {
  1558. if (status)
  1559. status.get = 'stale';
  1560. // delete only if not an in-flight background fetch
  1561. if (!fetching) {
  1562. if (!noDeleteOnStaleGet) {
  1563. this.delete(k);
  1564. }
  1565. if (status && allowStale)
  1566. status.returnedStale = true;
  1567. return allowStale ? value : undefined;
  1568. }
  1569. else {
  1570. if (status &&
  1571. allowStale &&
  1572. value.__staleWhileFetching !== undefined) {
  1573. status.returnedStale = true;
  1574. }
  1575. return allowStale ? value.__staleWhileFetching : undefined;
  1576. }
  1577. }
  1578. else {
  1579. if (status)
  1580. status.get = 'hit';
  1581. // if we're currently fetching it, we don't actually have it yet
  1582. // it's not stale, which means this isn't a staleWhileRefetching.
  1583. // If it's not stale, and fetching, AND has a __staleWhileFetching
  1584. // value, then that means the user fetched with {forceRefresh:true},
  1585. // so it's safe to return that value.
  1586. if (fetching) {
  1587. return value.__staleWhileFetching;
  1588. }
  1589. this.#moveToTail(index);
  1590. if (updateAgeOnGet) {
  1591. this.#updateItemAge(index);
  1592. }
  1593. return value;
  1594. }
  1595. }
  1596. else if (status) {
  1597. status.get = 'miss';
  1598. }
  1599. }
  1600. #connect(p, n) {
  1601. this.#prev[n] = p;
  1602. this.#next[p] = n;
  1603. }
  1604. #moveToTail(index) {
  1605. // if tail already, nothing to do
  1606. // if head, move head to next[index]
  1607. // else
  1608. // move next[prev[index]] to next[index] (head has no prev)
  1609. // move prev[next[index]] to prev[index]
  1610. // prev[index] = tail
  1611. // next[tail] = index
  1612. // tail = index
  1613. if (index !== this.#tail) {
  1614. if (index === this.#head) {
  1615. this.#head = this.#next[index];
  1616. }
  1617. else {
  1618. this.#connect(this.#prev[index], this.#next[index]);
  1619. }
  1620. this.#connect(this.#tail, index);
  1621. this.#tail = index;
  1622. }
  1623. }
  1624. /**
  1625. * Deletes a key out of the cache.
  1626. * Returns true if the key was deleted, false otherwise.
  1627. */
  1628. delete(k) {
  1629. let deleted = false;
  1630. if (this.#size !== 0) {
  1631. const index = this.#keyMap.get(k);
  1632. if (index !== undefined) {
  1633. deleted = true;
  1634. if (this.#size === 1) {
  1635. this.clear();
  1636. }
  1637. else {
  1638. this.#removeItemSize(index);
  1639. const v = this.#valList[index];
  1640. if (this.#isBackgroundFetch(v)) {
  1641. v.__abortController.abort(new Error('deleted'));
  1642. }
  1643. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1644. if (this.#hasDispose) {
  1645. this.#dispose?.(v, k, 'delete');
  1646. }
  1647. if (this.#hasDisposeAfter) {
  1648. this.#disposed?.push([v, k, 'delete']);
  1649. }
  1650. }
  1651. this.#keyMap.delete(k);
  1652. this.#keyList[index] = undefined;
  1653. this.#valList[index] = undefined;
  1654. if (index === this.#tail) {
  1655. this.#tail = this.#prev[index];
  1656. }
  1657. else if (index === this.#head) {
  1658. this.#head = this.#next[index];
  1659. }
  1660. else {
  1661. const pi = this.#prev[index];
  1662. this.#next[pi] = this.#next[index];
  1663. const ni = this.#next[index];
  1664. this.#prev[ni] = this.#prev[index];
  1665. }
  1666. this.#size--;
  1667. this.#free.push(index);
  1668. }
  1669. }
  1670. }
  1671. if (this.#hasDisposeAfter && this.#disposed?.length) {
  1672. const dt = this.#disposed;
  1673. let task;
  1674. while ((task = dt?.shift())) {
  1675. this.#disposeAfter?.(...task);
  1676. }
  1677. }
  1678. return deleted;
  1679. }
  1680. /**
  1681. * Clear the cache entirely, throwing away all values.
  1682. */
  1683. clear() {
  1684. for (const index of this.#rindexes({ allowStale: true })) {
  1685. const v = this.#valList[index];
  1686. if (this.#isBackgroundFetch(v)) {
  1687. v.__abortController.abort(new Error('deleted'));
  1688. }
  1689. else {
  1690. const k = this.#keyList[index];
  1691. if (this.#hasDispose) {
  1692. this.#dispose?.(v, k, 'delete');
  1693. }
  1694. if (this.#hasDisposeAfter) {
  1695. this.#disposed?.push([v, k, 'delete']);
  1696. }
  1697. }
  1698. }
  1699. this.#keyMap.clear();
  1700. this.#valList.fill(undefined);
  1701. this.#keyList.fill(undefined);
  1702. if (this.#ttls && this.#starts) {
  1703. this.#ttls.fill(0);
  1704. this.#starts.fill(0);
  1705. }
  1706. if (this.#sizes) {
  1707. this.#sizes.fill(0);
  1708. }
  1709. this.#head = 0;
  1710. this.#tail = 0;
  1711. this.#free.length = 0;
  1712. this.#calculatedSize = 0;
  1713. this.#size = 0;
  1714. if (this.#hasDisposeAfter && this.#disposed) {
  1715. const dt = this.#disposed;
  1716. let task;
  1717. while ((task = dt?.shift())) {
  1718. this.#disposeAfter?.(...task);
  1719. }
  1720. }
  1721. }
  1722. }
  1723. function createCache(max = 500) {
  1724. return new LRUCache({ max });
  1725. }
  1726. function isImportUsed(local, sfc) {
  1727. return resolveTemplateUsedIdentifiers(sfc).has(local);
  1728. }
  1729. const templateUsageCheckCache = createCache();
  1730. function resolveTemplateUsedIdentifiers(sfc) {
  1731. const { content, ast } = sfc.template;
  1732. const cached = templateUsageCheckCache.get(content);
  1733. if (cached) {
  1734. return cached;
  1735. }
  1736. const ids = /* @__PURE__ */ new Set();
  1737. ast.children.forEach(walk);
  1738. function walk(node) {
  1739. var _a;
  1740. switch (node.type) {
  1741. case 1:
  1742. let tag = node.tag;
  1743. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  1744. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1745. ids.add(shared.camelize(tag));
  1746. ids.add(shared.capitalize(shared.camelize(tag)));
  1747. }
  1748. for (let i = 0; i < node.props.length; i++) {
  1749. const prop = node.props[i];
  1750. if (prop.type === 7) {
  1751. if (!shared.isBuiltInDirective(prop.name)) {
  1752. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1753. }
  1754. if (prop.arg && !prop.arg.isStatic) {
  1755. extractIdentifiers(ids, prop.arg);
  1756. }
  1757. if (prop.name === "for") {
  1758. extractIdentifiers(ids, prop.forParseResult.source);
  1759. } else if (prop.exp) {
  1760. extractIdentifiers(ids, prop.exp);
  1761. } else if (prop.name === "bind" && !prop.exp) {
  1762. ids.add(prop.arg.content);
  1763. }
  1764. }
  1765. if (prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1766. ids.add(prop.value.content);
  1767. }
  1768. }
  1769. node.children.forEach(walk);
  1770. break;
  1771. case 5:
  1772. extractIdentifiers(ids, node.content);
  1773. break;
  1774. }
  1775. }
  1776. templateUsageCheckCache.set(content, ids);
  1777. return ids;
  1778. }
  1779. function extractIdentifiers(ids, node) {
  1780. if (node.ast) {
  1781. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1782. } else if (node.ast === null) {
  1783. ids.add(node.content);
  1784. }
  1785. }
  1786. const DEFAULT_FILENAME = "anonymous.vue";
  1787. const parseCache$1 = createCache();
  1788. function genCacheKey(source, options) {
  1789. var _a;
  1790. return source + JSON.stringify(
  1791. {
  1792. ...options,
  1793. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1794. },
  1795. (_, val) => typeof val === "function" ? val.toString() : val
  1796. );
  1797. }
  1798. function parse$2(source, options = {}) {
  1799. const sourceKey = genCacheKey(source, options);
  1800. const cache = parseCache$1.get(sourceKey);
  1801. if (cache) {
  1802. return cache;
  1803. }
  1804. const {
  1805. sourceMap = true,
  1806. filename = DEFAULT_FILENAME,
  1807. sourceRoot = "",
  1808. pad = false,
  1809. ignoreEmpty = true,
  1810. compiler = CompilerDOM__namespace,
  1811. templateParseOptions = {},
  1812. parseExpressions = true
  1813. } = options;
  1814. const descriptor = {
  1815. filename,
  1816. source,
  1817. template: null,
  1818. script: null,
  1819. scriptSetup: null,
  1820. styles: [],
  1821. customBlocks: [],
  1822. cssVars: [],
  1823. slotted: false,
  1824. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1825. };
  1826. const errors = [];
  1827. const ast = compiler.parse(source, {
  1828. parseMode: "sfc",
  1829. prefixIdentifiers: parseExpressions,
  1830. ...templateParseOptions,
  1831. onError: (e) => {
  1832. errors.push(e);
  1833. }
  1834. });
  1835. ast.children.forEach((node) => {
  1836. if (node.type !== 1) {
  1837. return;
  1838. }
  1839. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1840. return;
  1841. }
  1842. switch (node.tag) {
  1843. case "template":
  1844. if (!descriptor.template) {
  1845. const templateBlock = descriptor.template = createBlock(
  1846. node,
  1847. source,
  1848. false
  1849. );
  1850. if (!templateBlock.attrs.src) {
  1851. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1852. }
  1853. if (templateBlock.attrs.functional) {
  1854. const err = new SyntaxError(
  1855. `<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.`
  1856. );
  1857. err.loc = node.props.find(
  1858. (p) => p.type === 6 && p.name === "functional"
  1859. ).loc;
  1860. errors.push(err);
  1861. }
  1862. } else {
  1863. errors.push(createDuplicateBlockError(node));
  1864. }
  1865. break;
  1866. case "script":
  1867. const scriptBlock = createBlock(node, source, pad);
  1868. const isSetup = !!scriptBlock.attrs.setup;
  1869. if (isSetup && !descriptor.scriptSetup) {
  1870. descriptor.scriptSetup = scriptBlock;
  1871. break;
  1872. }
  1873. if (!isSetup && !descriptor.script) {
  1874. descriptor.script = scriptBlock;
  1875. break;
  1876. }
  1877. errors.push(createDuplicateBlockError(node, isSetup));
  1878. break;
  1879. case "style":
  1880. const styleBlock = createBlock(node, source, pad);
  1881. if (styleBlock.attrs.vars) {
  1882. errors.push(
  1883. new SyntaxError(
  1884. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1885. )
  1886. );
  1887. }
  1888. descriptor.styles.push(styleBlock);
  1889. break;
  1890. default:
  1891. descriptor.customBlocks.push(createBlock(node, source, pad));
  1892. break;
  1893. }
  1894. });
  1895. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1896. errors.push(
  1897. new SyntaxError(
  1898. `At least one <template> or <script> is required in a single file component.`
  1899. )
  1900. );
  1901. }
  1902. if (descriptor.scriptSetup) {
  1903. if (descriptor.scriptSetup.src) {
  1904. errors.push(
  1905. new SyntaxError(
  1906. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1907. )
  1908. );
  1909. descriptor.scriptSetup = null;
  1910. }
  1911. if (descriptor.script && descriptor.script.src) {
  1912. errors.push(
  1913. new SyntaxError(
  1914. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1915. )
  1916. );
  1917. descriptor.script = null;
  1918. }
  1919. }
  1920. let templateColumnOffset = 0;
  1921. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1922. [descriptor.template.content, templateColumnOffset] = dedent(
  1923. descriptor.template.content
  1924. );
  1925. }
  1926. if (sourceMap) {
  1927. const genMap = (block, columnOffset = 0) => {
  1928. if (block && !block.src) {
  1929. block.map = generateSourceMap(
  1930. filename,
  1931. source,
  1932. block.content,
  1933. sourceRoot,
  1934. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1935. columnOffset
  1936. );
  1937. }
  1938. };
  1939. genMap(descriptor.template, templateColumnOffset);
  1940. genMap(descriptor.script);
  1941. descriptor.styles.forEach((s) => genMap(s));
  1942. descriptor.customBlocks.forEach((s) => genMap(s));
  1943. }
  1944. descriptor.cssVars = parseCssVars(descriptor);
  1945. const slottedRE = /(?:::v-|:)slotted\(/;
  1946. descriptor.slotted = descriptor.styles.some(
  1947. (s) => s.scoped && slottedRE.test(s.content)
  1948. );
  1949. const result = {
  1950. descriptor,
  1951. errors
  1952. };
  1953. parseCache$1.set(sourceKey, result);
  1954. return result;
  1955. }
  1956. function createDuplicateBlockError(node, isScriptSetup = false) {
  1957. const err = new SyntaxError(
  1958. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1959. );
  1960. err.loc = node.loc;
  1961. return err;
  1962. }
  1963. function createBlock(node, source, pad) {
  1964. const type = node.tag;
  1965. const loc = node.innerLoc;
  1966. const attrs = {};
  1967. const block = {
  1968. type,
  1969. content: source.slice(loc.start.offset, loc.end.offset),
  1970. loc,
  1971. attrs
  1972. };
  1973. if (pad) {
  1974. block.content = padContent(source, block, pad) + block.content;
  1975. }
  1976. node.props.forEach((p) => {
  1977. if (p.type === 6) {
  1978. const name = p.name;
  1979. attrs[name] = p.value ? p.value.content || true : true;
  1980. if (name === "lang") {
  1981. block.lang = p.value && p.value.content;
  1982. } else if (name === "src") {
  1983. block.src = p.value && p.value.content;
  1984. } else if (type === "style") {
  1985. if (name === "scoped") {
  1986. block.scoped = true;
  1987. } else if (name === "module") {
  1988. block.module = attrs[name];
  1989. }
  1990. } else if (type === "script" && name === "setup") {
  1991. block.setup = attrs.setup;
  1992. }
  1993. }
  1994. });
  1995. return block;
  1996. }
  1997. const splitRE = /\r?\n/g;
  1998. const emptyRE = /^(?:\/\/)?\s*$/;
  1999. const replaceRE = /./g;
  2000. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  2001. const map = new sourceMapJs.SourceMapGenerator({
  2002. file: filename.replace(/\\/g, "/"),
  2003. sourceRoot: sourceRoot.replace(/\\/g, "/")
  2004. });
  2005. map.setSourceContent(filename, source);
  2006. map._sources.add(filename);
  2007. generated.split(splitRE).forEach((line, index) => {
  2008. if (!emptyRE.test(line)) {
  2009. const originalLine = index + 1 + lineOffset;
  2010. const generatedLine = index + 1;
  2011. for (let i = 0; i < line.length; i++) {
  2012. if (!/\s/.test(line[i])) {
  2013. map._mappings.add({
  2014. originalLine,
  2015. originalColumn: i + columnOffset,
  2016. generatedLine,
  2017. generatedColumn: i,
  2018. source: filename,
  2019. name: null
  2020. });
  2021. }
  2022. }
  2023. }
  2024. });
  2025. return map.toJSON();
  2026. }
  2027. function padContent(content, block, pad) {
  2028. content = content.slice(0, block.loc.start.offset);
  2029. if (pad === "space") {
  2030. return content.replace(replaceRE, " ");
  2031. } else {
  2032. const offset = content.split(splitRE).length;
  2033. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  2034. return Array(offset).join(padChar);
  2035. }
  2036. }
  2037. function hasSrc(node) {
  2038. return node.props.some((p) => {
  2039. if (p.type !== 6) {
  2040. return false;
  2041. }
  2042. return p.name === "src";
  2043. });
  2044. }
  2045. function isEmpty(node) {
  2046. for (let i = 0; i < node.children.length; i++) {
  2047. const child = node.children[i];
  2048. if (child.type !== 2 || child.content.trim() !== "") {
  2049. return false;
  2050. }
  2051. }
  2052. return true;
  2053. }
  2054. function hmrShouldReload(prevImports, next) {
  2055. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  2056. return false;
  2057. }
  2058. for (const key in prevImports) {
  2059. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2060. return true;
  2061. }
  2062. }
  2063. return false;
  2064. }
  2065. function dedent(s) {
  2066. const lines = s.split("\n");
  2067. const minIndent = lines.reduce(function(minIndent2, line) {
  2068. var _a, _b;
  2069. if (line.trim() === "") {
  2070. return minIndent2;
  2071. }
  2072. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2073. return Math.min(indent, minIndent2);
  2074. }, Infinity);
  2075. if (minIndent === 0) {
  2076. return [s, minIndent];
  2077. }
  2078. return [
  2079. lines.map(function(line) {
  2080. return line.slice(minIndent);
  2081. }).join("\n"),
  2082. minIndent
  2083. ];
  2084. }
  2085. function isRelativeUrl(url) {
  2086. const firstChar = url.charAt(0);
  2087. return firstChar === "." || firstChar === "~" || firstChar === "@";
  2088. }
  2089. const externalRE = /^(https?:)?\/\//;
  2090. function isExternalUrl(url) {
  2091. return externalRE.test(url);
  2092. }
  2093. const dataUrlRE = /^\s*data:/i;
  2094. function isDataUrl(url) {
  2095. return dataUrlRE.test(url);
  2096. }
  2097. function parseUrl(url) {
  2098. const firstChar = url.charAt(0);
  2099. if (firstChar === "~") {
  2100. const secondChar = url.charAt(1);
  2101. url = url.slice(secondChar === "/" ? 2 : 1);
  2102. }
  2103. return parseUriParts(url);
  2104. }
  2105. function parseUriParts(urlString) {
  2106. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2107. }
  2108. const defaultAssetUrlOptions = {
  2109. base: null,
  2110. includeAbsolute: false,
  2111. tags: {
  2112. video: ["src", "poster"],
  2113. source: ["src"],
  2114. img: ["src"],
  2115. image: ["xlink:href", "href"],
  2116. use: ["xlink:href", "href"]
  2117. }
  2118. };
  2119. const normalizeOptions = (options) => {
  2120. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2121. return {
  2122. ...defaultAssetUrlOptions,
  2123. tags: options
  2124. };
  2125. }
  2126. return {
  2127. ...defaultAssetUrlOptions,
  2128. ...options
  2129. };
  2130. };
  2131. const createAssetUrlTransformWithOptions = (options) => {
  2132. return (node, context) => transformAssetUrl(node, context, options);
  2133. };
  2134. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2135. if (node.type === 1) {
  2136. if (!node.props.length) {
  2137. return;
  2138. }
  2139. const tags = options.tags || defaultAssetUrlOptions.tags;
  2140. const attrs = tags[node.tag];
  2141. const wildCardAttrs = tags["*"];
  2142. if (!attrs && !wildCardAttrs) {
  2143. return;
  2144. }
  2145. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2146. node.props.forEach((attr, index) => {
  2147. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value || isExternalUrl(attr.value.content) || isDataUrl(attr.value.content) || attr.value.content[0] === "#" || !options.includeAbsolute && !isRelativeUrl(attr.value.content)) {
  2148. return;
  2149. }
  2150. const url = parseUrl(attr.value.content);
  2151. if (options.base && attr.value.content[0] === ".") {
  2152. const base = parseUrl(options.base);
  2153. const protocol = base.protocol || "";
  2154. const host = base.host ? protocol + "//" + base.host : "";
  2155. const basePath = base.path || "/";
  2156. attr.value.content = host + (path$3.posix || path$3).join(basePath, url.path + (url.hash || ""));
  2157. return;
  2158. }
  2159. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2160. node.props[index] = {
  2161. type: 7,
  2162. name: "bind",
  2163. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2164. exp,
  2165. modifiers: [],
  2166. loc: attr.loc
  2167. };
  2168. });
  2169. }
  2170. };
  2171. function getImportsExpressionExp(path2, hash, loc, context) {
  2172. if (path2) {
  2173. let name;
  2174. let exp;
  2175. const existingIndex = context.imports.findIndex((i) => i.path === path2);
  2176. if (existingIndex > -1) {
  2177. name = `_imports_${existingIndex}`;
  2178. exp = context.imports[existingIndex].exp;
  2179. } else {
  2180. name = `_imports_${context.imports.length}`;
  2181. exp = compilerCore.createSimpleExpression(
  2182. name,
  2183. false,
  2184. loc,
  2185. 3
  2186. );
  2187. context.imports.push({
  2188. exp,
  2189. path: decodeURIComponent(path2)
  2190. });
  2191. }
  2192. if (!hash) {
  2193. return exp;
  2194. }
  2195. const hashExp = `${name} + '${hash}'`;
  2196. const finalExp = compilerCore.createSimpleExpression(
  2197. hashExp,
  2198. false,
  2199. loc,
  2200. 3
  2201. );
  2202. if (!context.hoistStatic) {
  2203. return finalExp;
  2204. }
  2205. const existingHoistIndex = context.hoists.findIndex((h) => {
  2206. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2207. });
  2208. if (existingHoistIndex > -1) {
  2209. return compilerCore.createSimpleExpression(
  2210. `_hoisted_${existingHoistIndex + 1}`,
  2211. false,
  2212. loc,
  2213. 3
  2214. );
  2215. }
  2216. return context.hoist(finalExp);
  2217. } else {
  2218. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2219. }
  2220. }
  2221. const srcsetTags = ["img", "source"];
  2222. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2223. const createSrcsetTransformWithOptions = (options) => {
  2224. return (node, context) => transformSrcset(node, context, options);
  2225. };
  2226. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2227. if (node.type === 1) {
  2228. if (srcsetTags.includes(node.tag) && node.props.length) {
  2229. node.props.forEach((attr, index) => {
  2230. if (attr.name === "srcset" && attr.type === 6) {
  2231. if (!attr.value) return;
  2232. const value = attr.value.content;
  2233. if (!value) return;
  2234. const imageCandidates = value.split(",").map((s) => {
  2235. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2236. return { url, descriptor };
  2237. });
  2238. for (let i = 0; i < imageCandidates.length; i++) {
  2239. const { url } = imageCandidates[i];
  2240. if (isDataUrl(url)) {
  2241. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2242. imageCandidates.splice(i, 1);
  2243. }
  2244. }
  2245. const shouldProcessUrl = (url) => {
  2246. return !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2247. };
  2248. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2249. return;
  2250. }
  2251. if (options.base) {
  2252. const base = options.base;
  2253. const set = [];
  2254. let needImportTransform = false;
  2255. imageCandidates.forEach((candidate) => {
  2256. let { url, descriptor } = candidate;
  2257. descriptor = descriptor ? ` ${descriptor}` : ``;
  2258. if (url[0] === ".") {
  2259. candidate.url = (path$3.posix || path$3).join(base, url);
  2260. set.push(candidate.url + descriptor);
  2261. } else if (shouldProcessUrl(url)) {
  2262. needImportTransform = true;
  2263. } else {
  2264. set.push(url + descriptor);
  2265. }
  2266. });
  2267. if (!needImportTransform) {
  2268. attr.value.content = set.join(", ");
  2269. return;
  2270. }
  2271. }
  2272. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2273. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2274. if (shouldProcessUrl(url)) {
  2275. const { path: path2 } = parseUrl(url);
  2276. let exp2;
  2277. if (path2) {
  2278. const existingImportsIndex = context.imports.findIndex(
  2279. (i) => i.path === path2
  2280. );
  2281. if (existingImportsIndex > -1) {
  2282. exp2 = compilerCore.createSimpleExpression(
  2283. `_imports_${existingImportsIndex}`,
  2284. false,
  2285. attr.loc,
  2286. 3
  2287. );
  2288. } else {
  2289. exp2 = compilerCore.createSimpleExpression(
  2290. `_imports_${context.imports.length}`,
  2291. false,
  2292. attr.loc,
  2293. 3
  2294. );
  2295. context.imports.push({ exp: exp2, path: path2 });
  2296. }
  2297. compoundExpression.children.push(exp2);
  2298. }
  2299. } else {
  2300. const exp2 = compilerCore.createSimpleExpression(
  2301. `"${url}"`,
  2302. false,
  2303. attr.loc,
  2304. 3
  2305. );
  2306. compoundExpression.children.push(exp2);
  2307. }
  2308. const isNotLast = imageCandidates.length - 1 > index2;
  2309. if (descriptor && isNotLast) {
  2310. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2311. } else if (descriptor) {
  2312. compoundExpression.children.push(` + ' ${descriptor}'`);
  2313. } else if (isNotLast) {
  2314. compoundExpression.children.push(` + ', ' + `);
  2315. }
  2316. });
  2317. let exp = compoundExpression;
  2318. if (context.hoistStatic) {
  2319. exp = context.hoist(compoundExpression);
  2320. exp.constType = 3;
  2321. }
  2322. node.props[index] = {
  2323. type: 7,
  2324. name: "bind",
  2325. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2326. exp,
  2327. modifiers: [],
  2328. loc: attr.loc
  2329. };
  2330. }
  2331. });
  2332. }
  2333. }
  2334. };
  2335. function commonjsRequire(path) {
  2336. 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.');
  2337. }
  2338. var consolidate$2 = {exports: {}};
  2339. (function (module, exports) {
  2340. /*
  2341. * Engines which do not support caching of their file contents
  2342. * should use the `read()` function defined in consolidate.js
  2343. * On top of this, when an engine compiles to a `Function`,
  2344. * these functions should either be cached within consolidate.js
  2345. * or the engine itself via `options.cache`. This will allow
  2346. * users and frameworks to pass `options.cache = true` for
  2347. * `NODE_ENV=production`, however edit the file(s) without
  2348. * re-loading the application in development.
  2349. */
  2350. /**
  2351. * Module dependencies.
  2352. */
  2353. var fs = require$$0;
  2354. var path = path$3;
  2355. var util = require$$2;
  2356. var join = path.join;
  2357. var resolve = path.resolve;
  2358. var extname = path.extname;
  2359. var dirname = path.dirname;
  2360. var isAbsolute = path.isAbsolute;
  2361. var readCache = {};
  2362. /**
  2363. * Require cache.
  2364. */
  2365. var cacheStore = {};
  2366. /**
  2367. * Require cache.
  2368. */
  2369. var requires = {};
  2370. /**
  2371. * Clear the cache.
  2372. *
  2373. * @api public
  2374. */
  2375. exports.clearCache = function() {
  2376. readCache = {};
  2377. cacheStore = {};
  2378. };
  2379. /**
  2380. * Conditionally cache `compiled` template based
  2381. * on the `options` filename and `.cache` boolean.
  2382. *
  2383. * @param {Object} options
  2384. * @param {Function} compiled
  2385. * @return {Function}
  2386. * @api private
  2387. */
  2388. function cache(options, compiled) {
  2389. // cachable
  2390. if (compiled && options.filename && options.cache) {
  2391. delete readCache[options.filename];
  2392. cacheStore[options.filename] = compiled;
  2393. return compiled;
  2394. }
  2395. // check cache
  2396. if (options.filename && options.cache) {
  2397. return cacheStore[options.filename];
  2398. }
  2399. return compiled;
  2400. }
  2401. /**
  2402. * Read `path` with `options` with
  2403. * callback `(err, str)`. When `options.cache`
  2404. * is true the template string will be cached.
  2405. *
  2406. * @param {String} options
  2407. * @param {Function} cb
  2408. * @api private
  2409. */
  2410. function read(path, options, cb) {
  2411. var str = readCache[path];
  2412. var cached = options.cache && str && typeof str === 'string';
  2413. // cached (only if cached is a string and not a compiled template function)
  2414. if (cached) return cb(null, str);
  2415. // read
  2416. fs.readFile(path, 'utf8', function(err, str) {
  2417. if (err) return cb(err);
  2418. // remove extraneous utf8 BOM marker
  2419. str = str.replace(/^\uFEFF/, '');
  2420. if (options.cache) readCache[path] = str;
  2421. cb(null, str);
  2422. });
  2423. }
  2424. /**
  2425. * Read `path` with `options` with
  2426. * callback `(err, str)`. When `options.cache`
  2427. * is true the partial string will be cached.
  2428. *
  2429. * @param {String} options
  2430. * @param {Function} fn
  2431. * @api private
  2432. */
  2433. function readPartials(path, options, cb) {
  2434. if (!options.partials) return cb();
  2435. var keys = Object.keys(options.partials);
  2436. var partials = {};
  2437. function next(index) {
  2438. if (index === keys.length) return cb(null, partials);
  2439. var key = keys[index];
  2440. var partialPath = options.partials[key];
  2441. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2442. return next(++index);
  2443. }
  2444. var file;
  2445. if (isAbsolute(partialPath)) {
  2446. if (extname(partialPath) !== '') {
  2447. file = partialPath;
  2448. } else {
  2449. file = join(partialPath + extname(path));
  2450. }
  2451. } else {
  2452. file = join(dirname(path), partialPath + extname(path));
  2453. }
  2454. read(file, options, function(err, str) {
  2455. if (err) return cb(err);
  2456. partials[key] = str;
  2457. next(++index);
  2458. });
  2459. }
  2460. next(0);
  2461. }
  2462. /**
  2463. * promisify
  2464. */
  2465. function promisify(cb, fn) {
  2466. return new Promise(function(resolve, reject) {
  2467. cb = cb || function(err, html) {
  2468. if (err) {
  2469. return reject(err);
  2470. }
  2471. resolve(html);
  2472. };
  2473. fn(cb);
  2474. });
  2475. }
  2476. /**
  2477. * fromStringRenderer
  2478. */
  2479. function fromStringRenderer(name) {
  2480. return function(path, options, cb) {
  2481. options.filename = path;
  2482. return promisify(cb, function(cb) {
  2483. readPartials(path, options, function(err, partials) {
  2484. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2485. var opts = extend({}, options);
  2486. opts.partials = partials;
  2487. if (err) return cb(err);
  2488. if (cache(opts)) {
  2489. exports[name].render('', opts, cb);
  2490. } else {
  2491. read(path, opts, function(err, str) {
  2492. if (err) return cb(err);
  2493. exports[name].render(str, opts, cb);
  2494. });
  2495. }
  2496. });
  2497. });
  2498. };
  2499. }
  2500. /**
  2501. * velocity support.
  2502. */
  2503. exports.velocityjs = fromStringRenderer('velocityjs');
  2504. /**
  2505. * velocity string support.
  2506. */
  2507. exports.velocityjs.render = function(str, options, cb) {
  2508. return promisify(cb, function(cb) {
  2509. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2510. try {
  2511. options.locals = options;
  2512. cb(null, engine.render(str, options).trimLeft());
  2513. } catch (err) {
  2514. cb(err);
  2515. }
  2516. });
  2517. };
  2518. /**
  2519. * Liquid support.
  2520. */
  2521. exports.liquid = fromStringRenderer('liquid');
  2522. /**
  2523. * Liquid string support.
  2524. */
  2525. /**
  2526. * Note that in order to get filters and custom tags we've had to push
  2527. * all user-defined locals down into @locals. However, just to make things
  2528. * backwards-compatible, any property of `options` that is left after
  2529. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2530. * `includeDir` will also become a local.
  2531. */
  2532. function _renderTinyliquid(engine, str, options, cb) {
  2533. var context = engine.newContext();
  2534. var k;
  2535. /**
  2536. * Note that there's a bug in the library that doesn't allow us to pass
  2537. * the locals to newContext(), hence looping through the keys:
  2538. */
  2539. if (options.locals) {
  2540. for (k in options.locals) {
  2541. context.setLocals(k, options.locals[k]);
  2542. }
  2543. delete options.locals;
  2544. }
  2545. if (options.meta) {
  2546. context.setLocals('page', options.meta);
  2547. delete options.meta;
  2548. }
  2549. /**
  2550. * Add any defined filters:
  2551. */
  2552. if (options.filters) {
  2553. for (k in options.filters) {
  2554. context.setFilter(k, options.filters[k]);
  2555. }
  2556. delete options.filters;
  2557. }
  2558. /**
  2559. * Set up a callback for the include directory:
  2560. */
  2561. var includeDir = options.includeDir || process.cwd();
  2562. context.onInclude(function(name, callback) {
  2563. var extname = path.extname(name) ? '' : '.liquid';
  2564. var filename = path.resolve(includeDir, name + extname);
  2565. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2566. if (err) return callback(err);
  2567. callback(null, engine.parse(data));
  2568. });
  2569. });
  2570. delete options.includeDir;
  2571. /**
  2572. * The custom tag functions need to have their results pushed back
  2573. * through the parser, so set up a shim before calling the provided
  2574. * callback:
  2575. */
  2576. var compileOptions = {
  2577. customTags: {}
  2578. };
  2579. if (options.customTags) {
  2580. var tagFunctions = options.customTags;
  2581. for (k in options.customTags) {
  2582. /*Tell jshint there's no problem with having this function in the loop */
  2583. /*jshint -W083 */
  2584. compileOptions.customTags[k] = function(context, name, body) {
  2585. var tpl = tagFunctions[name](body.trim());
  2586. context.astStack.push(engine.parse(tpl));
  2587. };
  2588. /*jshint +W083 */
  2589. }
  2590. delete options.customTags;
  2591. }
  2592. /**
  2593. * Now anything left in `options` becomes a local:
  2594. */
  2595. for (k in options) {
  2596. context.setLocals(k, options[k]);
  2597. }
  2598. /**
  2599. * Finally, execute the template:
  2600. */
  2601. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2602. tmpl(context, cb);
  2603. }
  2604. exports.liquid.render = function(str, options, cb) {
  2605. return promisify(cb, function(cb) {
  2606. var engine = requires.liquid;
  2607. var Liquid;
  2608. try {
  2609. // set up tinyliquid engine
  2610. engine = requires.liquid = require('tinyliquid');
  2611. // use tinyliquid engine
  2612. _renderTinyliquid(engine, str, options, cb);
  2613. return;
  2614. } catch (err) {
  2615. // set up liquid-node engine
  2616. try {
  2617. Liquid = requires.liquid = require('liquid-node');
  2618. engine = new Liquid.Engine();
  2619. } catch (err) {
  2620. throw err;
  2621. }
  2622. }
  2623. // use liquid-node engine
  2624. try {
  2625. var locals = options.locals || {};
  2626. if (options.meta) {
  2627. locals.pages = options.meta;
  2628. delete options.meta;
  2629. }
  2630. /**
  2631. * Add any defined filters:
  2632. */
  2633. if (options.filters) {
  2634. engine.registerFilters(options.filters);
  2635. delete options.filters;
  2636. }
  2637. /**
  2638. * Set up a callback for the include directory:
  2639. */
  2640. var includeDir = options.includeDir || process.cwd();
  2641. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2642. delete options.includeDir;
  2643. /**
  2644. * The custom tag functions need to have their results pushed back
  2645. * through the parser, so set up a shim before calling the provided
  2646. * callback:
  2647. */
  2648. if (options.customTags) {
  2649. var tagFunctions = options.customTags;
  2650. for (k in options.customTags) {
  2651. engine.registerTag(k, tagFunctions[k]);
  2652. }
  2653. delete options.customTags;
  2654. }
  2655. /**
  2656. * Now anything left in `options` becomes a local:
  2657. */
  2658. for (var k in options) {
  2659. locals[k] = options[k];
  2660. }
  2661. /**
  2662. * Finally, execute the template:
  2663. */
  2664. return engine
  2665. .parseAndRender(str, locals)
  2666. .nodeify(function(err, result) {
  2667. if (err) {
  2668. throw new Error(err);
  2669. } else {
  2670. return cb(null, result);
  2671. }
  2672. });
  2673. } catch (err) {
  2674. cb(err);
  2675. }
  2676. });
  2677. };
  2678. /**
  2679. * Jade support.
  2680. */
  2681. exports.jade = function(path, options, cb) {
  2682. return promisify(cb, function(cb) {
  2683. var engine = requires.jade;
  2684. if (!engine) {
  2685. try {
  2686. engine = requires.jade = require('jade');
  2687. } catch (err) {
  2688. try {
  2689. engine = requires.jade = require('then-jade');
  2690. } catch (otherError) {
  2691. throw err;
  2692. }
  2693. }
  2694. }
  2695. try {
  2696. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2697. cb(null, tmpl(options));
  2698. } catch (err) {
  2699. cb(err);
  2700. }
  2701. });
  2702. };
  2703. /**
  2704. * Jade string support.
  2705. */
  2706. exports.jade.render = function(str, options, cb) {
  2707. return promisify(cb, function(cb) {
  2708. var engine = requires.jade;
  2709. if (!engine) {
  2710. try {
  2711. engine = requires.jade = require('jade');
  2712. } catch (err) {
  2713. try {
  2714. engine = requires.jade = require('then-jade');
  2715. } catch (otherError) {
  2716. throw err;
  2717. }
  2718. }
  2719. }
  2720. try {
  2721. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2722. cb(null, tmpl(options));
  2723. } catch (err) {
  2724. cb(err);
  2725. }
  2726. });
  2727. };
  2728. /**
  2729. * Dust support.
  2730. */
  2731. exports.dust = fromStringRenderer('dust');
  2732. /**
  2733. * Dust string support.
  2734. */
  2735. exports.dust.render = function(str, options, cb) {
  2736. return promisify(cb, function(cb) {
  2737. var engine = requires.dust;
  2738. if (!engine) {
  2739. try {
  2740. engine = requires.dust = require('dust');
  2741. } catch (err) {
  2742. try {
  2743. engine = requires.dust = require('dustjs-helpers');
  2744. } catch (err) {
  2745. engine = requires.dust = require('dustjs-linkedin');
  2746. }
  2747. }
  2748. }
  2749. var ext = 'dust';
  2750. var views = '.';
  2751. if (options) {
  2752. if (options.ext) ext = options.ext;
  2753. if (options.views) views = options.views;
  2754. if (options.settings && options.settings.views) views = options.settings.views;
  2755. }
  2756. if (!options || (options && !options.cache)) engine.cache = {};
  2757. engine.onLoad = function(path, callback) {
  2758. if (extname(path) === '') path += '.' + ext;
  2759. if (path[0] !== '/') path = views + '/' + path;
  2760. read(path, options, callback);
  2761. };
  2762. try {
  2763. var templateName;
  2764. if (options.filename) {
  2765. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2766. }
  2767. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2768. tmpl(options, cb);
  2769. } catch (err) {
  2770. cb(err);
  2771. }
  2772. });
  2773. };
  2774. /**
  2775. * Swig support.
  2776. */
  2777. exports.swig = fromStringRenderer('swig');
  2778. /**
  2779. * Swig string support.
  2780. */
  2781. exports.swig.render = function(str, options, cb) {
  2782. return promisify(cb, function(cb) {
  2783. var engine = requires.swig;
  2784. if (!engine) {
  2785. try {
  2786. engine = requires.swig = require('swig');
  2787. } catch (err) {
  2788. try {
  2789. engine = requires.swig = require('swig-templates');
  2790. } catch (otherError) {
  2791. throw err;
  2792. }
  2793. }
  2794. }
  2795. try {
  2796. if (options.cache === true) options.cache = 'memory';
  2797. engine.setDefaults({ cache: options.cache });
  2798. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2799. cb(null, tmpl(options));
  2800. } catch (err) {
  2801. cb(err);
  2802. }
  2803. });
  2804. };
  2805. /**
  2806. * Razor support.
  2807. */
  2808. exports.razor = function(path, options, cb) {
  2809. return promisify(cb, function(cb) {
  2810. var engine = requires.razor;
  2811. if (!engine) {
  2812. try {
  2813. engine = requires.razor = require('razor-tmpl');
  2814. } catch (err) {
  2815. throw err;
  2816. }
  2817. }
  2818. try {
  2819. var tmpl = cache(options) || cache(options, (locals) => {
  2820. console.log('Rendering razor file', path);
  2821. return engine.renderFileSync(path, locals);
  2822. });
  2823. cb(null, tmpl(options));
  2824. } catch (err) {
  2825. cb(err);
  2826. }
  2827. });
  2828. };
  2829. /**
  2830. * razor string support.
  2831. */
  2832. exports.razor.render = function(str, options, cb) {
  2833. return promisify(cb, function(cb) {
  2834. try {
  2835. var engine = requires.razor = require('razor-tmpl');
  2836. } catch (err) {
  2837. throw err;
  2838. }
  2839. try {
  2840. var tf = engine.compile(str);
  2841. var tmpl = cache(options) || cache(options, tf);
  2842. cb(null, tmpl(options));
  2843. } catch (err) {
  2844. cb(err);
  2845. }
  2846. });
  2847. };
  2848. /**
  2849. * Atpl support.
  2850. */
  2851. exports.atpl = fromStringRenderer('atpl');
  2852. /**
  2853. * Atpl string support.
  2854. */
  2855. exports.atpl.render = function(str, options, cb) {
  2856. return promisify(cb, function(cb) {
  2857. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2858. try {
  2859. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2860. cb(null, tmpl(options));
  2861. } catch (err) {
  2862. cb(err);
  2863. }
  2864. });
  2865. };
  2866. /**
  2867. * Liquor support,
  2868. */
  2869. exports.liquor = fromStringRenderer('liquor');
  2870. /**
  2871. * Liquor string support.
  2872. */
  2873. exports.liquor.render = function(str, options, cb) {
  2874. return promisify(cb, function(cb) {
  2875. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2876. try {
  2877. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2878. cb(null, tmpl(options));
  2879. } catch (err) {
  2880. cb(err);
  2881. }
  2882. });
  2883. };
  2884. /**
  2885. * Twig support.
  2886. */
  2887. exports.twig = fromStringRenderer('twig');
  2888. /**
  2889. * Twig string support.
  2890. */
  2891. exports.twig.render = function(str, options, cb) {
  2892. return promisify(cb, function(cb) {
  2893. var engine = requires.twig || (requires.twig = require('twig').twig);
  2894. var templateData = {
  2895. data: str,
  2896. allowInlineIncludes: options.allowInlineIncludes,
  2897. namespaces: options.namespaces,
  2898. path: options.path
  2899. };
  2900. try {
  2901. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2902. cb(null, tmpl.render(options));
  2903. } catch (err) {
  2904. cb(err);
  2905. }
  2906. });
  2907. };
  2908. /**
  2909. * EJS support.
  2910. */
  2911. exports.ejs = fromStringRenderer('ejs');
  2912. /**
  2913. * EJS string support.
  2914. */
  2915. exports.ejs.render = function(str, options, cb) {
  2916. return promisify(cb, function(cb) {
  2917. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2918. try {
  2919. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2920. cb(null, tmpl(options));
  2921. } catch (err) {
  2922. cb(err);
  2923. }
  2924. });
  2925. };
  2926. /**
  2927. * Eco support.
  2928. */
  2929. exports.eco = fromStringRenderer('eco');
  2930. /**
  2931. * Eco string support.
  2932. */
  2933. exports.eco.render = function(str, options, cb) {
  2934. return promisify(cb, function(cb) {
  2935. var engine = requires.eco || (requires.eco = require('eco'));
  2936. try {
  2937. cb(null, engine.render(str, options));
  2938. } catch (err) {
  2939. cb(err);
  2940. }
  2941. });
  2942. };
  2943. /**
  2944. * Jazz support.
  2945. */
  2946. exports.jazz = fromStringRenderer('jazz');
  2947. /**
  2948. * Jazz string support.
  2949. */
  2950. exports.jazz.render = function(str, options, cb) {
  2951. return promisify(cb, function(cb) {
  2952. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2953. try {
  2954. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2955. tmpl.eval(options, function(str) {
  2956. cb(null, str);
  2957. });
  2958. } catch (err) {
  2959. cb(err);
  2960. }
  2961. });
  2962. };
  2963. /**
  2964. * JQTPL support.
  2965. */
  2966. exports.jqtpl = fromStringRenderer('jqtpl');
  2967. /**
  2968. * JQTPL string support.
  2969. */
  2970. exports.jqtpl.render = function(str, options, cb) {
  2971. return promisify(cb, function(cb) {
  2972. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2973. try {
  2974. engine.template(str, str);
  2975. cb(null, engine.tmpl(str, options));
  2976. } catch (err) {
  2977. cb(err);
  2978. }
  2979. });
  2980. };
  2981. /**
  2982. * Haml support.
  2983. */
  2984. exports.haml = fromStringRenderer('haml');
  2985. /**
  2986. * Haml string support.
  2987. */
  2988. exports.haml.render = function(str, options, cb) {
  2989. return promisify(cb, function(cb) {
  2990. var engine = requires.haml || (requires.haml = require('hamljs'));
  2991. try {
  2992. options.locals = options;
  2993. cb(null, engine.render(str, options).trimLeft());
  2994. } catch (err) {
  2995. cb(err);
  2996. }
  2997. });
  2998. };
  2999. /**
  3000. * Hamlet support.
  3001. */
  3002. exports.hamlet = fromStringRenderer('hamlet');
  3003. /**
  3004. * Hamlet string support.
  3005. */
  3006. exports.hamlet.render = function(str, options, cb) {
  3007. return promisify(cb, function(cb) {
  3008. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  3009. try {
  3010. options.locals = options;
  3011. cb(null, engine.render(str, options).trimLeft());
  3012. } catch (err) {
  3013. cb(err);
  3014. }
  3015. });
  3016. };
  3017. /**
  3018. * Whiskers support.
  3019. */
  3020. exports.whiskers = function(path, options, cb) {
  3021. return promisify(cb, function(cb) {
  3022. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3023. engine.__express(path, options, cb);
  3024. });
  3025. };
  3026. /**
  3027. * Whiskers string support.
  3028. */
  3029. exports.whiskers.render = function(str, options, cb) {
  3030. return promisify(cb, function(cb) {
  3031. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3032. try {
  3033. cb(null, engine.render(str, options));
  3034. } catch (err) {
  3035. cb(err);
  3036. }
  3037. });
  3038. };
  3039. /**
  3040. * Coffee-HAML support.
  3041. */
  3042. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  3043. /**
  3044. * Coffee-HAML string support.
  3045. */
  3046. exports['haml-coffee'].render = function(str, options, cb) {
  3047. return promisify(cb, function(cb) {
  3048. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  3049. try {
  3050. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3051. cb(null, tmpl(options));
  3052. } catch (err) {
  3053. cb(err);
  3054. }
  3055. });
  3056. };
  3057. /**
  3058. * Hogan support.
  3059. */
  3060. exports.hogan = fromStringRenderer('hogan');
  3061. /**
  3062. * Hogan string support.
  3063. */
  3064. exports.hogan.render = function(str, options, cb) {
  3065. return promisify(cb, function(cb) {
  3066. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3067. try {
  3068. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3069. cb(null, tmpl.render(options, options.partials));
  3070. } catch (err) {
  3071. cb(err);
  3072. }
  3073. });
  3074. };
  3075. /**
  3076. * templayed.js support.
  3077. */
  3078. exports.templayed = fromStringRenderer('templayed');
  3079. /**
  3080. * templayed.js string support.
  3081. */
  3082. exports.templayed.render = function(str, options, cb) {
  3083. return promisify(cb, function(cb) {
  3084. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3085. try {
  3086. var tmpl = cache(options) || cache(options, engine(str));
  3087. cb(null, tmpl(options));
  3088. } catch (err) {
  3089. cb(err);
  3090. }
  3091. });
  3092. };
  3093. /**
  3094. * Handlebars support.
  3095. */
  3096. exports.handlebars = fromStringRenderer('handlebars');
  3097. /**
  3098. * Handlebars string support.
  3099. */
  3100. exports.handlebars.render = function(str, options, cb) {
  3101. return promisify(cb, function(cb) {
  3102. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3103. try {
  3104. for (var partial in options.partials) {
  3105. engine.registerPartial(partial, options.partials[partial]);
  3106. }
  3107. for (var helper in options.helpers) {
  3108. engine.registerHelper(helper, options.helpers[helper]);
  3109. }
  3110. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3111. cb(null, tmpl(options));
  3112. } catch (err) {
  3113. cb(err);
  3114. }
  3115. });
  3116. };
  3117. /**
  3118. * Underscore support.
  3119. */
  3120. exports.underscore = fromStringRenderer('underscore');
  3121. /**
  3122. * Underscore string support.
  3123. */
  3124. exports.underscore.render = function(str, options, cb) {
  3125. return promisify(cb, function(cb) {
  3126. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3127. try {
  3128. const partials = {};
  3129. for (var partial in options.partials) {
  3130. partials[partial] = engine.template(options.partials[partial]);
  3131. }
  3132. options.partials = partials;
  3133. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3134. cb(null, tmpl(options).replace(/\n$/, ''));
  3135. } catch (err) {
  3136. cb(err);
  3137. }
  3138. });
  3139. };
  3140. /**
  3141. * Lodash support.
  3142. */
  3143. exports.lodash = fromStringRenderer('lodash');
  3144. /**
  3145. * Lodash string support.
  3146. */
  3147. exports.lodash.render = function(str, options, cb) {
  3148. return promisify(cb, function(cb) {
  3149. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3150. try {
  3151. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3152. cb(null, tmpl(options).replace(/\n$/, ''));
  3153. } catch (err) {
  3154. cb(err);
  3155. }
  3156. });
  3157. };
  3158. /**
  3159. * Pug support. (formerly Jade)
  3160. */
  3161. exports.pug = function(path, options, cb) {
  3162. return promisify(cb, function(cb) {
  3163. var engine = requires.pug;
  3164. if (!engine) {
  3165. try {
  3166. engine = requires.pug = require('pug');
  3167. } catch (err) {
  3168. try {
  3169. engine = requires.pug = require('then-pug');
  3170. } catch (otherError) {
  3171. throw err;
  3172. }
  3173. }
  3174. }
  3175. try {
  3176. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3177. cb(null, tmpl(options));
  3178. } catch (err) {
  3179. cb(err);
  3180. }
  3181. });
  3182. };
  3183. /**
  3184. * Pug string support.
  3185. */
  3186. exports.pug.render = function(str, options, cb) {
  3187. return promisify(cb, function(cb) {
  3188. var engine = requires.pug;
  3189. if (!engine) {
  3190. try {
  3191. engine = requires.pug = require('pug');
  3192. } catch (err) {
  3193. try {
  3194. engine = requires.pug = require('then-pug');
  3195. } catch (otherError) {
  3196. throw err;
  3197. }
  3198. }
  3199. }
  3200. try {
  3201. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3202. cb(null, tmpl(options));
  3203. } catch (err) {
  3204. cb(err);
  3205. }
  3206. });
  3207. };
  3208. /**
  3209. * QEJS support.
  3210. */
  3211. exports.qejs = fromStringRenderer('qejs');
  3212. /**
  3213. * QEJS string support.
  3214. */
  3215. exports.qejs.render = function(str, options, cb) {
  3216. return promisify(cb, function(cb) {
  3217. try {
  3218. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3219. engine.render(str, options).then(function(result) {
  3220. cb(null, result);
  3221. }, function(err) {
  3222. cb(err);
  3223. }).done();
  3224. } catch (err) {
  3225. cb(err);
  3226. }
  3227. });
  3228. };
  3229. /**
  3230. * Walrus support.
  3231. */
  3232. exports.walrus = fromStringRenderer('walrus');
  3233. /**
  3234. * Walrus string support.
  3235. */
  3236. exports.walrus.render = function(str, options, cb) {
  3237. return promisify(cb, function(cb) {
  3238. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3239. try {
  3240. var tmpl = cache(options) || cache(options, engine.parse(str));
  3241. cb(null, tmpl.compile(options));
  3242. } catch (err) {
  3243. cb(err);
  3244. }
  3245. });
  3246. };
  3247. /**
  3248. * Mustache support.
  3249. */
  3250. exports.mustache = fromStringRenderer('mustache');
  3251. /**
  3252. * Mustache string support.
  3253. */
  3254. exports.mustache.render = function(str, options, cb) {
  3255. return promisify(cb, function(cb) {
  3256. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3257. try {
  3258. cb(null, engine.render(str, options, options.partials));
  3259. } catch (err) {
  3260. cb(err);
  3261. }
  3262. });
  3263. };
  3264. /**
  3265. * Just support.
  3266. */
  3267. exports.just = function(path, options, cb) {
  3268. return promisify(cb, function(cb) {
  3269. var engine = requires.just;
  3270. if (!engine) {
  3271. var JUST = require('just');
  3272. engine = requires.just = new JUST();
  3273. }
  3274. engine.configure({ useCache: options.cache });
  3275. engine.render(path, options, cb);
  3276. });
  3277. };
  3278. /**
  3279. * Just string support.
  3280. */
  3281. exports.just.render = function(str, options, cb) {
  3282. return promisify(cb, function(cb) {
  3283. var JUST = require('just');
  3284. var engine = new JUST({ root: { page: str }});
  3285. engine.render('page', options, cb);
  3286. });
  3287. };
  3288. /**
  3289. * ECT support.
  3290. */
  3291. exports.ect = function(path, options, cb) {
  3292. return promisify(cb, function(cb) {
  3293. var engine = requires.ect;
  3294. if (!engine) {
  3295. var ECT = require('ect');
  3296. engine = requires.ect = new ECT(options);
  3297. }
  3298. engine.configure({ cache: options.cache });
  3299. engine.render(path, options, cb);
  3300. });
  3301. };
  3302. /**
  3303. * ECT string support.
  3304. */
  3305. exports.ect.render = function(str, options, cb) {
  3306. return promisify(cb, function(cb) {
  3307. var ECT = require('ect');
  3308. var engine = new ECT({ root: { page: str }});
  3309. engine.render('page', options, cb);
  3310. });
  3311. };
  3312. /**
  3313. * mote support.
  3314. */
  3315. exports.mote = fromStringRenderer('mote');
  3316. /**
  3317. * mote string support.
  3318. */
  3319. exports.mote.render = function(str, options, cb) {
  3320. return promisify(cb, function(cb) {
  3321. var engine = requires.mote || (requires.mote = require('mote'));
  3322. try {
  3323. var tmpl = cache(options) || cache(options, engine.compile(str));
  3324. cb(null, tmpl(options));
  3325. } catch (err) {
  3326. cb(err);
  3327. }
  3328. });
  3329. };
  3330. /**
  3331. * Toffee support.
  3332. */
  3333. exports.toffee = function(path, options, cb) {
  3334. return promisify(cb, function(cb) {
  3335. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3336. toffee.__consolidate_engine_render(path, options, cb);
  3337. });
  3338. };
  3339. /**
  3340. * Toffee string support.
  3341. */
  3342. exports.toffee.render = function(str, options, cb) {
  3343. return promisify(cb, function(cb) {
  3344. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3345. try {
  3346. engine.str_render(str, options, cb);
  3347. } catch (err) {
  3348. cb(err);
  3349. }
  3350. });
  3351. };
  3352. /**
  3353. * doT support.
  3354. */
  3355. exports.dot = fromStringRenderer('dot');
  3356. /**
  3357. * doT string support.
  3358. */
  3359. exports.dot.render = function(str, options, cb) {
  3360. return promisify(cb, function(cb) {
  3361. var engine = requires.dot || (requires.dot = require('dot'));
  3362. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3363. try {
  3364. var settings = {};
  3365. settings = extend(settings, engine.templateSettings);
  3366. settings = extend(settings, options ? options.dot : {});
  3367. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3368. cb(null, tmpl(options));
  3369. } catch (err) {
  3370. cb(err);
  3371. }
  3372. });
  3373. };
  3374. /**
  3375. * bracket support.
  3376. */
  3377. exports.bracket = fromStringRenderer('bracket');
  3378. /**
  3379. * bracket string support.
  3380. */
  3381. exports.bracket.render = function(str, options, cb) {
  3382. return promisify(cb, function(cb) {
  3383. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3384. try {
  3385. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3386. cb(null, tmpl(options));
  3387. } catch (err) {
  3388. cb(err);
  3389. }
  3390. });
  3391. };
  3392. /**
  3393. * Ractive support.
  3394. */
  3395. exports.ractive = fromStringRenderer('ractive');
  3396. /**
  3397. * Ractive string support.
  3398. */
  3399. exports.ractive.render = function(str, options, cb) {
  3400. return promisify(cb, function(cb) {
  3401. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3402. var template = cache(options) || cache(options, Engine.parse(str));
  3403. options.template = template;
  3404. if (options.data === null || options.data === undefined) {
  3405. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3406. // Shallow clone the options object
  3407. options.data = extend({}, options);
  3408. // Remove consolidate-specific properties from the clone
  3409. var i;
  3410. var length;
  3411. var properties = ['template', 'filename', 'cache', 'partials'];
  3412. for (i = 0, length = properties.length; i < length; i++) {
  3413. var property = properties[i];
  3414. delete options.data[property];
  3415. }
  3416. }
  3417. try {
  3418. cb(null, new Engine(options).toHTML());
  3419. } catch (err) {
  3420. cb(err);
  3421. }
  3422. });
  3423. };
  3424. /**
  3425. * Nunjucks support.
  3426. */
  3427. exports.nunjucks = fromStringRenderer('nunjucks');
  3428. /**
  3429. * Nunjucks string support.
  3430. */
  3431. exports.nunjucks.render = function(str, options, cb) {
  3432. return promisify(cb, function(cb) {
  3433. try {
  3434. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3435. var env = engine;
  3436. // deprecated fallback support for express
  3437. // <https://github.com/tj/consolidate.js/pull/152>
  3438. // <https://github.com/tj/consolidate.js/pull/224>
  3439. if (options.settings && options.settings.views) {
  3440. env = engine.configure(options.settings.views);
  3441. } else if (options.nunjucks && options.nunjucks.configure) {
  3442. env = engine.configure.apply(engine, options.nunjucks.configure);
  3443. }
  3444. //
  3445. // because `renderString` does not initiate loaders
  3446. // we must manually create a loader for it based off
  3447. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3448. //
  3449. // <https://github.com/mozilla/nunjucks/issues/730>
  3450. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3451. //
  3452. // so instead we simply check if we passed a custom loader
  3453. // otherwise we create a simple file based loader
  3454. if (options.loader) {
  3455. env = new engine.Environment(options.loader);
  3456. } else if (options.settings && options.settings.views) {
  3457. env = new engine.Environment(
  3458. new engine.FileSystemLoader(options.settings.views)
  3459. );
  3460. } else if (options.nunjucks && options.nunjucks.loader) {
  3461. if (typeof options.nunjucks.loader === 'string') {
  3462. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3463. } else {
  3464. env = new engine.Environment(
  3465. new engine.FileSystemLoader(
  3466. options.nunjucks.loader[0],
  3467. options.nunjucks.loader[1]
  3468. )
  3469. );
  3470. }
  3471. }
  3472. env.renderString(str, options, cb);
  3473. } catch (err) {
  3474. throw cb(err);
  3475. }
  3476. });
  3477. };
  3478. /**
  3479. * HTMLing support.
  3480. */
  3481. exports.htmling = fromStringRenderer('htmling');
  3482. /**
  3483. * HTMLing string support.
  3484. */
  3485. exports.htmling.render = function(str, options, cb) {
  3486. return promisify(cb, function(cb) {
  3487. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3488. try {
  3489. var tmpl = cache(options) || cache(options, engine.string(str));
  3490. cb(null, tmpl.render(options));
  3491. } catch (err) {
  3492. cb(err);
  3493. }
  3494. });
  3495. };
  3496. /**
  3497. * Rendering function
  3498. */
  3499. function requireReact(module, filename) {
  3500. var babel = requires.babel || (requires.babel = require('babel-core'));
  3501. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3502. return module._compile(compiled, filename);
  3503. }
  3504. exports.requireReact = requireReact;
  3505. /**
  3506. * Converting a string into a node module.
  3507. */
  3508. function requireReactString(src, filename) {
  3509. var babel = requires.babel || (requires.babel = require('babel-core'));
  3510. if (!filename) filename = '';
  3511. var m = new module.constructor();
  3512. filename = filename || '';
  3513. // Compile Using React
  3514. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3515. // Compile as a module
  3516. m.paths = module.paths;
  3517. m._compile(compiled, filename);
  3518. return m.exports;
  3519. }
  3520. /**
  3521. * A naive helper to replace {{tags}} with options.tags content
  3522. */
  3523. function reactBaseTmpl(data, options) {
  3524. var exp;
  3525. var regex;
  3526. // Iterates through the keys in file object
  3527. // and interpolate / replace {{key}} with it's value
  3528. for (var k in options) {
  3529. if (options.hasOwnProperty(k)) {
  3530. exp = '{{' + k + '}}';
  3531. regex = new RegExp(exp, 'g');
  3532. if (data.match(regex)) {
  3533. data = data.replace(regex, options[k]);
  3534. }
  3535. }
  3536. }
  3537. return data;
  3538. }
  3539. /**
  3540. * Plates Support.
  3541. */
  3542. exports.plates = fromStringRenderer('plates');
  3543. /**
  3544. * Plates string support.
  3545. */
  3546. exports.plates.render = function(str, options, cb) {
  3547. return promisify(cb, function(cb) {
  3548. var engine = requires.plates || (requires.plates = require('plates'));
  3549. var map = options.map || undefined;
  3550. try {
  3551. var tmpl = engine.bind(str, options, map);
  3552. cb(null, tmpl);
  3553. } catch (err) {
  3554. cb(err);
  3555. }
  3556. });
  3557. };
  3558. /**
  3559. * The main render parser for React bsaed templates
  3560. */
  3561. function reactRenderer(type) {
  3562. if (commonjsRequire.extensions) {
  3563. // Ensure JSX is transformed on require
  3564. if (!commonjsRequire.extensions['.jsx']) {
  3565. commonjsRequire.extensions['.jsx'] = requireReact;
  3566. }
  3567. // Supporting .react extension as well as test cases
  3568. // Using .react extension is not recommended.
  3569. if (!commonjsRequire.extensions['.react']) {
  3570. commonjsRequire.extensions['.react'] = requireReact;
  3571. }
  3572. }
  3573. // Return rendering fx
  3574. return function(str, options, cb) {
  3575. return promisify(cb, function(cb) {
  3576. // React Import
  3577. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3578. var react = requires.react || (requires.react = require('react'));
  3579. // Assign HTML Base
  3580. var base = options.base;
  3581. delete options.base;
  3582. var enableCache = options.cache;
  3583. delete options.cache;
  3584. var isNonStatic = options.isNonStatic;
  3585. delete options.isNonStatic;
  3586. // Start Conversion
  3587. try {
  3588. var Code;
  3589. var Factory;
  3590. var baseStr;
  3591. var content;
  3592. var parsed;
  3593. if (!cache(options)) {
  3594. // Parsing
  3595. if (type === 'path') {
  3596. var path = resolve(str);
  3597. delete require.cache[path];
  3598. Code = commonjsRequire(path);
  3599. } else {
  3600. Code = requireReactString(str);
  3601. }
  3602. Factory = cache(options, react.createFactory(Code));
  3603. } else {
  3604. Factory = cache(options);
  3605. }
  3606. parsed = new Factory(options);
  3607. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3608. if (base) {
  3609. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3610. if (enableCache) {
  3611. readCache[str] = baseStr;
  3612. }
  3613. options.content = content;
  3614. content = reactBaseTmpl(baseStr, options);
  3615. }
  3616. cb(null, content);
  3617. } catch (err) {
  3618. cb(err);
  3619. }
  3620. });
  3621. };
  3622. }
  3623. /**
  3624. * React JS Support
  3625. */
  3626. exports.react = reactRenderer('path');
  3627. /**
  3628. * React JS string support.
  3629. */
  3630. exports.react.render = reactRenderer('string');
  3631. /**
  3632. * ARC-templates support.
  3633. */
  3634. exports['arc-templates'] = fromStringRenderer('arc-templates');
  3635. /**
  3636. * ARC-templates string support.
  3637. */
  3638. exports['arc-templates'].render = function(str, options, cb) {
  3639. var readFileWithOptions = util.promisify(read);
  3640. var consolidateFileSystem = {};
  3641. consolidateFileSystem.readFile = function(path) {
  3642. return readFileWithOptions(path, options);
  3643. };
  3644. return promisify(cb, function(cb) {
  3645. try {
  3646. var engine = requires['arc-templates'];
  3647. if (!engine) {
  3648. var Engine = require('arc-templates/dist/es5');
  3649. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3650. }
  3651. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3652. compiler.then(function(func) { return func(options); })
  3653. .then(function(result) { cb(null, result.content); })
  3654. .catch(cb);
  3655. } catch (err) {
  3656. cb(err);
  3657. }
  3658. });
  3659. };
  3660. /**
  3661. * Vash support
  3662. */
  3663. exports.vash = fromStringRenderer('vash');
  3664. /**
  3665. * Vash string support
  3666. */
  3667. exports.vash.render = function(str, options, cb) {
  3668. return promisify(cb, function(cb) {
  3669. var engine = requires.vash || (requires.vash = require('vash'));
  3670. try {
  3671. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3672. if (options.helpers) {
  3673. for (var key in options.helpers) {
  3674. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3675. continue;
  3676. }
  3677. engine.helpers[key] = options.helpers[key];
  3678. }
  3679. }
  3680. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3681. tmpl(options, function sealLayout(err, ctx) {
  3682. if (err) cb(err);
  3683. ctx.finishLayout();
  3684. cb(null, ctx.toString().replace(/\n$/, ''));
  3685. });
  3686. } catch (err) {
  3687. cb(err);
  3688. }
  3689. });
  3690. };
  3691. /**
  3692. * Slm support.
  3693. */
  3694. exports.slm = fromStringRenderer('slm');
  3695. /**
  3696. * Slm string support.
  3697. */
  3698. exports.slm.render = function(str, options, cb) {
  3699. return promisify(cb, function(cb) {
  3700. var engine = requires.slm || (requires.slm = require('slm'));
  3701. try {
  3702. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3703. cb(null, tmpl(options));
  3704. } catch (err) {
  3705. cb(err);
  3706. }
  3707. });
  3708. };
  3709. /**
  3710. * Marko support.
  3711. */
  3712. exports.marko = function(path, options, cb) {
  3713. return promisify(cb, function(cb) {
  3714. var engine = requires.marko || (requires.marko = require('marko'));
  3715. options.writeToDisk = !!options.cache;
  3716. try {
  3717. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3718. tmpl.renderToString(options, cb);
  3719. } catch (err) {
  3720. cb(err);
  3721. }
  3722. });
  3723. };
  3724. /**
  3725. * Marko string support.
  3726. */
  3727. exports.marko.render = function(str, options, cb) {
  3728. return promisify(cb, function(cb) {
  3729. var engine = requires.marko || (requires.marko = require('marko'));
  3730. options.writeToDisk = !!options.cache;
  3731. options.filename = options.filename || 'string.marko';
  3732. try {
  3733. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3734. tmpl.renderToString(options, cb);
  3735. } catch (err) {
  3736. cb(err);
  3737. }
  3738. });
  3739. };
  3740. /**
  3741. * Teacup support.
  3742. */
  3743. exports.teacup = function(path, options, cb) {
  3744. return promisify(cb, function(cb) {
  3745. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3746. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3747. if (path[0] !== '/') {
  3748. path = join(process.cwd(), path);
  3749. }
  3750. if (!options.cache) {
  3751. var callback = cb;
  3752. cb = function() {
  3753. delete require.cache[path];
  3754. callback.apply(this, arguments);
  3755. };
  3756. }
  3757. engine.renderFile(path, options, cb);
  3758. });
  3759. };
  3760. /**
  3761. * Teacup string support.
  3762. */
  3763. exports.teacup.render = function(str, options, cb) {
  3764. var coffee = require('coffee-script');
  3765. var vm = require('vm');
  3766. var sandbox = {
  3767. module: {exports: {}},
  3768. require: commonjsRequire
  3769. };
  3770. return promisify(cb, function(cb) {
  3771. vm.runInNewContext(coffee.compile(str), sandbox);
  3772. var tmpl = sandbox.module.exports;
  3773. cb(null, tmpl(options));
  3774. });
  3775. };
  3776. /**
  3777. * Squirrelly support.
  3778. */
  3779. exports.squirrelly = fromStringRenderer('squirrelly');
  3780. /**
  3781. * Squirrelly string support.
  3782. */
  3783. exports.squirrelly.render = function(str, options, cb) {
  3784. return promisify(cb, function(cb) {
  3785. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3786. try {
  3787. for (var partial in options.partials) {
  3788. engine.definePartial(partial, options.partials[partial]);
  3789. }
  3790. for (var helper in options.helpers) {
  3791. engine.defineHelper(helper, options.helpers[helper]);
  3792. }
  3793. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3794. cb(null, tmpl(options, engine));
  3795. } catch (err) {
  3796. cb(err);
  3797. }
  3798. });
  3799. };
  3800. /**
  3801. * Twing support.
  3802. */
  3803. exports.twing = fromStringRenderer('twing');
  3804. /**
  3805. * Twing string support.
  3806. */
  3807. exports.twing.render = function(str, options, cb) {
  3808. return promisify(cb, function(cb) {
  3809. var engine = requires.twing || (requires.twing = require('twing'));
  3810. try {
  3811. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3812. twingTemplate.render(options).then((rendTmpl) => {
  3813. var tmpl = cache(options) || cache(options, rendTmpl);
  3814. cb(null, tmpl);
  3815. });
  3816. });
  3817. } catch (err) {
  3818. cb(err);
  3819. }
  3820. });
  3821. };
  3822. /**
  3823. * expose the instance of the engine
  3824. */
  3825. exports.requires = requires;
  3826. } (consolidate$2, consolidate$2.exports));
  3827. var consolidateExports = consolidate$2.exports;
  3828. var consolidate = consolidateExports;
  3829. var consolidate$1 = /*@__PURE__*/getDefaultExportFromCjs(consolidate);
  3830. const hasWarned = {};
  3831. function warnOnce(msg) {
  3832. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3833. if (!isNodeProd && true && !hasWarned[msg]) {
  3834. hasWarned[msg] = true;
  3835. warn(msg);
  3836. }
  3837. }
  3838. function warn(msg) {
  3839. console.warn(
  3840. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3841. `
  3842. );
  3843. }
  3844. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3845. let res = "";
  3846. let err = null;
  3847. preprocessor.render(
  3848. source,
  3849. { filename, ...preprocessOptions },
  3850. (_err, _res) => {
  3851. if (_err) err = _err;
  3852. res = _res;
  3853. }
  3854. );
  3855. if (err) throw err;
  3856. return res;
  3857. }
  3858. function compileTemplate(options) {
  3859. const { preprocessLang, preprocessCustomRequire } = options;
  3860. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate$1[preprocessLang] : false;
  3861. if (preprocessor) {
  3862. try {
  3863. return doCompileTemplate({
  3864. ...options,
  3865. source: preprocess$1(options, preprocessor),
  3866. ast: void 0
  3867. // invalidate AST if template goes through preprocessor
  3868. });
  3869. } catch (e) {
  3870. return {
  3871. code: `export default function render() {}`,
  3872. source: options.source,
  3873. tips: [],
  3874. errors: [e]
  3875. };
  3876. }
  3877. } else if (preprocessLang) {
  3878. return {
  3879. code: `export default function render() {}`,
  3880. source: options.source,
  3881. tips: [
  3882. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3883. ],
  3884. errors: [
  3885. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3886. ]
  3887. };
  3888. } else {
  3889. return doCompileTemplate(options);
  3890. }
  3891. }
  3892. function doCompileTemplate({
  3893. filename,
  3894. id,
  3895. scoped,
  3896. slotted,
  3897. inMap,
  3898. source,
  3899. ast: inAST,
  3900. ssr = false,
  3901. ssrCssVars,
  3902. isProd = false,
  3903. compiler,
  3904. compilerOptions = {},
  3905. transformAssetUrls
  3906. }) {
  3907. const errors = [];
  3908. const warnings = [];
  3909. let nodeTransforms = [];
  3910. if (shared.isObject(transformAssetUrls)) {
  3911. const assetOptions = normalizeOptions(transformAssetUrls);
  3912. nodeTransforms = [
  3913. createAssetUrlTransformWithOptions(assetOptions),
  3914. createSrcsetTransformWithOptions(assetOptions)
  3915. ];
  3916. } else if (transformAssetUrls !== false) {
  3917. nodeTransforms = [transformAssetUrl, transformSrcset];
  3918. }
  3919. if (ssr && !ssrCssVars) {
  3920. warnOnce(
  3921. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  3922. );
  3923. }
  3924. if (!id) {
  3925. warnOnce(`compileTemplate now requires the \`id\` option.`);
  3926. id = "";
  3927. }
  3928. const shortId = id.replace(/^data-v-/, "");
  3929. const longId = `data-v-${shortId}`;
  3930. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3931. compiler = compiler || defaultCompiler;
  3932. if (compiler !== defaultCompiler) {
  3933. inAST = void 0;
  3934. }
  3935. if (inAST == null ? void 0 : inAST.transformed) {
  3936. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3937. prefixIdentifiers: true,
  3938. ...compilerOptions,
  3939. parseMode: "sfc",
  3940. onError: (e) => errors.push(e)
  3941. });
  3942. const template = newAST.children.find(
  3943. (node) => node.type === 1 && node.tag === "template"
  3944. );
  3945. inAST = compilerCore.createRoot(template.children, inAST.source);
  3946. }
  3947. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3948. mode: "module",
  3949. prefixIdentifiers: true,
  3950. hoistStatic: true,
  3951. cacheHandlers: true,
  3952. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3953. scopeId: scoped ? longId : void 0,
  3954. slotted,
  3955. sourceMap: true,
  3956. ...compilerOptions,
  3957. hmr: !isProd,
  3958. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3959. filename,
  3960. onError: (e) => errors.push(e),
  3961. onWarn: (w) => warnings.push(w)
  3962. });
  3963. if (inMap && !inAST) {
  3964. if (map) {
  3965. map = mapLines(inMap, map);
  3966. }
  3967. if (errors.length) {
  3968. patchErrors(errors, source, inMap);
  3969. }
  3970. }
  3971. const tips = warnings.map((w) => {
  3972. let msg = w.message;
  3973. if (w.loc) {
  3974. msg += `
  3975. ${shared.generateCodeFrame(
  3976. (inAST == null ? void 0 : inAST.source) || source,
  3977. w.loc.start.offset,
  3978. w.loc.end.offset
  3979. )}`;
  3980. }
  3981. return msg;
  3982. });
  3983. return { code, ast, preamble, source, errors, tips, map };
  3984. }
  3985. function mapLines(oldMap, newMap) {
  3986. if (!oldMap) return newMap;
  3987. if (!newMap) return oldMap;
  3988. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  3989. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  3990. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  3991. newMapConsumer.eachMapping((m) => {
  3992. if (m.originalLine == null) {
  3993. return;
  3994. }
  3995. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  3996. line: m.originalLine,
  3997. column: m.originalColumn
  3998. });
  3999. if (origPosInOldMap.source == null) {
  4000. return;
  4001. }
  4002. mergedMapGenerator.addMapping({
  4003. generated: {
  4004. line: m.generatedLine,
  4005. column: m.generatedColumn
  4006. },
  4007. original: {
  4008. line: origPosInOldMap.line,
  4009. // map line
  4010. // use current column, since the oldMap produced by @vue/compiler-sfc
  4011. // does not
  4012. column: m.originalColumn
  4013. },
  4014. source: origPosInOldMap.source,
  4015. name: origPosInOldMap.name
  4016. });
  4017. });
  4018. const generator = mergedMapGenerator;
  4019. oldMapConsumer.sources.forEach((sourceFile) => {
  4020. generator._sources.add(sourceFile);
  4021. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  4022. if (sourceContent != null) {
  4023. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  4024. }
  4025. });
  4026. generator._sourceRoot = oldMap.sourceRoot;
  4027. generator._file = oldMap.file;
  4028. return generator.toJSON();
  4029. }
  4030. function patchErrors(errors, source, inMap) {
  4031. const originalSource = inMap.sourcesContent[0];
  4032. const offset = originalSource.indexOf(source);
  4033. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  4034. errors.forEach((err) => {
  4035. if (err.loc) {
  4036. err.loc.start.line += lineOffset;
  4037. err.loc.start.offset += offset;
  4038. if (err.loc.end !== err.loc.start) {
  4039. err.loc.end.line += lineOffset;
  4040. err.loc.end.offset += offset;
  4041. }
  4042. }
  4043. });
  4044. }
  4045. const trimPlugin = () => {
  4046. return {
  4047. postcssPlugin: "vue-sfc-trim",
  4048. Once(root) {
  4049. root.walk(({ type, raws }) => {
  4050. if (type === "rule" || type === "atrule") {
  4051. if (raws.before) raws.before = "\n";
  4052. if ("after" in raws && raws.after) raws.after = "\n";
  4053. }
  4054. });
  4055. }
  4056. };
  4057. };
  4058. trimPlugin.postcss = true;
  4059. var dist = {exports: {}};
  4060. var processor = {exports: {}};
  4061. var parser = {exports: {}};
  4062. var root$2 = {exports: {}};
  4063. var container = {exports: {}};
  4064. var node$1 = {exports: {}};
  4065. var util$6 = {};
  4066. var unesc = {exports: {}};
  4067. (function (module, exports) {
  4068. exports.__esModule = true;
  4069. exports["default"] = unesc;
  4070. // Many thanks for this post which made this migration much easier.
  4071. // https://mathiasbynens.be/notes/css-escapes
  4072. /**
  4073. *
  4074. * @param {string} str
  4075. * @returns {[string, number]|undefined}
  4076. */
  4077. function gobbleHex(str) {
  4078. var lower = str.toLowerCase();
  4079. var hex = '';
  4080. var spaceTerminated = false;
  4081. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4082. var code = lower.charCodeAt(i);
  4083. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4084. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4085. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4086. spaceTerminated = code === 32;
  4087. if (!valid) {
  4088. break;
  4089. }
  4090. hex += lower[i];
  4091. }
  4092. if (hex.length === 0) {
  4093. return undefined;
  4094. }
  4095. var codePoint = parseInt(hex, 16);
  4096. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4097. // Add special case for
  4098. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4099. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4100. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4101. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4102. }
  4103. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4104. }
  4105. var CONTAINS_ESCAPE = /\\/;
  4106. function unesc(str) {
  4107. var needToProcess = CONTAINS_ESCAPE.test(str);
  4108. if (!needToProcess) {
  4109. return str;
  4110. }
  4111. var ret = "";
  4112. for (var i = 0; i < str.length; i++) {
  4113. if (str[i] === "\\") {
  4114. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4115. if (gobbled !== undefined) {
  4116. ret += gobbled[0];
  4117. i += gobbled[1];
  4118. continue;
  4119. }
  4120. // Retain a pair of \\ if double escaped `\\\\`
  4121. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4122. if (str[i + 1] === "\\") {
  4123. ret += "\\";
  4124. i++;
  4125. continue;
  4126. }
  4127. // if \\ is at the end of the string retain it
  4128. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4129. if (str.length === i + 1) {
  4130. ret += str[i];
  4131. }
  4132. continue;
  4133. }
  4134. ret += str[i];
  4135. }
  4136. return ret;
  4137. }
  4138. module.exports = exports.default;
  4139. } (unesc, unesc.exports));
  4140. var unescExports = unesc.exports;
  4141. var getProp = {exports: {}};
  4142. (function (module, exports) {
  4143. exports.__esModule = true;
  4144. exports["default"] = getProp;
  4145. function getProp(obj) {
  4146. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4147. props[_key - 1] = arguments[_key];
  4148. }
  4149. while (props.length > 0) {
  4150. var prop = props.shift();
  4151. if (!obj[prop]) {
  4152. return undefined;
  4153. }
  4154. obj = obj[prop];
  4155. }
  4156. return obj;
  4157. }
  4158. module.exports = exports.default;
  4159. } (getProp, getProp.exports));
  4160. var getPropExports = getProp.exports;
  4161. var ensureObject = {exports: {}};
  4162. (function (module, exports) {
  4163. exports.__esModule = true;
  4164. exports["default"] = ensureObject;
  4165. function ensureObject(obj) {
  4166. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4167. props[_key - 1] = arguments[_key];
  4168. }
  4169. while (props.length > 0) {
  4170. var prop = props.shift();
  4171. if (!obj[prop]) {
  4172. obj[prop] = {};
  4173. }
  4174. obj = obj[prop];
  4175. }
  4176. }
  4177. module.exports = exports.default;
  4178. } (ensureObject, ensureObject.exports));
  4179. var ensureObjectExports = ensureObject.exports;
  4180. var stripComments = {exports: {}};
  4181. (function (module, exports) {
  4182. exports.__esModule = true;
  4183. exports["default"] = stripComments;
  4184. function stripComments(str) {
  4185. var s = "";
  4186. var commentStart = str.indexOf("/*");
  4187. var lastEnd = 0;
  4188. while (commentStart >= 0) {
  4189. s = s + str.slice(lastEnd, commentStart);
  4190. var commentEnd = str.indexOf("*/", commentStart + 2);
  4191. if (commentEnd < 0) {
  4192. return s;
  4193. }
  4194. lastEnd = commentEnd + 2;
  4195. commentStart = str.indexOf("/*", lastEnd);
  4196. }
  4197. s = s + str.slice(lastEnd);
  4198. return s;
  4199. }
  4200. module.exports = exports.default;
  4201. } (stripComments, stripComments.exports));
  4202. var stripCommentsExports = stripComments.exports;
  4203. util$6.__esModule = true;
  4204. util$6.unesc = util$6.stripComments = util$6.getProp = util$6.ensureObject = void 0;
  4205. var _unesc = _interopRequireDefault$5(unescExports);
  4206. util$6.unesc = _unesc["default"];
  4207. var _getProp = _interopRequireDefault$5(getPropExports);
  4208. util$6.getProp = _getProp["default"];
  4209. var _ensureObject = _interopRequireDefault$5(ensureObjectExports);
  4210. util$6.ensureObject = _ensureObject["default"];
  4211. var _stripComments = _interopRequireDefault$5(stripCommentsExports);
  4212. util$6.stripComments = _stripComments["default"];
  4213. function _interopRequireDefault$5(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4214. (function (module, exports) {
  4215. exports.__esModule = true;
  4216. exports["default"] = void 0;
  4217. var _util = util$6;
  4218. 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); } }
  4219. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4220. var cloneNode = function cloneNode(obj, parent) {
  4221. if (typeof obj !== 'object' || obj === null) {
  4222. return obj;
  4223. }
  4224. var cloned = new obj.constructor();
  4225. for (var i in obj) {
  4226. if (!obj.hasOwnProperty(i)) {
  4227. continue;
  4228. }
  4229. var value = obj[i];
  4230. var type = typeof value;
  4231. if (i === 'parent' && type === 'object') {
  4232. if (parent) {
  4233. cloned[i] = parent;
  4234. }
  4235. } else if (value instanceof Array) {
  4236. cloned[i] = value.map(function (j) {
  4237. return cloneNode(j, cloned);
  4238. });
  4239. } else {
  4240. cloned[i] = cloneNode(value, cloned);
  4241. }
  4242. }
  4243. return cloned;
  4244. };
  4245. var Node = /*#__PURE__*/function () {
  4246. function Node(opts) {
  4247. if (opts === void 0) {
  4248. opts = {};
  4249. }
  4250. Object.assign(this, opts);
  4251. this.spaces = this.spaces || {};
  4252. this.spaces.before = this.spaces.before || '';
  4253. this.spaces.after = this.spaces.after || '';
  4254. }
  4255. var _proto = Node.prototype;
  4256. _proto.remove = function remove() {
  4257. if (this.parent) {
  4258. this.parent.removeChild(this);
  4259. }
  4260. this.parent = undefined;
  4261. return this;
  4262. };
  4263. _proto.replaceWith = function replaceWith() {
  4264. if (this.parent) {
  4265. for (var index in arguments) {
  4266. this.parent.insertBefore(this, arguments[index]);
  4267. }
  4268. this.remove();
  4269. }
  4270. return this;
  4271. };
  4272. _proto.next = function next() {
  4273. return this.parent.at(this.parent.index(this) + 1);
  4274. };
  4275. _proto.prev = function prev() {
  4276. return this.parent.at(this.parent.index(this) - 1);
  4277. };
  4278. _proto.clone = function clone(overrides) {
  4279. if (overrides === void 0) {
  4280. overrides = {};
  4281. }
  4282. var cloned = cloneNode(this);
  4283. for (var name in overrides) {
  4284. cloned[name] = overrides[name];
  4285. }
  4286. return cloned;
  4287. }
  4288. /**
  4289. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4290. * This allows non standard syntax to be appended to an existing property
  4291. * by specifying the escaped value. By specifying the escaped value,
  4292. * illegal characters are allowed to be directly inserted into css output.
  4293. * @param {string} name the property to set
  4294. * @param {any} value the unescaped value of the property
  4295. * @param {string} valueEscaped optional. the escaped value of the property.
  4296. */;
  4297. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4298. if (!this.raws) {
  4299. this.raws = {};
  4300. }
  4301. var originalValue = this[name];
  4302. var originalEscaped = this.raws[name];
  4303. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4304. if (originalEscaped || valueEscaped !== value) {
  4305. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4306. } else {
  4307. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4308. }
  4309. }
  4310. /**
  4311. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4312. * This allows the escaped value to be specified directly, allowing illegal
  4313. * characters to be directly inserted into css output.
  4314. * @param {string} name the property to set
  4315. * @param {any} value the unescaped value of the property
  4316. * @param {string} valueEscaped the escaped value of the property.
  4317. */;
  4318. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4319. if (!this.raws) {
  4320. this.raws = {};
  4321. }
  4322. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4323. this.raws[name] = valueEscaped;
  4324. }
  4325. /**
  4326. * When you want a value to passed through to CSS directly. This method
  4327. * deletes the corresponding raw value causing the stringifier to fallback
  4328. * to the unescaped value.
  4329. * @param {string} name the property to set.
  4330. * @param {any} value The value that is both escaped and unescaped.
  4331. */;
  4332. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4333. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4334. if (this.raws) {
  4335. delete this.raws[name];
  4336. }
  4337. }
  4338. /**
  4339. *
  4340. * @param {number} line The number (starting with 1)
  4341. * @param {number} column The column number (starting with 1)
  4342. */;
  4343. _proto.isAtPosition = function isAtPosition(line, column) {
  4344. if (this.source && this.source.start && this.source.end) {
  4345. if (this.source.start.line > line) {
  4346. return false;
  4347. }
  4348. if (this.source.end.line < line) {
  4349. return false;
  4350. }
  4351. if (this.source.start.line === line && this.source.start.column > column) {
  4352. return false;
  4353. }
  4354. if (this.source.end.line === line && this.source.end.column < column) {
  4355. return false;
  4356. }
  4357. return true;
  4358. }
  4359. return undefined;
  4360. };
  4361. _proto.stringifyProperty = function stringifyProperty(name) {
  4362. return this.raws && this.raws[name] || this[name];
  4363. };
  4364. _proto.valueToString = function valueToString() {
  4365. return String(this.stringifyProperty("value"));
  4366. };
  4367. _proto.toString = function toString() {
  4368. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4369. };
  4370. _createClass(Node, [{
  4371. key: "rawSpaceBefore",
  4372. get: function get() {
  4373. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4374. if (rawSpace === undefined) {
  4375. rawSpace = this.spaces && this.spaces.before;
  4376. }
  4377. return rawSpace || "";
  4378. },
  4379. set: function set(raw) {
  4380. (0, _util.ensureObject)(this, "raws", "spaces");
  4381. this.raws.spaces.before = raw;
  4382. }
  4383. }, {
  4384. key: "rawSpaceAfter",
  4385. get: function get() {
  4386. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4387. if (rawSpace === undefined) {
  4388. rawSpace = this.spaces.after;
  4389. }
  4390. return rawSpace || "";
  4391. },
  4392. set: function set(raw) {
  4393. (0, _util.ensureObject)(this, "raws", "spaces");
  4394. this.raws.spaces.after = raw;
  4395. }
  4396. }]);
  4397. return Node;
  4398. }();
  4399. exports["default"] = Node;
  4400. module.exports = exports.default;
  4401. } (node$1, node$1.exports));
  4402. var nodeExports = node$1.exports;
  4403. var types$1 = {};
  4404. types$1.__esModule = true;
  4405. 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;
  4406. var TAG = 'tag';
  4407. types$1.TAG = TAG;
  4408. var STRING = 'string';
  4409. types$1.STRING = STRING;
  4410. var SELECTOR = 'selector';
  4411. types$1.SELECTOR = SELECTOR;
  4412. var ROOT = 'root';
  4413. types$1.ROOT = ROOT;
  4414. var PSEUDO = 'pseudo';
  4415. types$1.PSEUDO = PSEUDO;
  4416. var NESTING = 'nesting';
  4417. types$1.NESTING = NESTING;
  4418. var ID = 'id';
  4419. types$1.ID = ID;
  4420. var COMMENT = 'comment';
  4421. types$1.COMMENT = COMMENT;
  4422. var COMBINATOR = 'combinator';
  4423. types$1.COMBINATOR = COMBINATOR;
  4424. var CLASS = 'class';
  4425. types$1.CLASS = CLASS;
  4426. var ATTRIBUTE = 'attribute';
  4427. types$1.ATTRIBUTE = ATTRIBUTE;
  4428. var UNIVERSAL = 'universal';
  4429. types$1.UNIVERSAL = UNIVERSAL;
  4430. (function (module, exports) {
  4431. exports.__esModule = true;
  4432. exports["default"] = void 0;
  4433. var _node = _interopRequireDefault(nodeExports);
  4434. var types = _interopRequireWildcard(types$1);
  4435. 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); }
  4436. 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; }
  4437. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4438. 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."); }
  4439. 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); }
  4440. 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; }
  4441. 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); } }
  4442. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4443. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4444. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4445. var Container = /*#__PURE__*/function (_Node) {
  4446. _inheritsLoose(Container, _Node);
  4447. function Container(opts) {
  4448. var _this;
  4449. _this = _Node.call(this, opts) || this;
  4450. if (!_this.nodes) {
  4451. _this.nodes = [];
  4452. }
  4453. return _this;
  4454. }
  4455. var _proto = Container.prototype;
  4456. _proto.append = function append(selector) {
  4457. selector.parent = this;
  4458. this.nodes.push(selector);
  4459. return this;
  4460. };
  4461. _proto.prepend = function prepend(selector) {
  4462. selector.parent = this;
  4463. this.nodes.unshift(selector);
  4464. return this;
  4465. };
  4466. _proto.at = function at(index) {
  4467. return this.nodes[index];
  4468. };
  4469. _proto.index = function index(child) {
  4470. if (typeof child === 'number') {
  4471. return child;
  4472. }
  4473. return this.nodes.indexOf(child);
  4474. };
  4475. _proto.removeChild = function removeChild(child) {
  4476. child = this.index(child);
  4477. this.at(child).parent = undefined;
  4478. this.nodes.splice(child, 1);
  4479. var index;
  4480. for (var id in this.indexes) {
  4481. index = this.indexes[id];
  4482. if (index >= child) {
  4483. this.indexes[id] = index - 1;
  4484. }
  4485. }
  4486. return this;
  4487. };
  4488. _proto.removeAll = function removeAll() {
  4489. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4490. var node = _step.value;
  4491. node.parent = undefined;
  4492. }
  4493. this.nodes = [];
  4494. return this;
  4495. };
  4496. _proto.empty = function empty() {
  4497. return this.removeAll();
  4498. };
  4499. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4500. newNode.parent = this;
  4501. var oldIndex = this.index(oldNode);
  4502. this.nodes.splice(oldIndex + 1, 0, newNode);
  4503. newNode.parent = this;
  4504. var index;
  4505. for (var id in this.indexes) {
  4506. index = this.indexes[id];
  4507. if (oldIndex <= index) {
  4508. this.indexes[id] = index + 1;
  4509. }
  4510. }
  4511. return this;
  4512. };
  4513. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4514. newNode.parent = this;
  4515. var oldIndex = this.index(oldNode);
  4516. this.nodes.splice(oldIndex, 0, newNode);
  4517. newNode.parent = this;
  4518. var index;
  4519. for (var id in this.indexes) {
  4520. index = this.indexes[id];
  4521. if (index <= oldIndex) {
  4522. this.indexes[id] = index + 1;
  4523. }
  4524. }
  4525. return this;
  4526. };
  4527. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4528. var found = undefined;
  4529. this.each(function (node) {
  4530. if (node.atPosition) {
  4531. var foundChild = node.atPosition(line, col);
  4532. if (foundChild) {
  4533. found = foundChild;
  4534. return false;
  4535. }
  4536. } else if (node.isAtPosition(line, col)) {
  4537. found = node;
  4538. return false;
  4539. }
  4540. });
  4541. return found;
  4542. }
  4543. /**
  4544. * Return the most specific node at the line and column number given.
  4545. * The source location is based on the original parsed location, locations aren't
  4546. * updated as selector nodes are mutated.
  4547. *
  4548. * Note that this location is relative to the location of the first character
  4549. * of the selector, and not the location of the selector in the overall document
  4550. * when used in conjunction with postcss.
  4551. *
  4552. * If not found, returns undefined.
  4553. * @param {number} line The line number of the node to find. (1-based index)
  4554. * @param {number} col The column number of the node to find. (1-based index)
  4555. */;
  4556. _proto.atPosition = function atPosition(line, col) {
  4557. if (this.isAtPosition(line, col)) {
  4558. return this._findChildAtPosition(line, col) || this;
  4559. } else {
  4560. return undefined;
  4561. }
  4562. };
  4563. _proto._inferEndPosition = function _inferEndPosition() {
  4564. if (this.last && this.last.source && this.last.source.end) {
  4565. this.source = this.source || {};
  4566. this.source.end = this.source.end || {};
  4567. Object.assign(this.source.end, this.last.source.end);
  4568. }
  4569. };
  4570. _proto.each = function each(callback) {
  4571. if (!this.lastEach) {
  4572. this.lastEach = 0;
  4573. }
  4574. if (!this.indexes) {
  4575. this.indexes = {};
  4576. }
  4577. this.lastEach++;
  4578. var id = this.lastEach;
  4579. this.indexes[id] = 0;
  4580. if (!this.length) {
  4581. return undefined;
  4582. }
  4583. var index, result;
  4584. while (this.indexes[id] < this.length) {
  4585. index = this.indexes[id];
  4586. result = callback(this.at(index), index);
  4587. if (result === false) {
  4588. break;
  4589. }
  4590. this.indexes[id] += 1;
  4591. }
  4592. delete this.indexes[id];
  4593. if (result === false) {
  4594. return false;
  4595. }
  4596. };
  4597. _proto.walk = function walk(callback) {
  4598. return this.each(function (node, i) {
  4599. var result = callback(node, i);
  4600. if (result !== false && node.length) {
  4601. result = node.walk(callback);
  4602. }
  4603. if (result === false) {
  4604. return false;
  4605. }
  4606. });
  4607. };
  4608. _proto.walkAttributes = function walkAttributes(callback) {
  4609. var _this2 = this;
  4610. return this.walk(function (selector) {
  4611. if (selector.type === types.ATTRIBUTE) {
  4612. return callback.call(_this2, selector);
  4613. }
  4614. });
  4615. };
  4616. _proto.walkClasses = function walkClasses(callback) {
  4617. var _this3 = this;
  4618. return this.walk(function (selector) {
  4619. if (selector.type === types.CLASS) {
  4620. return callback.call(_this3, selector);
  4621. }
  4622. });
  4623. };
  4624. _proto.walkCombinators = function walkCombinators(callback) {
  4625. var _this4 = this;
  4626. return this.walk(function (selector) {
  4627. if (selector.type === types.COMBINATOR) {
  4628. return callback.call(_this4, selector);
  4629. }
  4630. });
  4631. };
  4632. _proto.walkComments = function walkComments(callback) {
  4633. var _this5 = this;
  4634. return this.walk(function (selector) {
  4635. if (selector.type === types.COMMENT) {
  4636. return callback.call(_this5, selector);
  4637. }
  4638. });
  4639. };
  4640. _proto.walkIds = function walkIds(callback) {
  4641. var _this6 = this;
  4642. return this.walk(function (selector) {
  4643. if (selector.type === types.ID) {
  4644. return callback.call(_this6, selector);
  4645. }
  4646. });
  4647. };
  4648. _proto.walkNesting = function walkNesting(callback) {
  4649. var _this7 = this;
  4650. return this.walk(function (selector) {
  4651. if (selector.type === types.NESTING) {
  4652. return callback.call(_this7, selector);
  4653. }
  4654. });
  4655. };
  4656. _proto.walkPseudos = function walkPseudos(callback) {
  4657. var _this8 = this;
  4658. return this.walk(function (selector) {
  4659. if (selector.type === types.PSEUDO) {
  4660. return callback.call(_this8, selector);
  4661. }
  4662. });
  4663. };
  4664. _proto.walkTags = function walkTags(callback) {
  4665. var _this9 = this;
  4666. return this.walk(function (selector) {
  4667. if (selector.type === types.TAG) {
  4668. return callback.call(_this9, selector);
  4669. }
  4670. });
  4671. };
  4672. _proto.walkUniversals = function walkUniversals(callback) {
  4673. var _this10 = this;
  4674. return this.walk(function (selector) {
  4675. if (selector.type === types.UNIVERSAL) {
  4676. return callback.call(_this10, selector);
  4677. }
  4678. });
  4679. };
  4680. _proto.split = function split(callback) {
  4681. var _this11 = this;
  4682. var current = [];
  4683. return this.reduce(function (memo, node, index) {
  4684. var split = callback.call(_this11, node);
  4685. current.push(node);
  4686. if (split) {
  4687. memo.push(current);
  4688. current = [];
  4689. } else if (index === _this11.length - 1) {
  4690. memo.push(current);
  4691. }
  4692. return memo;
  4693. }, []);
  4694. };
  4695. _proto.map = function map(callback) {
  4696. return this.nodes.map(callback);
  4697. };
  4698. _proto.reduce = function reduce(callback, memo) {
  4699. return this.nodes.reduce(callback, memo);
  4700. };
  4701. _proto.every = function every(callback) {
  4702. return this.nodes.every(callback);
  4703. };
  4704. _proto.some = function some(callback) {
  4705. return this.nodes.some(callback);
  4706. };
  4707. _proto.filter = function filter(callback) {
  4708. return this.nodes.filter(callback);
  4709. };
  4710. _proto.sort = function sort(callback) {
  4711. return this.nodes.sort(callback);
  4712. };
  4713. _proto.toString = function toString() {
  4714. return this.map(String).join('');
  4715. };
  4716. _createClass(Container, [{
  4717. key: "first",
  4718. get: function get() {
  4719. return this.at(0);
  4720. }
  4721. }, {
  4722. key: "last",
  4723. get: function get() {
  4724. return this.at(this.length - 1);
  4725. }
  4726. }, {
  4727. key: "length",
  4728. get: function get() {
  4729. return this.nodes.length;
  4730. }
  4731. }]);
  4732. return Container;
  4733. }(_node["default"]);
  4734. exports["default"] = Container;
  4735. module.exports = exports.default;
  4736. } (container, container.exports));
  4737. var containerExports = container.exports;
  4738. (function (module, exports) {
  4739. exports.__esModule = true;
  4740. exports["default"] = void 0;
  4741. var _container = _interopRequireDefault(containerExports);
  4742. var _types = types$1;
  4743. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4744. 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); } }
  4745. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4746. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4747. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4748. var Root = /*#__PURE__*/function (_Container) {
  4749. _inheritsLoose(Root, _Container);
  4750. function Root(opts) {
  4751. var _this;
  4752. _this = _Container.call(this, opts) || this;
  4753. _this.type = _types.ROOT;
  4754. return _this;
  4755. }
  4756. var _proto = Root.prototype;
  4757. _proto.toString = function toString() {
  4758. var str = this.reduce(function (memo, selector) {
  4759. memo.push(String(selector));
  4760. return memo;
  4761. }, []).join(',');
  4762. return this.trailingComma ? str + ',' : str;
  4763. };
  4764. _proto.error = function error(message, options) {
  4765. if (this._error) {
  4766. return this._error(message, options);
  4767. } else {
  4768. return new Error(message);
  4769. }
  4770. };
  4771. _createClass(Root, [{
  4772. key: "errorGenerator",
  4773. set: function set(handler) {
  4774. this._error = handler;
  4775. }
  4776. }]);
  4777. return Root;
  4778. }(_container["default"]);
  4779. exports["default"] = Root;
  4780. module.exports = exports.default;
  4781. } (root$2, root$2.exports));
  4782. var rootExports = root$2.exports;
  4783. var selector$1 = {exports: {}};
  4784. (function (module, exports) {
  4785. exports.__esModule = true;
  4786. exports["default"] = void 0;
  4787. var _container = _interopRequireDefault(containerExports);
  4788. var _types = types$1;
  4789. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4790. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4791. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4792. var Selector = /*#__PURE__*/function (_Container) {
  4793. _inheritsLoose(Selector, _Container);
  4794. function Selector(opts) {
  4795. var _this;
  4796. _this = _Container.call(this, opts) || this;
  4797. _this.type = _types.SELECTOR;
  4798. return _this;
  4799. }
  4800. return Selector;
  4801. }(_container["default"]);
  4802. exports["default"] = Selector;
  4803. module.exports = exports.default;
  4804. } (selector$1, selector$1.exports));
  4805. var selectorExports = selector$1.exports;
  4806. var className$1 = {exports: {}};
  4807. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4808. var object = {};
  4809. var hasOwnProperty$1 = object.hasOwnProperty;
  4810. var merge$2 = function merge(options, defaults) {
  4811. if (!options) {
  4812. return defaults;
  4813. }
  4814. var result = {};
  4815. for (var key in defaults) {
  4816. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4817. // only recognized option names are used.
  4818. result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key];
  4819. }
  4820. return result;
  4821. };
  4822. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4823. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4824. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4825. // https://mathiasbynens.be/notes/css-escapes#css
  4826. var cssesc = function cssesc(string, options) {
  4827. options = merge$2(options, cssesc.options);
  4828. if (options.quotes != 'single' && options.quotes != 'double') {
  4829. options.quotes = 'single';
  4830. }
  4831. var quote = options.quotes == 'double' ? '"' : '\'';
  4832. var isIdentifier = options.isIdentifier;
  4833. var firstChar = string.charAt(0);
  4834. var output = '';
  4835. var counter = 0;
  4836. var length = string.length;
  4837. while (counter < length) {
  4838. var character = string.charAt(counter++);
  4839. var codePoint = character.charCodeAt();
  4840. var value = void 0;
  4841. // If it’s not a printable ASCII character…
  4842. if (codePoint < 0x20 || codePoint > 0x7E) {
  4843. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4844. // It’s a high surrogate, and there is a next character.
  4845. var extra = string.charCodeAt(counter++);
  4846. if ((extra & 0xFC00) == 0xDC00) {
  4847. // next character is low surrogate
  4848. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4849. } else {
  4850. // It’s an unmatched surrogate; only append this code unit, in case
  4851. // the next code unit is the high surrogate of a surrogate pair.
  4852. counter--;
  4853. }
  4854. }
  4855. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4856. } else {
  4857. if (options.escapeEverything) {
  4858. if (regexAnySingleEscape.test(character)) {
  4859. value = '\\' + character;
  4860. } else {
  4861. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4862. }
  4863. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4864. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4865. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4866. value = '\\' + character;
  4867. } else {
  4868. value = character;
  4869. }
  4870. }
  4871. output += value;
  4872. }
  4873. if (isIdentifier) {
  4874. if (/^-[-\d]/.test(output)) {
  4875. output = '\\-' + output.slice(1);
  4876. } else if (/\d/.test(firstChar)) {
  4877. output = '\\3' + firstChar + ' ' + output.slice(1);
  4878. }
  4879. }
  4880. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4881. // since they’re redundant. Note that this is only possible if the escape
  4882. // sequence isn’t preceded by an odd number of backslashes.
  4883. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4884. if ($1 && $1.length % 2) {
  4885. // It’s not safe to remove the space, so don’t.
  4886. return $0;
  4887. }
  4888. // Strip the space.
  4889. return ($1 || '') + $2;
  4890. });
  4891. if (!isIdentifier && options.wrap) {
  4892. return quote + output + quote;
  4893. }
  4894. return output;
  4895. };
  4896. // Expose default options (so they can be overridden globally).
  4897. cssesc.options = {
  4898. 'escapeEverything': false,
  4899. 'isIdentifier': false,
  4900. 'quotes': 'single',
  4901. 'wrap': false
  4902. };
  4903. cssesc.version = '3.0.0';
  4904. var cssesc_1 = cssesc;
  4905. (function (module, exports) {
  4906. exports.__esModule = true;
  4907. exports["default"] = void 0;
  4908. var _cssesc = _interopRequireDefault(cssesc_1);
  4909. var _util = util$6;
  4910. var _node = _interopRequireDefault(nodeExports);
  4911. var _types = types$1;
  4912. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4913. 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); } }
  4914. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4915. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4916. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4917. var ClassName = /*#__PURE__*/function (_Node) {
  4918. _inheritsLoose(ClassName, _Node);
  4919. function ClassName(opts) {
  4920. var _this;
  4921. _this = _Node.call(this, opts) || this;
  4922. _this.type = _types.CLASS;
  4923. _this._constructed = true;
  4924. return _this;
  4925. }
  4926. var _proto = ClassName.prototype;
  4927. _proto.valueToString = function valueToString() {
  4928. return '.' + _Node.prototype.valueToString.call(this);
  4929. };
  4930. _createClass(ClassName, [{
  4931. key: "value",
  4932. get: function get() {
  4933. return this._value;
  4934. },
  4935. set: function set(v) {
  4936. if (this._constructed) {
  4937. var escaped = (0, _cssesc["default"])(v, {
  4938. isIdentifier: true
  4939. });
  4940. if (escaped !== v) {
  4941. (0, _util.ensureObject)(this, "raws");
  4942. this.raws.value = escaped;
  4943. } else if (this.raws) {
  4944. delete this.raws.value;
  4945. }
  4946. }
  4947. this._value = v;
  4948. }
  4949. }]);
  4950. return ClassName;
  4951. }(_node["default"]);
  4952. exports["default"] = ClassName;
  4953. module.exports = exports.default;
  4954. } (className$1, className$1.exports));
  4955. var classNameExports = className$1.exports;
  4956. var comment$2 = {exports: {}};
  4957. (function (module, exports) {
  4958. exports.__esModule = true;
  4959. exports["default"] = void 0;
  4960. var _node = _interopRequireDefault(nodeExports);
  4961. var _types = types$1;
  4962. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4963. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4964. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4965. var Comment = /*#__PURE__*/function (_Node) {
  4966. _inheritsLoose(Comment, _Node);
  4967. function Comment(opts) {
  4968. var _this;
  4969. _this = _Node.call(this, opts) || this;
  4970. _this.type = _types.COMMENT;
  4971. return _this;
  4972. }
  4973. return Comment;
  4974. }(_node["default"]);
  4975. exports["default"] = Comment;
  4976. module.exports = exports.default;
  4977. } (comment$2, comment$2.exports));
  4978. var commentExports = comment$2.exports;
  4979. var id$1 = {exports: {}};
  4980. (function (module, exports) {
  4981. exports.__esModule = true;
  4982. exports["default"] = void 0;
  4983. var _node = _interopRequireDefault(nodeExports);
  4984. var _types = types$1;
  4985. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4986. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4987. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4988. var ID = /*#__PURE__*/function (_Node) {
  4989. _inheritsLoose(ID, _Node);
  4990. function ID(opts) {
  4991. var _this;
  4992. _this = _Node.call(this, opts) || this;
  4993. _this.type = _types.ID;
  4994. return _this;
  4995. }
  4996. var _proto = ID.prototype;
  4997. _proto.valueToString = function valueToString() {
  4998. return '#' + _Node.prototype.valueToString.call(this);
  4999. };
  5000. return ID;
  5001. }(_node["default"]);
  5002. exports["default"] = ID;
  5003. module.exports = exports.default;
  5004. } (id$1, id$1.exports));
  5005. var idExports = id$1.exports;
  5006. var tag$1 = {exports: {}};
  5007. var namespace = {exports: {}};
  5008. (function (module, exports) {
  5009. exports.__esModule = true;
  5010. exports["default"] = void 0;
  5011. var _cssesc = _interopRequireDefault(cssesc_1);
  5012. var _util = util$6;
  5013. var _node = _interopRequireDefault(nodeExports);
  5014. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5015. 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); } }
  5016. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5017. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5018. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5019. var Namespace = /*#__PURE__*/function (_Node) {
  5020. _inheritsLoose(Namespace, _Node);
  5021. function Namespace() {
  5022. return _Node.apply(this, arguments) || this;
  5023. }
  5024. var _proto = Namespace.prototype;
  5025. _proto.qualifiedName = function qualifiedName(value) {
  5026. if (this.namespace) {
  5027. return this.namespaceString + "|" + value;
  5028. } else {
  5029. return value;
  5030. }
  5031. };
  5032. _proto.valueToString = function valueToString() {
  5033. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5034. };
  5035. _createClass(Namespace, [{
  5036. key: "namespace",
  5037. get: function get() {
  5038. return this._namespace;
  5039. },
  5040. set: function set(namespace) {
  5041. if (namespace === true || namespace === "*" || namespace === "&") {
  5042. this._namespace = namespace;
  5043. if (this.raws) {
  5044. delete this.raws.namespace;
  5045. }
  5046. return;
  5047. }
  5048. var escaped = (0, _cssesc["default"])(namespace, {
  5049. isIdentifier: true
  5050. });
  5051. this._namespace = namespace;
  5052. if (escaped !== namespace) {
  5053. (0, _util.ensureObject)(this, "raws");
  5054. this.raws.namespace = escaped;
  5055. } else if (this.raws) {
  5056. delete this.raws.namespace;
  5057. }
  5058. }
  5059. }, {
  5060. key: "ns",
  5061. get: function get() {
  5062. return this._namespace;
  5063. },
  5064. set: function set(namespace) {
  5065. this.namespace = namespace;
  5066. }
  5067. }, {
  5068. key: "namespaceString",
  5069. get: function get() {
  5070. if (this.namespace) {
  5071. var ns = this.stringifyProperty("namespace");
  5072. if (ns === true) {
  5073. return '';
  5074. } else {
  5075. return ns;
  5076. }
  5077. } else {
  5078. return '';
  5079. }
  5080. }
  5081. }]);
  5082. return Namespace;
  5083. }(_node["default"]);
  5084. exports["default"] = Namespace;
  5085. module.exports = exports.default;
  5086. } (namespace, namespace.exports));
  5087. var namespaceExports = namespace.exports;
  5088. (function (module, exports) {
  5089. exports.__esModule = true;
  5090. exports["default"] = void 0;
  5091. var _namespace = _interopRequireDefault(namespaceExports);
  5092. var _types = types$1;
  5093. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5094. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5095. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5096. var Tag = /*#__PURE__*/function (_Namespace) {
  5097. _inheritsLoose(Tag, _Namespace);
  5098. function Tag(opts) {
  5099. var _this;
  5100. _this = _Namespace.call(this, opts) || this;
  5101. _this.type = _types.TAG;
  5102. return _this;
  5103. }
  5104. return Tag;
  5105. }(_namespace["default"]);
  5106. exports["default"] = Tag;
  5107. module.exports = exports.default;
  5108. } (tag$1, tag$1.exports));
  5109. var tagExports = tag$1.exports;
  5110. var string$1 = {exports: {}};
  5111. (function (module, exports) {
  5112. exports.__esModule = true;
  5113. exports["default"] = void 0;
  5114. var _node = _interopRequireDefault(nodeExports);
  5115. var _types = types$1;
  5116. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5117. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5118. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5119. var String = /*#__PURE__*/function (_Node) {
  5120. _inheritsLoose(String, _Node);
  5121. function String(opts) {
  5122. var _this;
  5123. _this = _Node.call(this, opts) || this;
  5124. _this.type = _types.STRING;
  5125. return _this;
  5126. }
  5127. return String;
  5128. }(_node["default"]);
  5129. exports["default"] = String;
  5130. module.exports = exports.default;
  5131. } (string$1, string$1.exports));
  5132. var stringExports = string$1.exports;
  5133. var pseudo$1 = {exports: {}};
  5134. (function (module, exports) {
  5135. exports.__esModule = true;
  5136. exports["default"] = void 0;
  5137. var _container = _interopRequireDefault(containerExports);
  5138. var _types = types$1;
  5139. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5140. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5141. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5142. var Pseudo = /*#__PURE__*/function (_Container) {
  5143. _inheritsLoose(Pseudo, _Container);
  5144. function Pseudo(opts) {
  5145. var _this;
  5146. _this = _Container.call(this, opts) || this;
  5147. _this.type = _types.PSEUDO;
  5148. return _this;
  5149. }
  5150. var _proto = Pseudo.prototype;
  5151. _proto.toString = function toString() {
  5152. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5153. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5154. };
  5155. return Pseudo;
  5156. }(_container["default"]);
  5157. exports["default"] = Pseudo;
  5158. module.exports = exports.default;
  5159. } (pseudo$1, pseudo$1.exports));
  5160. var pseudoExports = pseudo$1.exports;
  5161. var attribute$1 = {};
  5162. /**
  5163. * For Node.js, simply re-export the core `util.deprecate` function.
  5164. */
  5165. var node = require$$2.deprecate;
  5166. (function (exports) {
  5167. exports.__esModule = true;
  5168. exports["default"] = void 0;
  5169. exports.unescapeValue = unescapeValue;
  5170. var _cssesc = _interopRequireDefault(cssesc_1);
  5171. var _unesc = _interopRequireDefault(unescExports);
  5172. var _namespace = _interopRequireDefault(namespaceExports);
  5173. var _types = types$1;
  5174. var _CSSESC_QUOTE_OPTIONS;
  5175. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5176. 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); } }
  5177. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5178. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5179. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5180. var deprecate = node;
  5181. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5182. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5183. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5184. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5185. function unescapeValue(value) {
  5186. var deprecatedUsage = false;
  5187. var quoteMark = null;
  5188. var unescaped = value;
  5189. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5190. if (m) {
  5191. quoteMark = m[1];
  5192. unescaped = m[2];
  5193. }
  5194. unescaped = (0, _unesc["default"])(unescaped);
  5195. if (unescaped !== value) {
  5196. deprecatedUsage = true;
  5197. }
  5198. return {
  5199. deprecatedUsage: deprecatedUsage,
  5200. unescaped: unescaped,
  5201. quoteMark: quoteMark
  5202. };
  5203. }
  5204. function handleDeprecatedContructorOpts(opts) {
  5205. if (opts.quoteMark !== undefined) {
  5206. return opts;
  5207. }
  5208. if (opts.value === undefined) {
  5209. return opts;
  5210. }
  5211. warnOfDeprecatedConstructor();
  5212. var _unescapeValue = unescapeValue(opts.value),
  5213. quoteMark = _unescapeValue.quoteMark,
  5214. unescaped = _unescapeValue.unescaped;
  5215. if (!opts.raws) {
  5216. opts.raws = {};
  5217. }
  5218. if (opts.raws.value === undefined) {
  5219. opts.raws.value = opts.value;
  5220. }
  5221. opts.value = unescaped;
  5222. opts.quoteMark = quoteMark;
  5223. return opts;
  5224. }
  5225. var Attribute = /*#__PURE__*/function (_Namespace) {
  5226. _inheritsLoose(Attribute, _Namespace);
  5227. function Attribute(opts) {
  5228. var _this;
  5229. if (opts === void 0) {
  5230. opts = {};
  5231. }
  5232. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5233. _this.type = _types.ATTRIBUTE;
  5234. _this.raws = _this.raws || {};
  5235. Object.defineProperty(_this.raws, 'unquoted', {
  5236. get: deprecate(function () {
  5237. return _this.value;
  5238. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5239. set: deprecate(function () {
  5240. return _this.value;
  5241. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5242. });
  5243. _this._constructed = true;
  5244. return _this;
  5245. }
  5246. /**
  5247. * Returns the Attribute's value quoted such that it would be legal to use
  5248. * in the value of a css file. The original value's quotation setting
  5249. * used for stringification is left unchanged. See `setValue(value, options)`
  5250. * if you want to control the quote settings of a new value for the attribute.
  5251. *
  5252. * You can also change the quotation used for the current value by setting quoteMark.
  5253. *
  5254. * Options:
  5255. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5256. * option is not set, the original value for quoteMark will be used. If
  5257. * indeterminate, a double quote is used. The legal values are:
  5258. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5259. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5260. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5261. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5262. * over the quoteMark option value.
  5263. * * smart {boolean} - if true, will select a quote mark based on the value
  5264. * and the other options specified here. See the `smartQuoteMark()`
  5265. * method.
  5266. **/
  5267. var _proto = Attribute.prototype;
  5268. _proto.getQuotedValue = function getQuotedValue(options) {
  5269. if (options === void 0) {
  5270. options = {};
  5271. }
  5272. var quoteMark = this._determineQuoteMark(options);
  5273. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5274. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5275. return escaped;
  5276. };
  5277. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5278. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5279. }
  5280. /**
  5281. * Set the unescaped value with the specified quotation options. The value
  5282. * provided must not include any wrapping quote marks -- those quotes will
  5283. * be interpreted as part of the value and escaped accordingly.
  5284. */;
  5285. _proto.setValue = function setValue(value, options) {
  5286. if (options === void 0) {
  5287. options = {};
  5288. }
  5289. this._value = value;
  5290. this._quoteMark = this._determineQuoteMark(options);
  5291. this._syncRawValue();
  5292. }
  5293. /**
  5294. * Intelligently select a quoteMark value based on the value's contents. If
  5295. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5296. * mark will be picked that minimizes the number of escapes.
  5297. *
  5298. * If there's no clear winner, the quote mark from these options is used,
  5299. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5300. * true). If the quoteMark is unspecified, a double quote is used.
  5301. *
  5302. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5303. * from the quoteValue method.
  5304. */;
  5305. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5306. var v = this.value;
  5307. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5308. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5309. if (numSingleQuotes + numDoubleQuotes === 0) {
  5310. var escaped = (0, _cssesc["default"])(v, {
  5311. isIdentifier: true
  5312. });
  5313. if (escaped === v) {
  5314. return Attribute.NO_QUOTE;
  5315. } else {
  5316. var pref = this.preferredQuoteMark(options);
  5317. if (pref === Attribute.NO_QUOTE) {
  5318. // pick a quote mark that isn't none and see if it's smaller
  5319. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5320. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5321. var quoteValue = (0, _cssesc["default"])(v, opts);
  5322. if (quoteValue.length < escaped.length) {
  5323. return quote;
  5324. }
  5325. }
  5326. return pref;
  5327. }
  5328. } else if (numDoubleQuotes === numSingleQuotes) {
  5329. return this.preferredQuoteMark(options);
  5330. } else if (numDoubleQuotes < numSingleQuotes) {
  5331. return Attribute.DOUBLE_QUOTE;
  5332. } else {
  5333. return Attribute.SINGLE_QUOTE;
  5334. }
  5335. }
  5336. /**
  5337. * Selects the preferred quote mark based on the options and the current quote mark value.
  5338. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5339. * instead.
  5340. */;
  5341. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5342. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5343. if (quoteMark === undefined) {
  5344. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5345. }
  5346. if (quoteMark === undefined) {
  5347. quoteMark = Attribute.DOUBLE_QUOTE;
  5348. }
  5349. return quoteMark;
  5350. };
  5351. _proto._syncRawValue = function _syncRawValue() {
  5352. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5353. if (rawValue === this._value) {
  5354. if (this.raws) {
  5355. delete this.raws.value;
  5356. }
  5357. } else {
  5358. this.raws.value = rawValue;
  5359. }
  5360. };
  5361. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5362. if (this._constructed) {
  5363. var escaped = (0, _cssesc["default"])(value, {
  5364. isIdentifier: true
  5365. });
  5366. if (escaped !== value) {
  5367. this.raws[prop] = escaped;
  5368. } else {
  5369. delete this.raws[prop];
  5370. }
  5371. }
  5372. };
  5373. _proto._spacesFor = function _spacesFor(name) {
  5374. var attrSpaces = {
  5375. before: '',
  5376. after: ''
  5377. };
  5378. var spaces = this.spaces[name] || {};
  5379. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5380. return Object.assign(attrSpaces, spaces, rawSpaces);
  5381. };
  5382. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5383. if (spaceName === void 0) {
  5384. spaceName = name;
  5385. }
  5386. if (concat === void 0) {
  5387. concat = defaultAttrConcat;
  5388. }
  5389. var attrSpaces = this._spacesFor(spaceName);
  5390. return concat(this.stringifyProperty(name), attrSpaces);
  5391. }
  5392. /**
  5393. * returns the offset of the attribute part specified relative to the
  5394. * start of the node of the output string.
  5395. *
  5396. * * "ns" - alias for "namespace"
  5397. * * "namespace" - the namespace if it exists.
  5398. * * "attribute" - the attribute name
  5399. * * "attributeNS" - the start of the attribute or its namespace
  5400. * * "operator" - the match operator of the attribute
  5401. * * "value" - The value (string or identifier)
  5402. * * "insensitive" - the case insensitivity flag;
  5403. * @param part One of the possible values inside an attribute.
  5404. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5405. */;
  5406. _proto.offsetOf = function offsetOf(name) {
  5407. var count = 1;
  5408. var attributeSpaces = this._spacesFor("attribute");
  5409. count += attributeSpaces.before.length;
  5410. if (name === "namespace" || name === "ns") {
  5411. return this.namespace ? count : -1;
  5412. }
  5413. if (name === "attributeNS") {
  5414. return count;
  5415. }
  5416. count += this.namespaceString.length;
  5417. if (this.namespace) {
  5418. count += 1;
  5419. }
  5420. if (name === "attribute") {
  5421. return count;
  5422. }
  5423. count += this.stringifyProperty("attribute").length;
  5424. count += attributeSpaces.after.length;
  5425. var operatorSpaces = this._spacesFor("operator");
  5426. count += operatorSpaces.before.length;
  5427. var operator = this.stringifyProperty("operator");
  5428. if (name === "operator") {
  5429. return operator ? count : -1;
  5430. }
  5431. count += operator.length;
  5432. count += operatorSpaces.after.length;
  5433. var valueSpaces = this._spacesFor("value");
  5434. count += valueSpaces.before.length;
  5435. var value = this.stringifyProperty("value");
  5436. if (name === "value") {
  5437. return value ? count : -1;
  5438. }
  5439. count += value.length;
  5440. count += valueSpaces.after.length;
  5441. var insensitiveSpaces = this._spacesFor("insensitive");
  5442. count += insensitiveSpaces.before.length;
  5443. if (name === "insensitive") {
  5444. return this.insensitive ? count : -1;
  5445. }
  5446. return -1;
  5447. };
  5448. _proto.toString = function toString() {
  5449. var _this2 = this;
  5450. var selector = [this.rawSpaceBefore, '['];
  5451. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5452. if (this.operator && (this.value || this.value === '')) {
  5453. selector.push(this._stringFor('operator'));
  5454. selector.push(this._stringFor('value'));
  5455. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5456. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5457. attrSpaces.before = " ";
  5458. }
  5459. return defaultAttrConcat(attrValue, attrSpaces);
  5460. }));
  5461. }
  5462. selector.push(']');
  5463. selector.push(this.rawSpaceAfter);
  5464. return selector.join('');
  5465. };
  5466. _createClass(Attribute, [{
  5467. key: "quoted",
  5468. get: function get() {
  5469. var qm = this.quoteMark;
  5470. return qm === "'" || qm === '"';
  5471. },
  5472. set: function set(value) {
  5473. warnOfDeprecatedQuotedAssignment();
  5474. }
  5475. /**
  5476. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5477. * returns `null` if the value is not quoted.
  5478. * returns `undefined` if the quotation state is unknown (this can happen when
  5479. * the attribute is constructed without specifying a quote mark.)
  5480. */
  5481. }, {
  5482. key: "quoteMark",
  5483. get: function get() {
  5484. return this._quoteMark;
  5485. }
  5486. /**
  5487. * Set the quote mark to be used by this attribute's value.
  5488. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5489. * value is updated accordingly.
  5490. *
  5491. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5492. */,
  5493. set: function set(quoteMark) {
  5494. if (!this._constructed) {
  5495. this._quoteMark = quoteMark;
  5496. return;
  5497. }
  5498. if (this._quoteMark !== quoteMark) {
  5499. this._quoteMark = quoteMark;
  5500. this._syncRawValue();
  5501. }
  5502. }
  5503. }, {
  5504. key: "qualifiedAttribute",
  5505. get: function get() {
  5506. return this.qualifiedName(this.raws.attribute || this.attribute);
  5507. }
  5508. }, {
  5509. key: "insensitiveFlag",
  5510. get: function get() {
  5511. return this.insensitive ? 'i' : '';
  5512. }
  5513. }, {
  5514. key: "value",
  5515. get: function get() {
  5516. return this._value;
  5517. },
  5518. set:
  5519. /**
  5520. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5521. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5522. * is unescaped during parsing and any quote marks are removed.
  5523. *
  5524. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5525. * a deprecation warning is raised when the new value contains any characters that would
  5526. * require escaping (including if it contains wrapped quotes).
  5527. *
  5528. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5529. * how the new value is quoted.
  5530. */
  5531. function set(v) {
  5532. if (this._constructed) {
  5533. var _unescapeValue2 = unescapeValue(v),
  5534. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5535. unescaped = _unescapeValue2.unescaped,
  5536. quoteMark = _unescapeValue2.quoteMark;
  5537. if (deprecatedUsage) {
  5538. warnOfDeprecatedValueAssignment();
  5539. }
  5540. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5541. return;
  5542. }
  5543. this._value = unescaped;
  5544. this._quoteMark = quoteMark;
  5545. this._syncRawValue();
  5546. } else {
  5547. this._value = v;
  5548. }
  5549. }
  5550. }, {
  5551. key: "insensitive",
  5552. get: function get() {
  5553. return this._insensitive;
  5554. }
  5555. /**
  5556. * Set the case insensitive flag.
  5557. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5558. * of the attribute is updated accordingly.
  5559. *
  5560. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5561. */,
  5562. set: function set(insensitive) {
  5563. if (!insensitive) {
  5564. this._insensitive = false;
  5565. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5566. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5567. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5568. this.raws.insensitiveFlag = undefined;
  5569. }
  5570. }
  5571. this._insensitive = insensitive;
  5572. }
  5573. }, {
  5574. key: "attribute",
  5575. get: function get() {
  5576. return this._attribute;
  5577. },
  5578. set: function set(name) {
  5579. this._handleEscapes("attribute", name);
  5580. this._attribute = name;
  5581. }
  5582. }]);
  5583. return Attribute;
  5584. }(_namespace["default"]);
  5585. exports["default"] = Attribute;
  5586. Attribute.NO_QUOTE = null;
  5587. Attribute.SINGLE_QUOTE = "'";
  5588. Attribute.DOUBLE_QUOTE = '"';
  5589. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5590. "'": {
  5591. quotes: 'single',
  5592. wrap: true
  5593. },
  5594. '"': {
  5595. quotes: 'double',
  5596. wrap: true
  5597. }
  5598. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5599. isIdentifier: true
  5600. }, _CSSESC_QUOTE_OPTIONS);
  5601. function defaultAttrConcat(attrValue, attrSpaces) {
  5602. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5603. }
  5604. } (attribute$1));
  5605. var universal$1 = {exports: {}};
  5606. (function (module, exports) {
  5607. exports.__esModule = true;
  5608. exports["default"] = void 0;
  5609. var _namespace = _interopRequireDefault(namespaceExports);
  5610. var _types = types$1;
  5611. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5612. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5613. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5614. var Universal = /*#__PURE__*/function (_Namespace) {
  5615. _inheritsLoose(Universal, _Namespace);
  5616. function Universal(opts) {
  5617. var _this;
  5618. _this = _Namespace.call(this, opts) || this;
  5619. _this.type = _types.UNIVERSAL;
  5620. _this.value = '*';
  5621. return _this;
  5622. }
  5623. return Universal;
  5624. }(_namespace["default"]);
  5625. exports["default"] = Universal;
  5626. module.exports = exports.default;
  5627. } (universal$1, universal$1.exports));
  5628. var universalExports = universal$1.exports;
  5629. var combinator$2 = {exports: {}};
  5630. (function (module, exports) {
  5631. exports.__esModule = true;
  5632. exports["default"] = void 0;
  5633. var _node = _interopRequireDefault(nodeExports);
  5634. var _types = types$1;
  5635. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5636. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5637. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5638. var Combinator = /*#__PURE__*/function (_Node) {
  5639. _inheritsLoose(Combinator, _Node);
  5640. function Combinator(opts) {
  5641. var _this;
  5642. _this = _Node.call(this, opts) || this;
  5643. _this.type = _types.COMBINATOR;
  5644. return _this;
  5645. }
  5646. return Combinator;
  5647. }(_node["default"]);
  5648. exports["default"] = Combinator;
  5649. module.exports = exports.default;
  5650. } (combinator$2, combinator$2.exports));
  5651. var combinatorExports = combinator$2.exports;
  5652. var nesting$1 = {exports: {}};
  5653. (function (module, exports) {
  5654. exports.__esModule = true;
  5655. exports["default"] = void 0;
  5656. var _node = _interopRequireDefault(nodeExports);
  5657. var _types = types$1;
  5658. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5659. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5660. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5661. var Nesting = /*#__PURE__*/function (_Node) {
  5662. _inheritsLoose(Nesting, _Node);
  5663. function Nesting(opts) {
  5664. var _this;
  5665. _this = _Node.call(this, opts) || this;
  5666. _this.type = _types.NESTING;
  5667. _this.value = '&';
  5668. return _this;
  5669. }
  5670. return Nesting;
  5671. }(_node["default"]);
  5672. exports["default"] = Nesting;
  5673. module.exports = exports.default;
  5674. } (nesting$1, nesting$1.exports));
  5675. var nestingExports = nesting$1.exports;
  5676. var sortAscending = {exports: {}};
  5677. (function (module, exports) {
  5678. exports.__esModule = true;
  5679. exports["default"] = sortAscending;
  5680. function sortAscending(list) {
  5681. return list.sort(function (a, b) {
  5682. return a - b;
  5683. });
  5684. }
  5685. module.exports = exports.default;
  5686. } (sortAscending, sortAscending.exports));
  5687. var sortAscendingExports = sortAscending.exports;
  5688. var tokenize = {};
  5689. var tokenTypes = {};
  5690. tokenTypes.__esModule = true;
  5691. 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;
  5692. var ampersand = 38; // `&`.charCodeAt(0);
  5693. tokenTypes.ampersand = ampersand;
  5694. var asterisk = 42; // `*`.charCodeAt(0);
  5695. tokenTypes.asterisk = asterisk;
  5696. var at = 64; // `@`.charCodeAt(0);
  5697. tokenTypes.at = at;
  5698. var comma$1 = 44; // `,`.charCodeAt(0);
  5699. tokenTypes.comma = comma$1;
  5700. var colon$1 = 58; // `:`.charCodeAt(0);
  5701. tokenTypes.colon = colon$1;
  5702. var semicolon = 59; // `;`.charCodeAt(0);
  5703. tokenTypes.semicolon = semicolon;
  5704. var openParenthesis = 40; // `(`.charCodeAt(0);
  5705. tokenTypes.openParenthesis = openParenthesis;
  5706. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5707. tokenTypes.closeParenthesis = closeParenthesis;
  5708. var openSquare = 91; // `[`.charCodeAt(0);
  5709. tokenTypes.openSquare = openSquare;
  5710. var closeSquare = 93; // `]`.charCodeAt(0);
  5711. tokenTypes.closeSquare = closeSquare;
  5712. var dollar = 36; // `$`.charCodeAt(0);
  5713. tokenTypes.dollar = dollar;
  5714. var tilde = 126; // `~`.charCodeAt(0);
  5715. tokenTypes.tilde = tilde;
  5716. var caret = 94; // `^`.charCodeAt(0);
  5717. tokenTypes.caret = caret;
  5718. var plus$1 = 43; // `+`.charCodeAt(0);
  5719. tokenTypes.plus = plus$1;
  5720. var equals = 61; // `=`.charCodeAt(0);
  5721. tokenTypes.equals = equals;
  5722. var pipe = 124; // `|`.charCodeAt(0);
  5723. tokenTypes.pipe = pipe;
  5724. var greaterThan = 62; // `>`.charCodeAt(0);
  5725. tokenTypes.greaterThan = greaterThan;
  5726. var space = 32; // ` `.charCodeAt(0);
  5727. tokenTypes.space = space;
  5728. var singleQuote$1 = 39; // `'`.charCodeAt(0);
  5729. tokenTypes.singleQuote = singleQuote$1;
  5730. var doubleQuote$1 = 34; // `"`.charCodeAt(0);
  5731. tokenTypes.doubleQuote = doubleQuote$1;
  5732. var slash$1 = 47; // `/`.charCodeAt(0);
  5733. tokenTypes.slash = slash$1;
  5734. var bang = 33; // `!`.charCodeAt(0);
  5735. tokenTypes.bang = bang;
  5736. var backslash$1 = 92; // '\\'.charCodeAt(0);
  5737. tokenTypes.backslash = backslash$1;
  5738. var cr = 13; // '\r'.charCodeAt(0);
  5739. tokenTypes.cr = cr;
  5740. var feed = 12; // '\f'.charCodeAt(0);
  5741. tokenTypes.feed = feed;
  5742. var newline = 10; // '\n'.charCodeAt(0);
  5743. tokenTypes.newline = newline;
  5744. var tab = 9; // '\t'.charCodeAt(0);
  5745. // Expose aliases primarily for readability.
  5746. tokenTypes.tab = tab;
  5747. var str = singleQuote$1;
  5748. // No good single character representation!
  5749. tokenTypes.str = str;
  5750. var comment$1 = -1;
  5751. tokenTypes.comment = comment$1;
  5752. var word = -2;
  5753. tokenTypes.word = word;
  5754. var combinator$1 = -3;
  5755. tokenTypes.combinator = combinator$1;
  5756. (function (exports) {
  5757. exports.__esModule = true;
  5758. exports.FIELDS = void 0;
  5759. exports["default"] = tokenize;
  5760. var t = _interopRequireWildcard(tokenTypes);
  5761. var _unescapable, _wordDelimiters;
  5762. 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); }
  5763. 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; }
  5764. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5765. 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);
  5766. var hex = {};
  5767. var hexChars = "0123456789abcdefABCDEF";
  5768. for (var i = 0; i < hexChars.length; i++) {
  5769. hex[hexChars.charCodeAt(i)] = true;
  5770. }
  5771. /**
  5772. * Returns the last index of the bar css word
  5773. * @param {string} css The string in which the word begins
  5774. * @param {number} start The index into the string where word's first letter occurs
  5775. */
  5776. function consumeWord(css, start) {
  5777. var next = start;
  5778. var code;
  5779. do {
  5780. code = css.charCodeAt(next);
  5781. if (wordDelimiters[code]) {
  5782. return next - 1;
  5783. } else if (code === t.backslash) {
  5784. next = consumeEscape(css, next) + 1;
  5785. } else {
  5786. // All other characters are part of the word
  5787. next++;
  5788. }
  5789. } while (next < css.length);
  5790. return next - 1;
  5791. }
  5792. /**
  5793. * Returns the last index of the escape sequence
  5794. * @param {string} css The string in which the sequence begins
  5795. * @param {number} start The index into the string where escape character (`\`) occurs.
  5796. */
  5797. function consumeEscape(css, start) {
  5798. var next = start;
  5799. var code = css.charCodeAt(next + 1);
  5800. if (unescapable[code]) ; else if (hex[code]) {
  5801. var hexDigits = 0;
  5802. // consume up to 6 hex chars
  5803. do {
  5804. next++;
  5805. hexDigits++;
  5806. code = css.charCodeAt(next + 1);
  5807. } while (hex[code] && hexDigits < 6);
  5808. // if fewer than 6 hex chars, a trailing space ends the escape
  5809. if (hexDigits < 6 && code === t.space) {
  5810. next++;
  5811. }
  5812. } else {
  5813. // the next char is part of the current word
  5814. next++;
  5815. }
  5816. return next;
  5817. }
  5818. var FIELDS = {
  5819. TYPE: 0,
  5820. START_LINE: 1,
  5821. START_COL: 2,
  5822. END_LINE: 3,
  5823. END_COL: 4,
  5824. START_POS: 5,
  5825. END_POS: 6
  5826. };
  5827. exports.FIELDS = FIELDS;
  5828. function tokenize(input) {
  5829. var tokens = [];
  5830. var css = input.css.valueOf();
  5831. var _css = css,
  5832. length = _css.length;
  5833. var offset = -1;
  5834. var line = 1;
  5835. var start = 0;
  5836. var end = 0;
  5837. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  5838. function unclosed(what, fix) {
  5839. if (input.safe) {
  5840. // fyi: this is never set to true.
  5841. css += fix;
  5842. next = css.length - 1;
  5843. } else {
  5844. throw input.error('Unclosed ' + what, line, start - offset, start);
  5845. }
  5846. }
  5847. while (start < length) {
  5848. code = css.charCodeAt(start);
  5849. if (code === t.newline) {
  5850. offset = start;
  5851. line += 1;
  5852. }
  5853. switch (code) {
  5854. case t.space:
  5855. case t.tab:
  5856. case t.newline:
  5857. case t.cr:
  5858. case t.feed:
  5859. next = start;
  5860. do {
  5861. next += 1;
  5862. code = css.charCodeAt(next);
  5863. if (code === t.newline) {
  5864. offset = next;
  5865. line += 1;
  5866. }
  5867. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  5868. tokenType = t.space;
  5869. endLine = line;
  5870. endColumn = next - offset - 1;
  5871. end = next;
  5872. break;
  5873. case t.plus:
  5874. case t.greaterThan:
  5875. case t.tilde:
  5876. case t.pipe:
  5877. next = start;
  5878. do {
  5879. next += 1;
  5880. code = css.charCodeAt(next);
  5881. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  5882. tokenType = t.combinator;
  5883. endLine = line;
  5884. endColumn = start - offset;
  5885. end = next;
  5886. break;
  5887. // Consume these characters as single tokens.
  5888. case t.asterisk:
  5889. case t.ampersand:
  5890. case t.bang:
  5891. case t.comma:
  5892. case t.equals:
  5893. case t.dollar:
  5894. case t.caret:
  5895. case t.openSquare:
  5896. case t.closeSquare:
  5897. case t.colon:
  5898. case t.semicolon:
  5899. case t.openParenthesis:
  5900. case t.closeParenthesis:
  5901. next = start;
  5902. tokenType = code;
  5903. endLine = line;
  5904. endColumn = start - offset;
  5905. end = next + 1;
  5906. break;
  5907. case t.singleQuote:
  5908. case t.doubleQuote:
  5909. quote = code === t.singleQuote ? "'" : '"';
  5910. next = start;
  5911. do {
  5912. escaped = false;
  5913. next = css.indexOf(quote, next + 1);
  5914. if (next === -1) {
  5915. unclosed('quote', quote);
  5916. }
  5917. escapePos = next;
  5918. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  5919. escapePos -= 1;
  5920. escaped = !escaped;
  5921. }
  5922. } while (escaped);
  5923. tokenType = t.str;
  5924. endLine = line;
  5925. endColumn = start - offset;
  5926. end = next + 1;
  5927. break;
  5928. default:
  5929. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  5930. next = css.indexOf('*/', start + 2) + 1;
  5931. if (next === 0) {
  5932. unclosed('comment', '*/');
  5933. }
  5934. content = css.slice(start, next + 1);
  5935. lines = content.split('\n');
  5936. last = lines.length - 1;
  5937. if (last > 0) {
  5938. nextLine = line + last;
  5939. nextOffset = next - lines[last].length;
  5940. } else {
  5941. nextLine = line;
  5942. nextOffset = offset;
  5943. }
  5944. tokenType = t.comment;
  5945. line = nextLine;
  5946. endLine = nextLine;
  5947. endColumn = next - nextOffset;
  5948. } else if (code === t.slash) {
  5949. next = start;
  5950. tokenType = code;
  5951. endLine = line;
  5952. endColumn = start - offset;
  5953. end = next + 1;
  5954. } else {
  5955. next = consumeWord(css, start);
  5956. tokenType = t.word;
  5957. endLine = line;
  5958. endColumn = next - offset;
  5959. }
  5960. end = next + 1;
  5961. break;
  5962. }
  5963. // Ensure that the token structure remains consistent
  5964. tokens.push([tokenType,
  5965. // [0] Token type
  5966. line,
  5967. // [1] Starting line
  5968. start - offset,
  5969. // [2] Starting column
  5970. endLine,
  5971. // [3] Ending line
  5972. endColumn,
  5973. // [4] Ending column
  5974. start,
  5975. // [5] Start position / Source index
  5976. end // [6] End position
  5977. ]);
  5978. // Reset offset for the next token
  5979. if (nextOffset) {
  5980. offset = nextOffset;
  5981. nextOffset = null;
  5982. }
  5983. start = end;
  5984. }
  5985. return tokens;
  5986. }
  5987. } (tokenize));
  5988. (function (module, exports) {
  5989. exports.__esModule = true;
  5990. exports["default"] = void 0;
  5991. var _root = _interopRequireDefault(rootExports);
  5992. var _selector = _interopRequireDefault(selectorExports);
  5993. var _className = _interopRequireDefault(classNameExports);
  5994. var _comment = _interopRequireDefault(commentExports);
  5995. var _id = _interopRequireDefault(idExports);
  5996. var _tag = _interopRequireDefault(tagExports);
  5997. var _string = _interopRequireDefault(stringExports);
  5998. var _pseudo = _interopRequireDefault(pseudoExports);
  5999. var _attribute = _interopRequireWildcard(attribute$1);
  6000. var _universal = _interopRequireDefault(universalExports);
  6001. var _combinator = _interopRequireDefault(combinatorExports);
  6002. var _nesting = _interopRequireDefault(nestingExports);
  6003. var _sortAscending = _interopRequireDefault(sortAscendingExports);
  6004. var _tokenize = _interopRequireWildcard(tokenize);
  6005. var tokens = _interopRequireWildcard(tokenTypes);
  6006. var types = _interopRequireWildcard(types$1);
  6007. var _util = util$6;
  6008. var _WHITESPACE_TOKENS, _Object$assign;
  6009. 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); }
  6010. 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; }
  6011. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6012. 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); } }
  6013. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6014. 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);
  6015. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6016. function tokenStart(token) {
  6017. return {
  6018. line: token[_tokenize.FIELDS.START_LINE],
  6019. column: token[_tokenize.FIELDS.START_COL]
  6020. };
  6021. }
  6022. function tokenEnd(token) {
  6023. return {
  6024. line: token[_tokenize.FIELDS.END_LINE],
  6025. column: token[_tokenize.FIELDS.END_COL]
  6026. };
  6027. }
  6028. function getSource(startLine, startColumn, endLine, endColumn) {
  6029. return {
  6030. start: {
  6031. line: startLine,
  6032. column: startColumn
  6033. },
  6034. end: {
  6035. line: endLine,
  6036. column: endColumn
  6037. }
  6038. };
  6039. }
  6040. function getTokenSource(token) {
  6041. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6042. }
  6043. function getTokenSourceSpan(startToken, endToken) {
  6044. if (!startToken) {
  6045. return undefined;
  6046. }
  6047. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6048. }
  6049. function unescapeProp(node, prop) {
  6050. var value = node[prop];
  6051. if (typeof value !== "string") {
  6052. return;
  6053. }
  6054. if (value.indexOf("\\") !== -1) {
  6055. (0, _util.ensureObject)(node, 'raws');
  6056. node[prop] = (0, _util.unesc)(value);
  6057. if (node.raws[prop] === undefined) {
  6058. node.raws[prop] = value;
  6059. }
  6060. }
  6061. return node;
  6062. }
  6063. function indexesOf(array, item) {
  6064. var i = -1;
  6065. var indexes = [];
  6066. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6067. indexes.push(i);
  6068. }
  6069. return indexes;
  6070. }
  6071. function uniqs() {
  6072. var list = Array.prototype.concat.apply([], arguments);
  6073. return list.filter(function (item, i) {
  6074. return i === list.indexOf(item);
  6075. });
  6076. }
  6077. var Parser = /*#__PURE__*/function () {
  6078. function Parser(rule, options) {
  6079. if (options === void 0) {
  6080. options = {};
  6081. }
  6082. this.rule = rule;
  6083. this.options = Object.assign({
  6084. lossy: false,
  6085. safe: false
  6086. }, options);
  6087. this.position = 0;
  6088. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6089. this.tokens = (0, _tokenize["default"])({
  6090. css: this.css,
  6091. error: this._errorGenerator(),
  6092. safe: this.options.safe
  6093. });
  6094. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6095. this.root = new _root["default"]({
  6096. source: rootSource
  6097. });
  6098. this.root.errorGenerator = this._errorGenerator();
  6099. var selector = new _selector["default"]({
  6100. source: {
  6101. start: {
  6102. line: 1,
  6103. column: 1
  6104. }
  6105. },
  6106. sourceIndex: 0
  6107. });
  6108. this.root.append(selector);
  6109. this.current = selector;
  6110. this.loop();
  6111. }
  6112. var _proto = Parser.prototype;
  6113. _proto._errorGenerator = function _errorGenerator() {
  6114. var _this = this;
  6115. return function (message, errorOptions) {
  6116. if (typeof _this.rule === 'string') {
  6117. return new Error(message);
  6118. }
  6119. return _this.rule.error(message, errorOptions);
  6120. };
  6121. };
  6122. _proto.attribute = function attribute() {
  6123. var attr = [];
  6124. var startingToken = this.currToken;
  6125. this.position++;
  6126. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6127. attr.push(this.currToken);
  6128. this.position++;
  6129. }
  6130. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6131. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6132. }
  6133. var len = attr.length;
  6134. var node = {
  6135. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6136. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6137. };
  6138. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6139. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6140. }
  6141. var pos = 0;
  6142. var spaceBefore = '';
  6143. var commentBefore = '';
  6144. var lastAdded = null;
  6145. var spaceAfterMeaningfulToken = false;
  6146. while (pos < len) {
  6147. var token = attr[pos];
  6148. var content = this.content(token);
  6149. var next = attr[pos + 1];
  6150. switch (token[_tokenize.FIELDS.TYPE]) {
  6151. case tokens.space:
  6152. // if (
  6153. // len === 1 ||
  6154. // pos === 0 && this.content(next) === '|'
  6155. // ) {
  6156. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6157. // }
  6158. spaceAfterMeaningfulToken = true;
  6159. if (this.options.lossy) {
  6160. break;
  6161. }
  6162. if (lastAdded) {
  6163. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6164. var prevContent = node.spaces[lastAdded].after || '';
  6165. node.spaces[lastAdded].after = prevContent + content;
  6166. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6167. if (existingComment) {
  6168. node.raws.spaces[lastAdded].after = existingComment + content;
  6169. }
  6170. } else {
  6171. spaceBefore = spaceBefore + content;
  6172. commentBefore = commentBefore + content;
  6173. }
  6174. break;
  6175. case tokens.asterisk:
  6176. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6177. node.operator = content;
  6178. lastAdded = 'operator';
  6179. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6180. if (spaceBefore) {
  6181. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6182. node.spaces.attribute.before = spaceBefore;
  6183. spaceBefore = '';
  6184. }
  6185. if (commentBefore) {
  6186. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6187. node.raws.spaces.attribute.before = spaceBefore;
  6188. commentBefore = '';
  6189. }
  6190. node.namespace = (node.namespace || "") + content;
  6191. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6192. if (rawValue) {
  6193. node.raws.namespace += content;
  6194. }
  6195. lastAdded = 'namespace';
  6196. }
  6197. spaceAfterMeaningfulToken = false;
  6198. break;
  6199. case tokens.dollar:
  6200. if (lastAdded === "value") {
  6201. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6202. node.value += "$";
  6203. if (oldRawValue) {
  6204. node.raws.value = oldRawValue + "$";
  6205. }
  6206. break;
  6207. }
  6208. // Falls through
  6209. case tokens.caret:
  6210. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6211. node.operator = content;
  6212. lastAdded = 'operator';
  6213. }
  6214. spaceAfterMeaningfulToken = false;
  6215. break;
  6216. case tokens.combinator:
  6217. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6218. node.operator = content;
  6219. lastAdded = 'operator';
  6220. }
  6221. if (content !== '|') {
  6222. spaceAfterMeaningfulToken = false;
  6223. break;
  6224. }
  6225. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6226. node.operator = content;
  6227. lastAdded = 'operator';
  6228. } else if (!node.namespace && !node.attribute) {
  6229. node.namespace = true;
  6230. }
  6231. spaceAfterMeaningfulToken = false;
  6232. break;
  6233. case tokens.word:
  6234. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6235. // this look-ahead probably fails with comment nodes involved.
  6236. !node.operator && !node.namespace) {
  6237. node.namespace = content;
  6238. lastAdded = 'namespace';
  6239. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6240. if (spaceBefore) {
  6241. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6242. node.spaces.attribute.before = spaceBefore;
  6243. spaceBefore = '';
  6244. }
  6245. if (commentBefore) {
  6246. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6247. node.raws.spaces.attribute.before = commentBefore;
  6248. commentBefore = '';
  6249. }
  6250. node.attribute = (node.attribute || "") + content;
  6251. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6252. if (_rawValue) {
  6253. node.raws.attribute += content;
  6254. }
  6255. lastAdded = 'attribute';
  6256. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6257. var _unescaped = (0, _util.unesc)(content);
  6258. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6259. var oldValue = node.value || '';
  6260. node.value = oldValue + _unescaped;
  6261. node.quoteMark = null;
  6262. if (_unescaped !== content || _oldRawValue) {
  6263. (0, _util.ensureObject)(node, 'raws');
  6264. node.raws.value = (_oldRawValue || oldValue) + content;
  6265. }
  6266. lastAdded = 'value';
  6267. } else {
  6268. var insensitive = content === 'i' || content === "I";
  6269. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6270. node.insensitive = insensitive;
  6271. if (!insensitive || content === "I") {
  6272. (0, _util.ensureObject)(node, 'raws');
  6273. node.raws.insensitiveFlag = content;
  6274. }
  6275. lastAdded = 'insensitive';
  6276. if (spaceBefore) {
  6277. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6278. node.spaces.insensitive.before = spaceBefore;
  6279. spaceBefore = '';
  6280. }
  6281. if (commentBefore) {
  6282. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6283. node.raws.spaces.insensitive.before = commentBefore;
  6284. commentBefore = '';
  6285. }
  6286. } else if (node.value || node.value === '') {
  6287. lastAdded = 'value';
  6288. node.value += content;
  6289. if (node.raws.value) {
  6290. node.raws.value += content;
  6291. }
  6292. }
  6293. }
  6294. spaceAfterMeaningfulToken = false;
  6295. break;
  6296. case tokens.str:
  6297. if (!node.attribute || !node.operator) {
  6298. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6299. index: token[_tokenize.FIELDS.START_POS]
  6300. });
  6301. }
  6302. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6303. unescaped = _unescapeValue.unescaped,
  6304. quoteMark = _unescapeValue.quoteMark;
  6305. node.value = unescaped;
  6306. node.quoteMark = quoteMark;
  6307. lastAdded = 'value';
  6308. (0, _util.ensureObject)(node, 'raws');
  6309. node.raws.value = content;
  6310. spaceAfterMeaningfulToken = false;
  6311. break;
  6312. case tokens.equals:
  6313. if (!node.attribute) {
  6314. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6315. }
  6316. if (node.value) {
  6317. return this.error('Unexpected "=" found; an operator was already defined.', {
  6318. index: token[_tokenize.FIELDS.START_POS]
  6319. });
  6320. }
  6321. node.operator = node.operator ? node.operator + content : content;
  6322. lastAdded = 'operator';
  6323. spaceAfterMeaningfulToken = false;
  6324. break;
  6325. case tokens.comment:
  6326. if (lastAdded) {
  6327. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6328. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6329. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6330. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6331. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6332. } else {
  6333. var lastValue = node[lastAdded] || '';
  6334. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6335. (0, _util.ensureObject)(node, 'raws');
  6336. node.raws[lastAdded] = rawLastValue + content;
  6337. }
  6338. } else {
  6339. commentBefore = commentBefore + content;
  6340. }
  6341. break;
  6342. default:
  6343. return this.error("Unexpected \"" + content + "\" found.", {
  6344. index: token[_tokenize.FIELDS.START_POS]
  6345. });
  6346. }
  6347. pos++;
  6348. }
  6349. unescapeProp(node, "attribute");
  6350. unescapeProp(node, "namespace");
  6351. this.newNode(new _attribute["default"](node));
  6352. this.position++;
  6353. }
  6354. /**
  6355. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6356. * if the token position is negative, all remaining tokens are consumed.
  6357. *
  6358. * This returns an array containing a single string node if all whitespace,
  6359. * otherwise an array of comment nodes with space before and after.
  6360. *
  6361. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6362. * a previous node's space metadata.
  6363. *
  6364. * In lossy mode, this returns only comments.
  6365. */;
  6366. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6367. if (stopPosition < 0) {
  6368. stopPosition = this.tokens.length;
  6369. }
  6370. var startPosition = this.position;
  6371. var nodes = [];
  6372. var space = "";
  6373. var lastComment = undefined;
  6374. do {
  6375. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6376. if (!this.options.lossy) {
  6377. space += this.content();
  6378. }
  6379. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6380. var spaces = {};
  6381. if (space) {
  6382. spaces.before = space;
  6383. space = "";
  6384. }
  6385. lastComment = new _comment["default"]({
  6386. value: this.content(),
  6387. source: getTokenSource(this.currToken),
  6388. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6389. spaces: spaces
  6390. });
  6391. nodes.push(lastComment);
  6392. }
  6393. } while (++this.position < stopPosition);
  6394. if (space) {
  6395. if (lastComment) {
  6396. lastComment.spaces.after = space;
  6397. } else if (!this.options.lossy) {
  6398. var firstToken = this.tokens[startPosition];
  6399. var lastToken = this.tokens[this.position - 1];
  6400. nodes.push(new _string["default"]({
  6401. value: '',
  6402. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6403. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6404. spaces: {
  6405. before: space,
  6406. after: ''
  6407. }
  6408. }));
  6409. }
  6410. }
  6411. return nodes;
  6412. }
  6413. /**
  6414. *
  6415. * @param {*} nodes
  6416. */;
  6417. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6418. var _this2 = this;
  6419. if (requiredSpace === void 0) {
  6420. requiredSpace = false;
  6421. }
  6422. var space = "";
  6423. var rawSpace = "";
  6424. nodes.forEach(function (n) {
  6425. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6426. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6427. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6428. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6429. });
  6430. if (rawSpace === space) {
  6431. rawSpace = undefined;
  6432. }
  6433. var result = {
  6434. space: space,
  6435. rawSpace: rawSpace
  6436. };
  6437. return result;
  6438. };
  6439. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6440. if (position === void 0) {
  6441. position = this.position;
  6442. }
  6443. 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;
  6444. };
  6445. _proto.namedCombinator = function namedCombinator() {
  6446. if (this.isNamedCombinator()) {
  6447. var nameRaw = this.content(this.tokens[this.position + 1]);
  6448. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6449. var raws = {};
  6450. if (name !== nameRaw) {
  6451. raws.value = "/" + nameRaw + "/";
  6452. }
  6453. var node = new _combinator["default"]({
  6454. value: "/" + name + "/",
  6455. 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]),
  6456. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6457. raws: raws
  6458. });
  6459. this.position = this.position + 3;
  6460. return node;
  6461. } else {
  6462. this.unexpected();
  6463. }
  6464. };
  6465. _proto.combinator = function combinator() {
  6466. var _this3 = this;
  6467. if (this.content() === '|') {
  6468. return this.namespace();
  6469. }
  6470. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6471. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6472. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  6473. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6474. if (nodes.length > 0) {
  6475. var last = this.current.last;
  6476. if (last) {
  6477. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6478. space = _this$convertWhitespa.space,
  6479. rawSpace = _this$convertWhitespa.rawSpace;
  6480. if (rawSpace !== undefined) {
  6481. last.rawSpaceAfter += rawSpace;
  6482. }
  6483. last.spaces.after += space;
  6484. } else {
  6485. nodes.forEach(function (n) {
  6486. return _this3.newNode(n);
  6487. });
  6488. }
  6489. }
  6490. return;
  6491. }
  6492. var firstToken = this.currToken;
  6493. var spaceOrDescendantSelectorNodes = undefined;
  6494. if (nextSigTokenPos > this.position) {
  6495. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6496. }
  6497. var node;
  6498. if (this.isNamedCombinator()) {
  6499. node = this.namedCombinator();
  6500. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6501. node = new _combinator["default"]({
  6502. value: this.content(),
  6503. source: getTokenSource(this.currToken),
  6504. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6505. });
  6506. this.position++;
  6507. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6508. this.unexpected();
  6509. }
  6510. if (node) {
  6511. if (spaceOrDescendantSelectorNodes) {
  6512. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6513. _space = _this$convertWhitespa2.space,
  6514. _rawSpace = _this$convertWhitespa2.rawSpace;
  6515. node.spaces.before = _space;
  6516. node.rawSpaceBefore = _rawSpace;
  6517. }
  6518. } else {
  6519. // descendant combinator
  6520. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6521. _space2 = _this$convertWhitespa3.space,
  6522. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6523. if (!_rawSpace2) {
  6524. _rawSpace2 = _space2;
  6525. }
  6526. var spaces = {};
  6527. var raws = {
  6528. spaces: {}
  6529. };
  6530. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6531. spaces.before = _space2.slice(0, _space2.length - 1);
  6532. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6533. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  6534. spaces.after = _space2.slice(1);
  6535. raws.spaces.after = _rawSpace2.slice(1);
  6536. } else {
  6537. raws.value = _rawSpace2;
  6538. }
  6539. node = new _combinator["default"]({
  6540. value: ' ',
  6541. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6542. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6543. spaces: spaces,
  6544. raws: raws
  6545. });
  6546. }
  6547. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6548. node.spaces.after = this.optionalSpace(this.content());
  6549. this.position++;
  6550. }
  6551. return this.newNode(node);
  6552. };
  6553. _proto.comma = function comma() {
  6554. if (this.position === this.tokens.length - 1) {
  6555. this.root.trailingComma = true;
  6556. this.position++;
  6557. return;
  6558. }
  6559. this.current._inferEndPosition();
  6560. var selector = new _selector["default"]({
  6561. source: {
  6562. start: tokenStart(this.tokens[this.position + 1])
  6563. },
  6564. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  6565. });
  6566. this.current.parent.append(selector);
  6567. this.current = selector;
  6568. this.position++;
  6569. };
  6570. _proto.comment = function comment() {
  6571. var current = this.currToken;
  6572. this.newNode(new _comment["default"]({
  6573. value: this.content(),
  6574. source: getTokenSource(current),
  6575. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6576. }));
  6577. this.position++;
  6578. };
  6579. _proto.error = function error(message, opts) {
  6580. throw this.root.error(message, opts);
  6581. };
  6582. _proto.missingBackslash = function missingBackslash() {
  6583. return this.error('Expected a backslash preceding the semicolon.', {
  6584. index: this.currToken[_tokenize.FIELDS.START_POS]
  6585. });
  6586. };
  6587. _proto.missingParenthesis = function missingParenthesis() {
  6588. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6589. };
  6590. _proto.missingSquareBracket = function missingSquareBracket() {
  6591. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6592. };
  6593. _proto.unexpected = function unexpected() {
  6594. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6595. };
  6596. _proto.unexpectedPipe = function unexpectedPipe() {
  6597. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6598. };
  6599. _proto.namespace = function namespace() {
  6600. var before = this.prevToken && this.content(this.prevToken) || true;
  6601. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6602. this.position++;
  6603. return this.word(before);
  6604. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6605. this.position++;
  6606. return this.universal(before);
  6607. }
  6608. this.unexpectedPipe();
  6609. };
  6610. _proto.nesting = function nesting() {
  6611. if (this.nextToken) {
  6612. var nextContent = this.content(this.nextToken);
  6613. if (nextContent === "|") {
  6614. this.position++;
  6615. return;
  6616. }
  6617. }
  6618. var current = this.currToken;
  6619. this.newNode(new _nesting["default"]({
  6620. value: this.content(),
  6621. source: getTokenSource(current),
  6622. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6623. }));
  6624. this.position++;
  6625. };
  6626. _proto.parentheses = function parentheses() {
  6627. var last = this.current.last;
  6628. var unbalanced = 1;
  6629. this.position++;
  6630. if (last && last.type === types.PSEUDO) {
  6631. var selector = new _selector["default"]({
  6632. source: {
  6633. start: tokenStart(this.tokens[this.position])
  6634. },
  6635. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  6636. });
  6637. var cache = this.current;
  6638. last.append(selector);
  6639. this.current = selector;
  6640. while (this.position < this.tokens.length && unbalanced) {
  6641. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6642. unbalanced++;
  6643. }
  6644. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6645. unbalanced--;
  6646. }
  6647. if (unbalanced) {
  6648. this.parse();
  6649. } else {
  6650. this.current.source.end = tokenEnd(this.currToken);
  6651. this.current.parent.source.end = tokenEnd(this.currToken);
  6652. this.position++;
  6653. }
  6654. }
  6655. this.current = cache;
  6656. } else {
  6657. // I think this case should be an error. It's used to implement a basic parse of media queries
  6658. // but I don't think it's a good idea.
  6659. var parenStart = this.currToken;
  6660. var parenValue = "(";
  6661. var parenEnd;
  6662. while (this.position < this.tokens.length && unbalanced) {
  6663. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6664. unbalanced++;
  6665. }
  6666. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6667. unbalanced--;
  6668. }
  6669. parenEnd = this.currToken;
  6670. parenValue += this.parseParenthesisToken(this.currToken);
  6671. this.position++;
  6672. }
  6673. if (last) {
  6674. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6675. } else {
  6676. this.newNode(new _string["default"]({
  6677. value: parenValue,
  6678. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6679. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6680. }));
  6681. }
  6682. }
  6683. if (unbalanced) {
  6684. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6685. }
  6686. };
  6687. _proto.pseudo = function pseudo() {
  6688. var _this4 = this;
  6689. var pseudoStr = '';
  6690. var startingToken = this.currToken;
  6691. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6692. pseudoStr += this.content();
  6693. this.position++;
  6694. }
  6695. if (!this.currToken) {
  6696. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6697. }
  6698. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6699. this.splitWord(false, function (first, length) {
  6700. pseudoStr += first;
  6701. _this4.newNode(new _pseudo["default"]({
  6702. value: pseudoStr,
  6703. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6704. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6705. }));
  6706. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6707. _this4.error('Misplaced parenthesis.', {
  6708. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6709. });
  6710. }
  6711. });
  6712. } else {
  6713. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6714. }
  6715. };
  6716. _proto.space = function space() {
  6717. var content = this.content();
  6718. // Handle space before and after the selector
  6719. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6720. return node.type === 'comment';
  6721. })) {
  6722. this.spaces = this.optionalSpace(content);
  6723. this.position++;
  6724. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6725. this.current.last.spaces.after = this.optionalSpace(content);
  6726. this.position++;
  6727. } else {
  6728. this.combinator();
  6729. }
  6730. };
  6731. _proto.string = function string() {
  6732. var current = this.currToken;
  6733. this.newNode(new _string["default"]({
  6734. value: this.content(),
  6735. source: getTokenSource(current),
  6736. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6737. }));
  6738. this.position++;
  6739. };
  6740. _proto.universal = function universal(namespace) {
  6741. var nextToken = this.nextToken;
  6742. if (nextToken && this.content(nextToken) === '|') {
  6743. this.position++;
  6744. return this.namespace();
  6745. }
  6746. var current = this.currToken;
  6747. this.newNode(new _universal["default"]({
  6748. value: this.content(),
  6749. source: getTokenSource(current),
  6750. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6751. }), namespace);
  6752. this.position++;
  6753. };
  6754. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6755. var _this5 = this;
  6756. var nextToken = this.nextToken;
  6757. var word = this.content();
  6758. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6759. this.position++;
  6760. var current = this.content();
  6761. word += current;
  6762. if (current.lastIndexOf('\\') === current.length - 1) {
  6763. var next = this.nextToken;
  6764. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6765. word += this.requiredSpace(this.content(next));
  6766. this.position++;
  6767. }
  6768. }
  6769. nextToken = this.nextToken;
  6770. }
  6771. var hasClass = indexesOf(word, '.').filter(function (i) {
  6772. // Allow escaped dot within class name
  6773. var escapedDot = word[i - 1] === '\\';
  6774. // Allow decimal numbers percent in @keyframes
  6775. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6776. return !escapedDot && !isKeyframesPercent;
  6777. });
  6778. var hasId = indexesOf(word, '#').filter(function (i) {
  6779. return word[i - 1] !== '\\';
  6780. });
  6781. // Eliminate Sass interpolations from the list of id indexes
  6782. var interpolations = indexesOf(word, '#{');
  6783. if (interpolations.length) {
  6784. hasId = hasId.filter(function (hashIndex) {
  6785. return !~interpolations.indexOf(hashIndex);
  6786. });
  6787. }
  6788. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6789. indices.forEach(function (ind, i) {
  6790. var index = indices[i + 1] || word.length;
  6791. var value = word.slice(ind, index);
  6792. if (i === 0 && firstCallback) {
  6793. return firstCallback.call(_this5, value, indices.length);
  6794. }
  6795. var node;
  6796. var current = _this5.currToken;
  6797. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6798. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6799. if (~hasClass.indexOf(ind)) {
  6800. var classNameOpts = {
  6801. value: value.slice(1),
  6802. source: source,
  6803. sourceIndex: sourceIndex
  6804. };
  6805. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6806. } else if (~hasId.indexOf(ind)) {
  6807. var idOpts = {
  6808. value: value.slice(1),
  6809. source: source,
  6810. sourceIndex: sourceIndex
  6811. };
  6812. node = new _id["default"](unescapeProp(idOpts, "value"));
  6813. } else {
  6814. var tagOpts = {
  6815. value: value,
  6816. source: source,
  6817. sourceIndex: sourceIndex
  6818. };
  6819. unescapeProp(tagOpts, "value");
  6820. node = new _tag["default"](tagOpts);
  6821. }
  6822. _this5.newNode(node, namespace);
  6823. // Ensure that the namespace is used only once
  6824. namespace = null;
  6825. });
  6826. this.position++;
  6827. };
  6828. _proto.word = function word(namespace) {
  6829. var nextToken = this.nextToken;
  6830. if (nextToken && this.content(nextToken) === '|') {
  6831. this.position++;
  6832. return this.namespace();
  6833. }
  6834. return this.splitWord(namespace);
  6835. };
  6836. _proto.loop = function loop() {
  6837. while (this.position < this.tokens.length) {
  6838. this.parse(true);
  6839. }
  6840. this.current._inferEndPosition();
  6841. return this.root;
  6842. };
  6843. _proto.parse = function parse(throwOnParenthesis) {
  6844. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  6845. case tokens.space:
  6846. this.space();
  6847. break;
  6848. case tokens.comment:
  6849. this.comment();
  6850. break;
  6851. case tokens.openParenthesis:
  6852. this.parentheses();
  6853. break;
  6854. case tokens.closeParenthesis:
  6855. if (throwOnParenthesis) {
  6856. this.missingParenthesis();
  6857. }
  6858. break;
  6859. case tokens.openSquare:
  6860. this.attribute();
  6861. break;
  6862. case tokens.dollar:
  6863. case tokens.caret:
  6864. case tokens.equals:
  6865. case tokens.word:
  6866. this.word();
  6867. break;
  6868. case tokens.colon:
  6869. this.pseudo();
  6870. break;
  6871. case tokens.comma:
  6872. this.comma();
  6873. break;
  6874. case tokens.asterisk:
  6875. this.universal();
  6876. break;
  6877. case tokens.ampersand:
  6878. this.nesting();
  6879. break;
  6880. case tokens.slash:
  6881. case tokens.combinator:
  6882. this.combinator();
  6883. break;
  6884. case tokens.str:
  6885. this.string();
  6886. break;
  6887. // These cases throw; no break needed.
  6888. case tokens.closeSquare:
  6889. this.missingSquareBracket();
  6890. case tokens.semicolon:
  6891. this.missingBackslash();
  6892. default:
  6893. this.unexpected();
  6894. }
  6895. }
  6896. /**
  6897. * Helpers
  6898. */;
  6899. _proto.expected = function expected(description, index, found) {
  6900. if (Array.isArray(description)) {
  6901. var last = description.pop();
  6902. description = description.join(', ') + " or " + last;
  6903. }
  6904. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  6905. if (!found) {
  6906. return this.error("Expected " + an + " " + description + ".", {
  6907. index: index
  6908. });
  6909. }
  6910. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  6911. index: index
  6912. });
  6913. };
  6914. _proto.requiredSpace = function requiredSpace(space) {
  6915. return this.options.lossy ? ' ' : space;
  6916. };
  6917. _proto.optionalSpace = function optionalSpace(space) {
  6918. return this.options.lossy ? '' : space;
  6919. };
  6920. _proto.lossySpace = function lossySpace(space, required) {
  6921. if (this.options.lossy) {
  6922. return required ? ' ' : '';
  6923. } else {
  6924. return space;
  6925. }
  6926. };
  6927. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  6928. var content = this.content(token);
  6929. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  6930. return this.requiredSpace(content);
  6931. } else {
  6932. return content;
  6933. }
  6934. };
  6935. _proto.newNode = function newNode(node, namespace) {
  6936. if (namespace) {
  6937. if (/^ +$/.test(namespace)) {
  6938. if (!this.options.lossy) {
  6939. this.spaces = (this.spaces || '') + namespace;
  6940. }
  6941. namespace = true;
  6942. }
  6943. node.namespace = namespace;
  6944. unescapeProp(node, "namespace");
  6945. }
  6946. if (this.spaces) {
  6947. node.spaces.before = this.spaces;
  6948. this.spaces = '';
  6949. }
  6950. return this.current.append(node);
  6951. };
  6952. _proto.content = function content(token) {
  6953. if (token === void 0) {
  6954. token = this.currToken;
  6955. }
  6956. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  6957. };
  6958. /**
  6959. * returns the index of the next non-whitespace, non-comment token.
  6960. * returns -1 if no meaningful token is found.
  6961. */
  6962. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  6963. if (startPosition === void 0) {
  6964. startPosition = this.position + 1;
  6965. }
  6966. var searchPosition = startPosition;
  6967. while (searchPosition < this.tokens.length) {
  6968. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  6969. searchPosition++;
  6970. continue;
  6971. } else {
  6972. return searchPosition;
  6973. }
  6974. }
  6975. return -1;
  6976. };
  6977. _createClass(Parser, [{
  6978. key: "currToken",
  6979. get: function get() {
  6980. return this.tokens[this.position];
  6981. }
  6982. }, {
  6983. key: "nextToken",
  6984. get: function get() {
  6985. return this.tokens[this.position + 1];
  6986. }
  6987. }, {
  6988. key: "prevToken",
  6989. get: function get() {
  6990. return this.tokens[this.position - 1];
  6991. }
  6992. }]);
  6993. return Parser;
  6994. }();
  6995. exports["default"] = Parser;
  6996. module.exports = exports.default;
  6997. } (parser, parser.exports));
  6998. var parserExports = parser.exports;
  6999. (function (module, exports) {
  7000. exports.__esModule = true;
  7001. exports["default"] = void 0;
  7002. var _parser = _interopRequireDefault(parserExports);
  7003. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7004. var Processor = /*#__PURE__*/function () {
  7005. function Processor(func, options) {
  7006. this.func = func || function noop() {};
  7007. this.funcRes = null;
  7008. this.options = options;
  7009. }
  7010. var _proto = Processor.prototype;
  7011. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7012. if (options === void 0) {
  7013. options = {};
  7014. }
  7015. var merged = Object.assign({}, this.options, options);
  7016. if (merged.updateSelector === false) {
  7017. return false;
  7018. } else {
  7019. return typeof rule !== "string";
  7020. }
  7021. };
  7022. _proto._isLossy = function _isLossy(options) {
  7023. if (options === void 0) {
  7024. options = {};
  7025. }
  7026. var merged = Object.assign({}, this.options, options);
  7027. if (merged.lossless === false) {
  7028. return true;
  7029. } else {
  7030. return false;
  7031. }
  7032. };
  7033. _proto._root = function _root(rule, options) {
  7034. if (options === void 0) {
  7035. options = {};
  7036. }
  7037. var parser = new _parser["default"](rule, this._parseOptions(options));
  7038. return parser.root;
  7039. };
  7040. _proto._parseOptions = function _parseOptions(options) {
  7041. return {
  7042. lossy: this._isLossy(options)
  7043. };
  7044. };
  7045. _proto._run = function _run(rule, options) {
  7046. var _this = this;
  7047. if (options === void 0) {
  7048. options = {};
  7049. }
  7050. return new Promise(function (resolve, reject) {
  7051. try {
  7052. var root = _this._root(rule, options);
  7053. Promise.resolve(_this.func(root)).then(function (transform) {
  7054. var string = undefined;
  7055. if (_this._shouldUpdateSelector(rule, options)) {
  7056. string = root.toString();
  7057. rule.selector = string;
  7058. }
  7059. return {
  7060. transform: transform,
  7061. root: root,
  7062. string: string
  7063. };
  7064. }).then(resolve, reject);
  7065. } catch (e) {
  7066. reject(e);
  7067. return;
  7068. }
  7069. });
  7070. };
  7071. _proto._runSync = function _runSync(rule, options) {
  7072. if (options === void 0) {
  7073. options = {};
  7074. }
  7075. var root = this._root(rule, options);
  7076. var transform = this.func(root);
  7077. if (transform && typeof transform.then === "function") {
  7078. throw new Error("Selector processor returned a promise to a synchronous call.");
  7079. }
  7080. var string = undefined;
  7081. if (options.updateSelector && typeof rule !== "string") {
  7082. string = root.toString();
  7083. rule.selector = string;
  7084. }
  7085. return {
  7086. transform: transform,
  7087. root: root,
  7088. string: string
  7089. };
  7090. }
  7091. /**
  7092. * Process rule into a selector AST.
  7093. *
  7094. * @param rule {postcss.Rule | string} The css selector to be processed
  7095. * @param options The options for processing
  7096. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7097. */;
  7098. _proto.ast = function ast(rule, options) {
  7099. return this._run(rule, options).then(function (result) {
  7100. return result.root;
  7101. });
  7102. }
  7103. /**
  7104. * Process rule into a selector AST synchronously.
  7105. *
  7106. * @param rule {postcss.Rule | string} The css selector to be processed
  7107. * @param options The options for processing
  7108. * @returns {parser.Root} The AST of the selector after processing it.
  7109. */;
  7110. _proto.astSync = function astSync(rule, options) {
  7111. return this._runSync(rule, options).root;
  7112. }
  7113. /**
  7114. * Process a selector into a transformed value asynchronously
  7115. *
  7116. * @param rule {postcss.Rule | string} The css selector to be processed
  7117. * @param options The options for processing
  7118. * @returns {Promise<any>} The value returned by the processor.
  7119. */;
  7120. _proto.transform = function transform(rule, options) {
  7121. return this._run(rule, options).then(function (result) {
  7122. return result.transform;
  7123. });
  7124. }
  7125. /**
  7126. * Process a selector into a transformed value synchronously.
  7127. *
  7128. * @param rule {postcss.Rule | string} The css selector to be processed
  7129. * @param options The options for processing
  7130. * @returns {any} The value returned by the processor.
  7131. */;
  7132. _proto.transformSync = function transformSync(rule, options) {
  7133. return this._runSync(rule, options).transform;
  7134. }
  7135. /**
  7136. * Process a selector into a new selector string asynchronously.
  7137. *
  7138. * @param rule {postcss.Rule | string} The css selector to be processed
  7139. * @param options The options for processing
  7140. * @returns {string} the selector after processing.
  7141. */;
  7142. _proto.process = function process(rule, options) {
  7143. return this._run(rule, options).then(function (result) {
  7144. return result.string || result.root.toString();
  7145. });
  7146. }
  7147. /**
  7148. * Process a selector into a new selector string synchronously.
  7149. *
  7150. * @param rule {postcss.Rule | string} The css selector to be processed
  7151. * @param options The options for processing
  7152. * @returns {string} the selector after processing.
  7153. */;
  7154. _proto.processSync = function processSync(rule, options) {
  7155. var result = this._runSync(rule, options);
  7156. return result.string || result.root.toString();
  7157. };
  7158. return Processor;
  7159. }();
  7160. exports["default"] = Processor;
  7161. module.exports = exports.default;
  7162. } (processor, processor.exports));
  7163. var processorExports = processor.exports;
  7164. var selectors = {};
  7165. var constructors = {};
  7166. constructors.__esModule = true;
  7167. 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;
  7168. var _attribute = _interopRequireDefault$4(attribute$1);
  7169. var _className = _interopRequireDefault$4(classNameExports);
  7170. var _combinator = _interopRequireDefault$4(combinatorExports);
  7171. var _comment = _interopRequireDefault$4(commentExports);
  7172. var _id = _interopRequireDefault$4(idExports);
  7173. var _nesting = _interopRequireDefault$4(nestingExports);
  7174. var _pseudo = _interopRequireDefault$4(pseudoExports);
  7175. var _root = _interopRequireDefault$4(rootExports);
  7176. var _selector = _interopRequireDefault$4(selectorExports);
  7177. var _string = _interopRequireDefault$4(stringExports);
  7178. var _tag = _interopRequireDefault$4(tagExports);
  7179. var _universal = _interopRequireDefault$4(universalExports);
  7180. function _interopRequireDefault$4(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7181. var attribute = function attribute(opts) {
  7182. return new _attribute["default"](opts);
  7183. };
  7184. constructors.attribute = attribute;
  7185. var className = function className(opts) {
  7186. return new _className["default"](opts);
  7187. };
  7188. constructors.className = className;
  7189. var combinator = function combinator(opts) {
  7190. return new _combinator["default"](opts);
  7191. };
  7192. constructors.combinator = combinator;
  7193. var comment = function comment(opts) {
  7194. return new _comment["default"](opts);
  7195. };
  7196. constructors.comment = comment;
  7197. var id = function id(opts) {
  7198. return new _id["default"](opts);
  7199. };
  7200. constructors.id = id;
  7201. var nesting = function nesting(opts) {
  7202. return new _nesting["default"](opts);
  7203. };
  7204. constructors.nesting = nesting;
  7205. var pseudo = function pseudo(opts) {
  7206. return new _pseudo["default"](opts);
  7207. };
  7208. constructors.pseudo = pseudo;
  7209. var root$1 = function root(opts) {
  7210. return new _root["default"](opts);
  7211. };
  7212. constructors.root = root$1;
  7213. var selector = function selector(opts) {
  7214. return new _selector["default"](opts);
  7215. };
  7216. constructors.selector = selector;
  7217. var string = function string(opts) {
  7218. return new _string["default"](opts);
  7219. };
  7220. constructors.string = string;
  7221. var tag = function tag(opts) {
  7222. return new _tag["default"](opts);
  7223. };
  7224. constructors.tag = tag;
  7225. var universal = function universal(opts) {
  7226. return new _universal["default"](opts);
  7227. };
  7228. constructors.universal = universal;
  7229. var guards = {};
  7230. guards.__esModule = true;
  7231. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  7232. guards.isContainer = isContainer;
  7233. guards.isIdentifier = void 0;
  7234. guards.isNamespace = isNamespace;
  7235. guards.isNesting = void 0;
  7236. guards.isNode = isNode;
  7237. guards.isPseudo = void 0;
  7238. guards.isPseudoClass = isPseudoClass;
  7239. guards.isPseudoElement = isPseudoElement;
  7240. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  7241. var _types = types$1;
  7242. var _IS_TYPE;
  7243. 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);
  7244. function isNode(node) {
  7245. return typeof node === "object" && IS_TYPE[node.type];
  7246. }
  7247. function isNodeType(type, node) {
  7248. return isNode(node) && node.type === type;
  7249. }
  7250. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7251. guards.isAttribute = isAttribute;
  7252. var isClassName = isNodeType.bind(null, _types.CLASS);
  7253. guards.isClassName = isClassName;
  7254. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7255. guards.isCombinator = isCombinator;
  7256. var isComment = isNodeType.bind(null, _types.COMMENT);
  7257. guards.isComment = isComment;
  7258. var isIdentifier = isNodeType.bind(null, _types.ID);
  7259. guards.isIdentifier = isIdentifier;
  7260. var isNesting = isNodeType.bind(null, _types.NESTING);
  7261. guards.isNesting = isNesting;
  7262. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7263. guards.isPseudo = isPseudo;
  7264. var isRoot = isNodeType.bind(null, _types.ROOT);
  7265. guards.isRoot = isRoot;
  7266. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7267. guards.isSelector = isSelector;
  7268. var isString = isNodeType.bind(null, _types.STRING);
  7269. guards.isString = isString;
  7270. var isTag = isNodeType.bind(null, _types.TAG);
  7271. guards.isTag = isTag;
  7272. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7273. guards.isUniversal = isUniversal;
  7274. function isPseudoElement(node) {
  7275. 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");
  7276. }
  7277. function isPseudoClass(node) {
  7278. return isPseudo(node) && !isPseudoElement(node);
  7279. }
  7280. function isContainer(node) {
  7281. return !!(isNode(node) && node.walk);
  7282. }
  7283. function isNamespace(node) {
  7284. return isAttribute(node) || isTag(node);
  7285. }
  7286. (function (exports) {
  7287. exports.__esModule = true;
  7288. var _types = types$1;
  7289. Object.keys(_types).forEach(function (key) {
  7290. if (key === "default" || key === "__esModule") return;
  7291. if (key in exports && exports[key] === _types[key]) return;
  7292. exports[key] = _types[key];
  7293. });
  7294. var _constructors = constructors;
  7295. Object.keys(_constructors).forEach(function (key) {
  7296. if (key === "default" || key === "__esModule") return;
  7297. if (key in exports && exports[key] === _constructors[key]) return;
  7298. exports[key] = _constructors[key];
  7299. });
  7300. var _guards = guards;
  7301. Object.keys(_guards).forEach(function (key) {
  7302. if (key === "default" || key === "__esModule") return;
  7303. if (key in exports && exports[key] === _guards[key]) return;
  7304. exports[key] = _guards[key];
  7305. });
  7306. } (selectors));
  7307. (function (module, exports) {
  7308. exports.__esModule = true;
  7309. exports["default"] = void 0;
  7310. var _processor = _interopRequireDefault(processorExports);
  7311. var selectors$1 = _interopRequireWildcard(selectors);
  7312. 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); }
  7313. 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; }
  7314. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7315. var parser = function parser(processor) {
  7316. return new _processor["default"](processor);
  7317. };
  7318. Object.assign(parser, selectors$1);
  7319. delete parser.__esModule;
  7320. var _default = parser;
  7321. exports["default"] = _default;
  7322. module.exports = exports.default;
  7323. } (dist, dist.exports));
  7324. var distExports = dist.exports;
  7325. var selectorParser$2 = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7326. const animationNameRE = /^(-\w+-)?animation-name$/;
  7327. const animationRE = /^(-\w+-)?animation$/;
  7328. const scopedPlugin = (id = "") => {
  7329. const keyframes = /* @__PURE__ */ Object.create(null);
  7330. const shortId = id.replace(/^data-v-/, "");
  7331. return {
  7332. postcssPlugin: "vue-sfc-scoped",
  7333. Rule(rule) {
  7334. processRule(id, rule);
  7335. },
  7336. AtRule(node) {
  7337. if (/-?keyframes$/.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7338. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7339. }
  7340. },
  7341. OnceExit(root) {
  7342. if (Object.keys(keyframes).length) {
  7343. root.walkDecls((decl) => {
  7344. if (animationNameRE.test(decl.prop)) {
  7345. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7346. }
  7347. if (animationRE.test(decl.prop)) {
  7348. decl.value = decl.value.split(",").map((v) => {
  7349. const vals = v.trim().split(/\s+/);
  7350. const i = vals.findIndex((val) => keyframes[val]);
  7351. if (i !== -1) {
  7352. vals.splice(i, 1, keyframes[vals[i]]);
  7353. return vals.join(" ");
  7354. } else {
  7355. return v;
  7356. }
  7357. }).join(",");
  7358. }
  7359. });
  7360. }
  7361. }
  7362. };
  7363. };
  7364. const processedRules = /* @__PURE__ */ new WeakSet();
  7365. function processRule(id, rule) {
  7366. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && /-?keyframes$/.test(rule.parent.name)) {
  7367. return;
  7368. }
  7369. processedRules.add(rule);
  7370. rule.selector = selectorParser$2((selectorRoot) => {
  7371. selectorRoot.each((selector) => {
  7372. rewriteSelector(id, selector, selectorRoot);
  7373. });
  7374. }).processSync(rule.selector);
  7375. }
  7376. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  7377. let node = null;
  7378. let shouldInject = true;
  7379. selector.each((n) => {
  7380. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7381. n.value = " ";
  7382. n.spaces.before = n.spaces.after = "";
  7383. warn(
  7384. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7385. );
  7386. return false;
  7387. }
  7388. if (n.type === "pseudo") {
  7389. const { value } = n;
  7390. if (value === ":deep" || value === "::v-deep") {
  7391. if (n.nodes.length) {
  7392. let last = n;
  7393. n.nodes[0].each((ss) => {
  7394. selector.insertAfter(last, ss);
  7395. last = ss;
  7396. });
  7397. const prev = selector.at(selector.index(n) - 1);
  7398. if (!prev || !isSpaceCombinator(prev)) {
  7399. selector.insertAfter(
  7400. n,
  7401. selectorParser$2.combinator({
  7402. value: " "
  7403. })
  7404. );
  7405. }
  7406. selector.removeChild(n);
  7407. } else {
  7408. warn(
  7409. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7410. );
  7411. const prev = selector.at(selector.index(n) - 1);
  7412. if (prev && isSpaceCombinator(prev)) {
  7413. selector.removeChild(prev);
  7414. }
  7415. selector.removeChild(n);
  7416. }
  7417. return false;
  7418. }
  7419. if (value === ":slotted" || value === "::v-slotted") {
  7420. rewriteSelector(
  7421. id,
  7422. n.nodes[0],
  7423. selectorRoot,
  7424. true
  7425. /* slotted */
  7426. );
  7427. let last = n;
  7428. n.nodes[0].each((ss) => {
  7429. selector.insertAfter(last, ss);
  7430. last = ss;
  7431. });
  7432. selector.removeChild(n);
  7433. shouldInject = false;
  7434. return false;
  7435. }
  7436. if (value === ":global" || value === "::v-global") {
  7437. selectorRoot.insertAfter(selector, n.nodes[0]);
  7438. selectorRoot.removeChild(selector);
  7439. return false;
  7440. }
  7441. }
  7442. if (n.type === "universal") {
  7443. const prev = selector.at(selector.index(n) - 1);
  7444. const next = selector.at(selector.index(n) + 1);
  7445. if (!prev) {
  7446. if (next) {
  7447. if (next.type === "combinator" && next.value === " ") {
  7448. selector.removeChild(next);
  7449. }
  7450. selector.removeChild(n);
  7451. return;
  7452. } else {
  7453. node = selectorParser$2.combinator({
  7454. value: ""
  7455. });
  7456. selector.insertBefore(n, node);
  7457. selector.removeChild(n);
  7458. return false;
  7459. }
  7460. }
  7461. if (node) return;
  7462. }
  7463. if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node) {
  7464. node = n;
  7465. }
  7466. });
  7467. if (node) {
  7468. const { type, value } = node;
  7469. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7470. node.nodes.forEach(
  7471. (value2) => rewriteSelector(id, value2, selectorRoot, slotted)
  7472. );
  7473. shouldInject = false;
  7474. }
  7475. }
  7476. if (node) {
  7477. node.spaces.after = "";
  7478. } else {
  7479. selector.first.spaces.before = "";
  7480. }
  7481. if (shouldInject) {
  7482. const idToAdd = slotted ? id + "-s" : id;
  7483. selector.insertAfter(
  7484. // If node is null it means we need to inject [id] at the start
  7485. // insertAfter can handle `null` here
  7486. node,
  7487. selectorParser$2.attribute({
  7488. attribute: idToAdd,
  7489. value: idToAdd,
  7490. raws: {},
  7491. quoteMark: `"`
  7492. })
  7493. );
  7494. }
  7495. }
  7496. function isSpaceCombinator(node) {
  7497. return node.type === "combinator" && /^\s+$/.test(node.value);
  7498. }
  7499. scopedPlugin.postcss = true;
  7500. var sourceMap$1 = {};
  7501. var sourceMapGenerator = {};
  7502. var base64Vlq = {};
  7503. var base64$1 = {};
  7504. /* -*- Mode: js; js-indent-level: 2; -*- */
  7505. /*
  7506. * Copyright 2011 Mozilla Foundation and contributors
  7507. * Licensed under the New BSD license. See LICENSE or:
  7508. * http://opensource.org/licenses/BSD-3-Clause
  7509. */
  7510. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7511. /**
  7512. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7513. */
  7514. base64$1.encode = function (number) {
  7515. if (0 <= number && number < intToCharMap.length) {
  7516. return intToCharMap[number];
  7517. }
  7518. throw new TypeError("Must be between 0 and 63: " + number);
  7519. };
  7520. /**
  7521. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7522. * failure.
  7523. */
  7524. base64$1.decode = function (charCode) {
  7525. var bigA = 65; // 'A'
  7526. var bigZ = 90; // 'Z'
  7527. var littleA = 97; // 'a'
  7528. var littleZ = 122; // 'z'
  7529. var zero = 48; // '0'
  7530. var nine = 57; // '9'
  7531. var plus = 43; // '+'
  7532. var slash = 47; // '/'
  7533. var littleOffset = 26;
  7534. var numberOffset = 52;
  7535. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7536. if (bigA <= charCode && charCode <= bigZ) {
  7537. return (charCode - bigA);
  7538. }
  7539. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7540. if (littleA <= charCode && charCode <= littleZ) {
  7541. return (charCode - littleA + littleOffset);
  7542. }
  7543. // 52 - 61: 0123456789
  7544. if (zero <= charCode && charCode <= nine) {
  7545. return (charCode - zero + numberOffset);
  7546. }
  7547. // 62: +
  7548. if (charCode == plus) {
  7549. return 62;
  7550. }
  7551. // 63: /
  7552. if (charCode == slash) {
  7553. return 63;
  7554. }
  7555. // Invalid base64 digit.
  7556. return -1;
  7557. };
  7558. /* -*- Mode: js; js-indent-level: 2; -*- */
  7559. /*
  7560. * Copyright 2011 Mozilla Foundation and contributors
  7561. * Licensed under the New BSD license. See LICENSE or:
  7562. * http://opensource.org/licenses/BSD-3-Clause
  7563. *
  7564. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7565. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7566. *
  7567. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7568. * Redistribution and use in source and binary forms, with or without
  7569. * modification, are permitted provided that the following conditions are
  7570. * met:
  7571. *
  7572. * * Redistributions of source code must retain the above copyright
  7573. * notice, this list of conditions and the following disclaimer.
  7574. * * Redistributions in binary form must reproduce the above
  7575. * copyright notice, this list of conditions and the following
  7576. * disclaimer in the documentation and/or other materials provided
  7577. * with the distribution.
  7578. * * Neither the name of Google Inc. nor the names of its
  7579. * contributors may be used to endorse or promote products derived
  7580. * from this software without specific prior written permission.
  7581. *
  7582. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7583. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7584. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7585. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7586. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7587. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7588. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7589. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7590. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7591. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7592. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7593. */
  7594. var base64 = base64$1;
  7595. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7596. // length quantities we use in the source map spec, the first bit is the sign,
  7597. // the next four bits are the actual value, and the 6th bit is the
  7598. // continuation bit. The continuation bit tells us whether there are more
  7599. // digits in this value following this digit.
  7600. //
  7601. // Continuation
  7602. // | Sign
  7603. // | |
  7604. // V V
  7605. // 101011
  7606. var VLQ_BASE_SHIFT = 5;
  7607. // binary: 100000
  7608. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7609. // binary: 011111
  7610. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7611. // binary: 100000
  7612. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7613. /**
  7614. * Converts from a two-complement value to a value where the sign bit is
  7615. * placed in the least significant bit. For example, as decimals:
  7616. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7617. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7618. */
  7619. function toVLQSigned(aValue) {
  7620. return aValue < 0
  7621. ? ((-aValue) << 1) + 1
  7622. : (aValue << 1) + 0;
  7623. }
  7624. /**
  7625. * Converts to a two-complement value from a value where the sign bit is
  7626. * placed in the least significant bit. For example, as decimals:
  7627. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7628. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7629. */
  7630. function fromVLQSigned(aValue) {
  7631. var isNegative = (aValue & 1) === 1;
  7632. var shifted = aValue >> 1;
  7633. return isNegative
  7634. ? -shifted
  7635. : shifted;
  7636. }
  7637. /**
  7638. * Returns the base 64 VLQ encoded value.
  7639. */
  7640. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7641. var encoded = "";
  7642. var digit;
  7643. var vlq = toVLQSigned(aValue);
  7644. do {
  7645. digit = vlq & VLQ_BASE_MASK;
  7646. vlq >>>= VLQ_BASE_SHIFT;
  7647. if (vlq > 0) {
  7648. // There are still more digits in this value, so we must make sure the
  7649. // continuation bit is marked.
  7650. digit |= VLQ_CONTINUATION_BIT;
  7651. }
  7652. encoded += base64.encode(digit);
  7653. } while (vlq > 0);
  7654. return encoded;
  7655. };
  7656. /**
  7657. * Decodes the next base 64 VLQ value from the given string and returns the
  7658. * value and the rest of the string via the out parameter.
  7659. */
  7660. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  7661. var strLen = aStr.length;
  7662. var result = 0;
  7663. var shift = 0;
  7664. var continuation, digit;
  7665. do {
  7666. if (aIndex >= strLen) {
  7667. throw new Error("Expected more digits in base 64 VLQ value.");
  7668. }
  7669. digit = base64.decode(aStr.charCodeAt(aIndex++));
  7670. if (digit === -1) {
  7671. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  7672. }
  7673. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  7674. digit &= VLQ_BASE_MASK;
  7675. result = result + (digit << shift);
  7676. shift += VLQ_BASE_SHIFT;
  7677. } while (continuation);
  7678. aOutParam.value = fromVLQSigned(result);
  7679. aOutParam.rest = aIndex;
  7680. };
  7681. var util$5 = {};
  7682. /* -*- Mode: js; js-indent-level: 2; -*- */
  7683. (function (exports) {
  7684. /*
  7685. * Copyright 2011 Mozilla Foundation and contributors
  7686. * Licensed under the New BSD license. See LICENSE or:
  7687. * http://opensource.org/licenses/BSD-3-Clause
  7688. */
  7689. /**
  7690. * This is a helper function for getting values from parameter/options
  7691. * objects.
  7692. *
  7693. * @param args The object we are extracting values from
  7694. * @param name The name of the property we are getting.
  7695. * @param defaultValue An optional value to return if the property is missing
  7696. * from the object. If this is not specified and the property is missing, an
  7697. * error will be thrown.
  7698. */
  7699. function getArg(aArgs, aName, aDefaultValue) {
  7700. if (aName in aArgs) {
  7701. return aArgs[aName];
  7702. } else if (arguments.length === 3) {
  7703. return aDefaultValue;
  7704. } else {
  7705. throw new Error('"' + aName + '" is a required argument.');
  7706. }
  7707. }
  7708. exports.getArg = getArg;
  7709. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  7710. var dataUrlRegexp = /^data:.+\,.+$/;
  7711. function urlParse(aUrl) {
  7712. var match = aUrl.match(urlRegexp);
  7713. if (!match) {
  7714. return null;
  7715. }
  7716. return {
  7717. scheme: match[1],
  7718. auth: match[2],
  7719. host: match[3],
  7720. port: match[4],
  7721. path: match[5]
  7722. };
  7723. }
  7724. exports.urlParse = urlParse;
  7725. function urlGenerate(aParsedUrl) {
  7726. var url = '';
  7727. if (aParsedUrl.scheme) {
  7728. url += aParsedUrl.scheme + ':';
  7729. }
  7730. url += '//';
  7731. if (aParsedUrl.auth) {
  7732. url += aParsedUrl.auth + '@';
  7733. }
  7734. if (aParsedUrl.host) {
  7735. url += aParsedUrl.host;
  7736. }
  7737. if (aParsedUrl.port) {
  7738. url += ":" + aParsedUrl.port;
  7739. }
  7740. if (aParsedUrl.path) {
  7741. url += aParsedUrl.path;
  7742. }
  7743. return url;
  7744. }
  7745. exports.urlGenerate = urlGenerate;
  7746. /**
  7747. * Normalizes a path, or the path portion of a URL:
  7748. *
  7749. * - Replaces consecutive slashes with one slash.
  7750. * - Removes unnecessary '.' parts.
  7751. * - Removes unnecessary '<dir>/..' parts.
  7752. *
  7753. * Based on code in the Node.js 'path' core module.
  7754. *
  7755. * @param aPath The path or url to normalize.
  7756. */
  7757. function normalize(aPath) {
  7758. var path = aPath;
  7759. var url = urlParse(aPath);
  7760. if (url) {
  7761. if (!url.path) {
  7762. return aPath;
  7763. }
  7764. path = url.path;
  7765. }
  7766. var isAbsolute = exports.isAbsolute(path);
  7767. var parts = path.split(/\/+/);
  7768. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  7769. part = parts[i];
  7770. if (part === '.') {
  7771. parts.splice(i, 1);
  7772. } else if (part === '..') {
  7773. up++;
  7774. } else if (up > 0) {
  7775. if (part === '') {
  7776. // The first part is blank if the path is absolute. Trying to go
  7777. // above the root is a no-op. Therefore we can remove all '..' parts
  7778. // directly after the root.
  7779. parts.splice(i + 1, up);
  7780. up = 0;
  7781. } else {
  7782. parts.splice(i, 2);
  7783. up--;
  7784. }
  7785. }
  7786. }
  7787. path = parts.join('/');
  7788. if (path === '') {
  7789. path = isAbsolute ? '/' : '.';
  7790. }
  7791. if (url) {
  7792. url.path = path;
  7793. return urlGenerate(url);
  7794. }
  7795. return path;
  7796. }
  7797. exports.normalize = normalize;
  7798. /**
  7799. * Joins two paths/URLs.
  7800. *
  7801. * @param aRoot The root path or URL.
  7802. * @param aPath The path or URL to be joined with the root.
  7803. *
  7804. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  7805. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  7806. * first.
  7807. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  7808. * is updated with the result and aRoot is returned. Otherwise the result
  7809. * is returned.
  7810. * - If aPath is absolute, the result is aPath.
  7811. * - Otherwise the two paths are joined with a slash.
  7812. * - Joining for example 'http://' and 'www.example.com' is also supported.
  7813. */
  7814. function join(aRoot, aPath) {
  7815. if (aRoot === "") {
  7816. aRoot = ".";
  7817. }
  7818. if (aPath === "") {
  7819. aPath = ".";
  7820. }
  7821. var aPathUrl = urlParse(aPath);
  7822. var aRootUrl = urlParse(aRoot);
  7823. if (aRootUrl) {
  7824. aRoot = aRootUrl.path || '/';
  7825. }
  7826. // `join(foo, '//www.example.org')`
  7827. if (aPathUrl && !aPathUrl.scheme) {
  7828. if (aRootUrl) {
  7829. aPathUrl.scheme = aRootUrl.scheme;
  7830. }
  7831. return urlGenerate(aPathUrl);
  7832. }
  7833. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  7834. return aPath;
  7835. }
  7836. // `join('http://', 'www.example.com')`
  7837. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  7838. aRootUrl.host = aPath;
  7839. return urlGenerate(aRootUrl);
  7840. }
  7841. var joined = aPath.charAt(0) === '/'
  7842. ? aPath
  7843. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  7844. if (aRootUrl) {
  7845. aRootUrl.path = joined;
  7846. return urlGenerate(aRootUrl);
  7847. }
  7848. return joined;
  7849. }
  7850. exports.join = join;
  7851. exports.isAbsolute = function (aPath) {
  7852. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  7853. };
  7854. /**
  7855. * Make a path relative to a URL or another path.
  7856. *
  7857. * @param aRoot The root path or URL.
  7858. * @param aPath The path or URL to be made relative to aRoot.
  7859. */
  7860. function relative(aRoot, aPath) {
  7861. if (aRoot === "") {
  7862. aRoot = ".";
  7863. }
  7864. aRoot = aRoot.replace(/\/$/, '');
  7865. // It is possible for the path to be above the root. In this case, simply
  7866. // checking whether the root is a prefix of the path won't work. Instead, we
  7867. // need to remove components from the root one by one, until either we find
  7868. // a prefix that fits, or we run out of components to remove.
  7869. var level = 0;
  7870. while (aPath.indexOf(aRoot + '/') !== 0) {
  7871. var index = aRoot.lastIndexOf("/");
  7872. if (index < 0) {
  7873. return aPath;
  7874. }
  7875. // If the only part of the root that is left is the scheme (i.e. http://,
  7876. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  7877. // have exhausted all components, so the path is not relative to the root.
  7878. aRoot = aRoot.slice(0, index);
  7879. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  7880. return aPath;
  7881. }
  7882. ++level;
  7883. }
  7884. // Make sure we add a "../" for each component we removed from the root.
  7885. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  7886. }
  7887. exports.relative = relative;
  7888. var supportsNullProto = (function () {
  7889. var obj = Object.create(null);
  7890. return !('__proto__' in obj);
  7891. }());
  7892. function identity (s) {
  7893. return s;
  7894. }
  7895. /**
  7896. * Because behavior goes wacky when you set `__proto__` on objects, we
  7897. * have to prefix all the strings in our set with an arbitrary character.
  7898. *
  7899. * See https://github.com/mozilla/source-map/pull/31 and
  7900. * https://github.com/mozilla/source-map/issues/30
  7901. *
  7902. * @param String aStr
  7903. */
  7904. function toSetString(aStr) {
  7905. if (isProtoString(aStr)) {
  7906. return '$' + aStr;
  7907. }
  7908. return aStr;
  7909. }
  7910. exports.toSetString = supportsNullProto ? identity : toSetString;
  7911. function fromSetString(aStr) {
  7912. if (isProtoString(aStr)) {
  7913. return aStr.slice(1);
  7914. }
  7915. return aStr;
  7916. }
  7917. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  7918. function isProtoString(s) {
  7919. if (!s) {
  7920. return false;
  7921. }
  7922. var length = s.length;
  7923. if (length < 9 /* "__proto__".length */) {
  7924. return false;
  7925. }
  7926. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  7927. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  7928. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  7929. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  7930. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  7931. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  7932. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  7933. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  7934. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  7935. return false;
  7936. }
  7937. for (var i = length - 10; i >= 0; i--) {
  7938. if (s.charCodeAt(i) !== 36 /* '$' */) {
  7939. return false;
  7940. }
  7941. }
  7942. return true;
  7943. }
  7944. /**
  7945. * Comparator between two mappings where the original positions are compared.
  7946. *
  7947. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  7948. * mappings with the same original source/line/column, but different generated
  7949. * line and column the same. Useful when searching for a mapping with a
  7950. * stubbed out mapping.
  7951. */
  7952. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  7953. var cmp = strcmp(mappingA.source, mappingB.source);
  7954. if (cmp !== 0) {
  7955. return cmp;
  7956. }
  7957. cmp = mappingA.originalLine - mappingB.originalLine;
  7958. if (cmp !== 0) {
  7959. return cmp;
  7960. }
  7961. cmp = mappingA.originalColumn - mappingB.originalColumn;
  7962. if (cmp !== 0 || onlyCompareOriginal) {
  7963. return cmp;
  7964. }
  7965. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  7966. if (cmp !== 0) {
  7967. return cmp;
  7968. }
  7969. cmp = mappingA.generatedLine - mappingB.generatedLine;
  7970. if (cmp !== 0) {
  7971. return cmp;
  7972. }
  7973. return strcmp(mappingA.name, mappingB.name);
  7974. }
  7975. exports.compareByOriginalPositions = compareByOriginalPositions;
  7976. /**
  7977. * Comparator between two mappings with deflated source and name indices where
  7978. * the generated positions are compared.
  7979. *
  7980. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  7981. * mappings with the same generated line and column, but different
  7982. * source/name/original line and column the same. Useful when searching for a
  7983. * mapping with a stubbed out mapping.
  7984. */
  7985. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  7986. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  7987. if (cmp !== 0) {
  7988. return cmp;
  7989. }
  7990. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  7991. if (cmp !== 0 || onlyCompareGenerated) {
  7992. return cmp;
  7993. }
  7994. cmp = strcmp(mappingA.source, mappingB.source);
  7995. if (cmp !== 0) {
  7996. return cmp;
  7997. }
  7998. cmp = mappingA.originalLine - mappingB.originalLine;
  7999. if (cmp !== 0) {
  8000. return cmp;
  8001. }
  8002. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8003. if (cmp !== 0) {
  8004. return cmp;
  8005. }
  8006. return strcmp(mappingA.name, mappingB.name);
  8007. }
  8008. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8009. function strcmp(aStr1, aStr2) {
  8010. if (aStr1 === aStr2) {
  8011. return 0;
  8012. }
  8013. if (aStr1 === null) {
  8014. return 1; // aStr2 !== null
  8015. }
  8016. if (aStr2 === null) {
  8017. return -1; // aStr1 !== null
  8018. }
  8019. if (aStr1 > aStr2) {
  8020. return 1;
  8021. }
  8022. return -1;
  8023. }
  8024. /**
  8025. * Comparator between two mappings with inflated source and name strings where
  8026. * the generated positions are compared.
  8027. */
  8028. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8029. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8030. if (cmp !== 0) {
  8031. return cmp;
  8032. }
  8033. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8034. if (cmp !== 0) {
  8035. return cmp;
  8036. }
  8037. cmp = strcmp(mappingA.source, mappingB.source);
  8038. if (cmp !== 0) {
  8039. return cmp;
  8040. }
  8041. cmp = mappingA.originalLine - mappingB.originalLine;
  8042. if (cmp !== 0) {
  8043. return cmp;
  8044. }
  8045. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8046. if (cmp !== 0) {
  8047. return cmp;
  8048. }
  8049. return strcmp(mappingA.name, mappingB.name);
  8050. }
  8051. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8052. /**
  8053. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8054. * in the source maps specification), and then parse the string as
  8055. * JSON.
  8056. */
  8057. function parseSourceMapInput(str) {
  8058. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8059. }
  8060. exports.parseSourceMapInput = parseSourceMapInput;
  8061. /**
  8062. * Compute the URL of a source given the the source root, the source's
  8063. * URL, and the source map's URL.
  8064. */
  8065. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8066. sourceURL = sourceURL || '';
  8067. if (sourceRoot) {
  8068. // This follows what Chrome does.
  8069. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8070. sourceRoot += '/';
  8071. }
  8072. // The spec says:
  8073. // Line 4: An optional source root, useful for relocating source
  8074. // files on a server or removing repeated values in the
  8075. // “sources” entry. This value is prepended to the individual
  8076. // entries in the “source” field.
  8077. sourceURL = sourceRoot + sourceURL;
  8078. }
  8079. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8080. // a parameter. This mode is still somewhat supported, which is why
  8081. // this code block is conditional. However, it's preferable to pass
  8082. // the source map URL to SourceMapConsumer, so that this function
  8083. // can implement the source URL resolution algorithm as outlined in
  8084. // the spec. This block is basically the equivalent of:
  8085. // new URL(sourceURL, sourceMapURL).toString()
  8086. // ... except it avoids using URL, which wasn't available in the
  8087. // older releases of node still supported by this library.
  8088. //
  8089. // The spec says:
  8090. // If the sources are not absolute URLs after prepending of the
  8091. // “sourceRoot”, the sources are resolved relative to the
  8092. // SourceMap (like resolving script src in a html document).
  8093. if (sourceMapURL) {
  8094. var parsed = urlParse(sourceMapURL);
  8095. if (!parsed) {
  8096. throw new Error("sourceMapURL could not be parsed");
  8097. }
  8098. if (parsed.path) {
  8099. // Strip the last path component, but keep the "/".
  8100. var index = parsed.path.lastIndexOf('/');
  8101. if (index >= 0) {
  8102. parsed.path = parsed.path.substring(0, index + 1);
  8103. }
  8104. }
  8105. sourceURL = join(urlGenerate(parsed), sourceURL);
  8106. }
  8107. return normalize(sourceURL);
  8108. }
  8109. exports.computeSourceURL = computeSourceURL;
  8110. } (util$5));
  8111. var arraySet = {};
  8112. /* -*- Mode: js; js-indent-level: 2; -*- */
  8113. /*
  8114. * Copyright 2011 Mozilla Foundation and contributors
  8115. * Licensed under the New BSD license. See LICENSE or:
  8116. * http://opensource.org/licenses/BSD-3-Clause
  8117. */
  8118. var util$4 = util$5;
  8119. var has = Object.prototype.hasOwnProperty;
  8120. var hasNativeMap = typeof Map !== "undefined";
  8121. /**
  8122. * A data structure which is a combination of an array and a set. Adding a new
  8123. * member is O(1), testing for membership is O(1), and finding the index of an
  8124. * element is O(1). Removing elements from the set is not supported. Only
  8125. * strings are supported for membership.
  8126. */
  8127. function ArraySet$2() {
  8128. this._array = [];
  8129. this._set = hasNativeMap ? new Map() : Object.create(null);
  8130. }
  8131. /**
  8132. * Static method for creating ArraySet instances from an existing array.
  8133. */
  8134. ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8135. var set = new ArraySet$2();
  8136. for (var i = 0, len = aArray.length; i < len; i++) {
  8137. set.add(aArray[i], aAllowDuplicates);
  8138. }
  8139. return set;
  8140. };
  8141. /**
  8142. * Return how many unique items are in this ArraySet. If duplicates have been
  8143. * added, than those do not count towards the size.
  8144. *
  8145. * @returns Number
  8146. */
  8147. ArraySet$2.prototype.size = function ArraySet_size() {
  8148. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8149. };
  8150. /**
  8151. * Add the given string to this set.
  8152. *
  8153. * @param String aStr
  8154. */
  8155. ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8156. var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr);
  8157. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8158. var idx = this._array.length;
  8159. if (!isDuplicate || aAllowDuplicates) {
  8160. this._array.push(aStr);
  8161. }
  8162. if (!isDuplicate) {
  8163. if (hasNativeMap) {
  8164. this._set.set(aStr, idx);
  8165. } else {
  8166. this._set[sStr] = idx;
  8167. }
  8168. }
  8169. };
  8170. /**
  8171. * Is the given string a member of this set?
  8172. *
  8173. * @param String aStr
  8174. */
  8175. ArraySet$2.prototype.has = function ArraySet_has(aStr) {
  8176. if (hasNativeMap) {
  8177. return this._set.has(aStr);
  8178. } else {
  8179. var sStr = util$4.toSetString(aStr);
  8180. return has.call(this._set, sStr);
  8181. }
  8182. };
  8183. /**
  8184. * What is the index of the given string in the array?
  8185. *
  8186. * @param String aStr
  8187. */
  8188. ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8189. if (hasNativeMap) {
  8190. var idx = this._set.get(aStr);
  8191. if (idx >= 0) {
  8192. return idx;
  8193. }
  8194. } else {
  8195. var sStr = util$4.toSetString(aStr);
  8196. if (has.call(this._set, sStr)) {
  8197. return this._set[sStr];
  8198. }
  8199. }
  8200. throw new Error('"' + aStr + '" is not in the set.');
  8201. };
  8202. /**
  8203. * What is the element at the given index?
  8204. *
  8205. * @param Number aIdx
  8206. */
  8207. ArraySet$2.prototype.at = function ArraySet_at(aIdx) {
  8208. if (aIdx >= 0 && aIdx < this._array.length) {
  8209. return this._array[aIdx];
  8210. }
  8211. throw new Error('No element indexed by ' + aIdx);
  8212. };
  8213. /**
  8214. * Returns the array representation of this set (which has the proper indices
  8215. * indicated by indexOf). Note that this is a copy of the internal array used
  8216. * for storing the members so that no one can mess with internal state.
  8217. */
  8218. ArraySet$2.prototype.toArray = function ArraySet_toArray() {
  8219. return this._array.slice();
  8220. };
  8221. arraySet.ArraySet = ArraySet$2;
  8222. var mappingList = {};
  8223. /* -*- Mode: js; js-indent-level: 2; -*- */
  8224. /*
  8225. * Copyright 2014 Mozilla Foundation and contributors
  8226. * Licensed under the New BSD license. See LICENSE or:
  8227. * http://opensource.org/licenses/BSD-3-Clause
  8228. */
  8229. var util$3 = util$5;
  8230. /**
  8231. * Determine whether mappingB is after mappingA with respect to generated
  8232. * position.
  8233. */
  8234. function generatedPositionAfter(mappingA, mappingB) {
  8235. // Optimized for most common case
  8236. var lineA = mappingA.generatedLine;
  8237. var lineB = mappingB.generatedLine;
  8238. var columnA = mappingA.generatedColumn;
  8239. var columnB = mappingB.generatedColumn;
  8240. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8241. util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8242. }
  8243. /**
  8244. * A data structure to provide a sorted view of accumulated mappings in a
  8245. * performance conscious manner. It trades a neglibable overhead in general
  8246. * case for a large speedup in case of mappings being added in order.
  8247. */
  8248. function MappingList$1() {
  8249. this._array = [];
  8250. this._sorted = true;
  8251. // Serves as infimum
  8252. this._last = {generatedLine: -1, generatedColumn: 0};
  8253. }
  8254. /**
  8255. * Iterate through internal items. This method takes the same arguments that
  8256. * `Array.prototype.forEach` takes.
  8257. *
  8258. * NOTE: The order of the mappings is NOT guaranteed.
  8259. */
  8260. MappingList$1.prototype.unsortedForEach =
  8261. function MappingList_forEach(aCallback, aThisArg) {
  8262. this._array.forEach(aCallback, aThisArg);
  8263. };
  8264. /**
  8265. * Add the given source mapping.
  8266. *
  8267. * @param Object aMapping
  8268. */
  8269. MappingList$1.prototype.add = function MappingList_add(aMapping) {
  8270. if (generatedPositionAfter(this._last, aMapping)) {
  8271. this._last = aMapping;
  8272. this._array.push(aMapping);
  8273. } else {
  8274. this._sorted = false;
  8275. this._array.push(aMapping);
  8276. }
  8277. };
  8278. /**
  8279. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8280. * generated position.
  8281. *
  8282. * WARNING: This method returns internal data without copying, for
  8283. * performance. The return value must NOT be mutated, and should be treated as
  8284. * an immutable borrow. If you want to take ownership, you must make your own
  8285. * copy.
  8286. */
  8287. MappingList$1.prototype.toArray = function MappingList_toArray() {
  8288. if (!this._sorted) {
  8289. this._array.sort(util$3.compareByGeneratedPositionsInflated);
  8290. this._sorted = true;
  8291. }
  8292. return this._array;
  8293. };
  8294. mappingList.MappingList = MappingList$1;
  8295. /* -*- Mode: js; js-indent-level: 2; -*- */
  8296. /*
  8297. * Copyright 2011 Mozilla Foundation and contributors
  8298. * Licensed under the New BSD license. See LICENSE or:
  8299. * http://opensource.org/licenses/BSD-3-Clause
  8300. */
  8301. var base64VLQ$1 = base64Vlq;
  8302. var util$2 = util$5;
  8303. var ArraySet$1 = arraySet.ArraySet;
  8304. var MappingList = mappingList.MappingList;
  8305. /**
  8306. * An instance of the SourceMapGenerator represents a source map which is
  8307. * being built incrementally. You may pass an object with the following
  8308. * properties:
  8309. *
  8310. * - file: The filename of the generated source.
  8311. * - sourceRoot: A root for all relative URLs in this source map.
  8312. */
  8313. function SourceMapGenerator$2(aArgs) {
  8314. if (!aArgs) {
  8315. aArgs = {};
  8316. }
  8317. this._file = util$2.getArg(aArgs, 'file', null);
  8318. this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null);
  8319. this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false);
  8320. this._sources = new ArraySet$1();
  8321. this._names = new ArraySet$1();
  8322. this._mappings = new MappingList();
  8323. this._sourcesContents = null;
  8324. }
  8325. SourceMapGenerator$2.prototype._version = 3;
  8326. /**
  8327. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8328. *
  8329. * @param aSourceMapConsumer The SourceMap.
  8330. */
  8331. SourceMapGenerator$2.fromSourceMap =
  8332. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8333. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8334. var generator = new SourceMapGenerator$2({
  8335. file: aSourceMapConsumer.file,
  8336. sourceRoot: sourceRoot
  8337. });
  8338. aSourceMapConsumer.eachMapping(function (mapping) {
  8339. var newMapping = {
  8340. generated: {
  8341. line: mapping.generatedLine,
  8342. column: mapping.generatedColumn
  8343. }
  8344. };
  8345. if (mapping.source != null) {
  8346. newMapping.source = mapping.source;
  8347. if (sourceRoot != null) {
  8348. newMapping.source = util$2.relative(sourceRoot, newMapping.source);
  8349. }
  8350. newMapping.original = {
  8351. line: mapping.originalLine,
  8352. column: mapping.originalColumn
  8353. };
  8354. if (mapping.name != null) {
  8355. newMapping.name = mapping.name;
  8356. }
  8357. }
  8358. generator.addMapping(newMapping);
  8359. });
  8360. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8361. var sourceRelative = sourceFile;
  8362. if (sourceRoot !== null) {
  8363. sourceRelative = util$2.relative(sourceRoot, sourceFile);
  8364. }
  8365. if (!generator._sources.has(sourceRelative)) {
  8366. generator._sources.add(sourceRelative);
  8367. }
  8368. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8369. if (content != null) {
  8370. generator.setSourceContent(sourceFile, content);
  8371. }
  8372. });
  8373. return generator;
  8374. };
  8375. /**
  8376. * Add a single mapping from original source line and column to the generated
  8377. * source's line and column for this source map being created. The mapping
  8378. * object should have the following properties:
  8379. *
  8380. * - generated: An object with the generated line and column positions.
  8381. * - original: An object with the original line and column positions.
  8382. * - source: The original source file (relative to the sourceRoot).
  8383. * - name: An optional original token name for this mapping.
  8384. */
  8385. SourceMapGenerator$2.prototype.addMapping =
  8386. function SourceMapGenerator_addMapping(aArgs) {
  8387. var generated = util$2.getArg(aArgs, 'generated');
  8388. var original = util$2.getArg(aArgs, 'original', null);
  8389. var source = util$2.getArg(aArgs, 'source', null);
  8390. var name = util$2.getArg(aArgs, 'name', null);
  8391. if (!this._skipValidation) {
  8392. this._validateMapping(generated, original, source, name);
  8393. }
  8394. if (source != null) {
  8395. source = String(source);
  8396. if (!this._sources.has(source)) {
  8397. this._sources.add(source);
  8398. }
  8399. }
  8400. if (name != null) {
  8401. name = String(name);
  8402. if (!this._names.has(name)) {
  8403. this._names.add(name);
  8404. }
  8405. }
  8406. this._mappings.add({
  8407. generatedLine: generated.line,
  8408. generatedColumn: generated.column,
  8409. originalLine: original != null && original.line,
  8410. originalColumn: original != null && original.column,
  8411. source: source,
  8412. name: name
  8413. });
  8414. };
  8415. /**
  8416. * Set the source content for a source file.
  8417. */
  8418. SourceMapGenerator$2.prototype.setSourceContent =
  8419. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8420. var source = aSourceFile;
  8421. if (this._sourceRoot != null) {
  8422. source = util$2.relative(this._sourceRoot, source);
  8423. }
  8424. if (aSourceContent != null) {
  8425. // Add the source content to the _sourcesContents map.
  8426. // Create a new _sourcesContents map if the property is null.
  8427. if (!this._sourcesContents) {
  8428. this._sourcesContents = Object.create(null);
  8429. }
  8430. this._sourcesContents[util$2.toSetString(source)] = aSourceContent;
  8431. } else if (this._sourcesContents) {
  8432. // Remove the source file from the _sourcesContents map.
  8433. // If the _sourcesContents map is empty, set the property to null.
  8434. delete this._sourcesContents[util$2.toSetString(source)];
  8435. if (Object.keys(this._sourcesContents).length === 0) {
  8436. this._sourcesContents = null;
  8437. }
  8438. }
  8439. };
  8440. /**
  8441. * Applies the mappings of a sub-source-map for a specific source file to the
  8442. * source map being generated. Each mapping to the supplied source file is
  8443. * rewritten using the supplied source map. Note: The resolution for the
  8444. * resulting mappings is the minimium of this map and the supplied map.
  8445. *
  8446. * @param aSourceMapConsumer The source map to be applied.
  8447. * @param aSourceFile Optional. The filename of the source file.
  8448. * If omitted, SourceMapConsumer's file property will be used.
  8449. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8450. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8451. * This parameter is needed when the two source maps aren't in the same
  8452. * directory, and the source map to be applied contains relative source
  8453. * paths. If so, those relative source paths need to be rewritten
  8454. * relative to the SourceMapGenerator.
  8455. */
  8456. SourceMapGenerator$2.prototype.applySourceMap =
  8457. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8458. var sourceFile = aSourceFile;
  8459. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8460. if (aSourceFile == null) {
  8461. if (aSourceMapConsumer.file == null) {
  8462. throw new Error(
  8463. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8464. 'or the source map\'s "file" property. Both were omitted.'
  8465. );
  8466. }
  8467. sourceFile = aSourceMapConsumer.file;
  8468. }
  8469. var sourceRoot = this._sourceRoot;
  8470. // Make "sourceFile" relative if an absolute Url is passed.
  8471. if (sourceRoot != null) {
  8472. sourceFile = util$2.relative(sourceRoot, sourceFile);
  8473. }
  8474. // Applying the SourceMap can add and remove items from the sources and
  8475. // the names array.
  8476. var newSources = new ArraySet$1();
  8477. var newNames = new ArraySet$1();
  8478. // Find mappings for the "sourceFile"
  8479. this._mappings.unsortedForEach(function (mapping) {
  8480. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8481. // Check if it can be mapped by the source map, then update the mapping.
  8482. var original = aSourceMapConsumer.originalPositionFor({
  8483. line: mapping.originalLine,
  8484. column: mapping.originalColumn
  8485. });
  8486. if (original.source != null) {
  8487. // Copy mapping
  8488. mapping.source = original.source;
  8489. if (aSourceMapPath != null) {
  8490. mapping.source = util$2.join(aSourceMapPath, mapping.source);
  8491. }
  8492. if (sourceRoot != null) {
  8493. mapping.source = util$2.relative(sourceRoot, mapping.source);
  8494. }
  8495. mapping.originalLine = original.line;
  8496. mapping.originalColumn = original.column;
  8497. if (original.name != null) {
  8498. mapping.name = original.name;
  8499. }
  8500. }
  8501. }
  8502. var source = mapping.source;
  8503. if (source != null && !newSources.has(source)) {
  8504. newSources.add(source);
  8505. }
  8506. var name = mapping.name;
  8507. if (name != null && !newNames.has(name)) {
  8508. newNames.add(name);
  8509. }
  8510. }, this);
  8511. this._sources = newSources;
  8512. this._names = newNames;
  8513. // Copy sourcesContents of applied map.
  8514. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8515. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8516. if (content != null) {
  8517. if (aSourceMapPath != null) {
  8518. sourceFile = util$2.join(aSourceMapPath, sourceFile);
  8519. }
  8520. if (sourceRoot != null) {
  8521. sourceFile = util$2.relative(sourceRoot, sourceFile);
  8522. }
  8523. this.setSourceContent(sourceFile, content);
  8524. }
  8525. }, this);
  8526. };
  8527. /**
  8528. * A mapping can have one of the three levels of data:
  8529. *
  8530. * 1. Just the generated position.
  8531. * 2. The Generated position, original position, and original source.
  8532. * 3. Generated and original position, original source, as well as a name
  8533. * token.
  8534. *
  8535. * To maintain consistency, we validate that any new mapping being added falls
  8536. * in to one of these categories.
  8537. */
  8538. SourceMapGenerator$2.prototype._validateMapping =
  8539. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8540. aName) {
  8541. // When aOriginal is truthy but has empty values for .line and .column,
  8542. // it is most likely a programmer error. In this case we throw a very
  8543. // specific error message to try to guide them the right way.
  8544. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8545. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8546. throw new Error(
  8547. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8548. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8549. 'null for the original mapping instead of an object with empty or null values.'
  8550. );
  8551. }
  8552. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8553. && aGenerated.line > 0 && aGenerated.column >= 0
  8554. && !aOriginal && !aSource && !aName) {
  8555. // Case 1.
  8556. return;
  8557. }
  8558. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8559. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8560. && aGenerated.line > 0 && aGenerated.column >= 0
  8561. && aOriginal.line > 0 && aOriginal.column >= 0
  8562. && aSource) {
  8563. // Cases 2 and 3.
  8564. return;
  8565. }
  8566. else {
  8567. throw new Error('Invalid mapping: ' + JSON.stringify({
  8568. generated: aGenerated,
  8569. source: aSource,
  8570. original: aOriginal,
  8571. name: aName
  8572. }));
  8573. }
  8574. };
  8575. /**
  8576. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8577. * specified by the source map format.
  8578. */
  8579. SourceMapGenerator$2.prototype._serializeMappings =
  8580. function SourceMapGenerator_serializeMappings() {
  8581. var previousGeneratedColumn = 0;
  8582. var previousGeneratedLine = 1;
  8583. var previousOriginalColumn = 0;
  8584. var previousOriginalLine = 0;
  8585. var previousName = 0;
  8586. var previousSource = 0;
  8587. var result = '';
  8588. var next;
  8589. var mapping;
  8590. var nameIdx;
  8591. var sourceIdx;
  8592. var mappings = this._mappings.toArray();
  8593. for (var i = 0, len = mappings.length; i < len; i++) {
  8594. mapping = mappings[i];
  8595. next = '';
  8596. if (mapping.generatedLine !== previousGeneratedLine) {
  8597. previousGeneratedColumn = 0;
  8598. while (mapping.generatedLine !== previousGeneratedLine) {
  8599. next += ';';
  8600. previousGeneratedLine++;
  8601. }
  8602. }
  8603. else {
  8604. if (i > 0) {
  8605. if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8606. continue;
  8607. }
  8608. next += ',';
  8609. }
  8610. }
  8611. next += base64VLQ$1.encode(mapping.generatedColumn
  8612. - previousGeneratedColumn);
  8613. previousGeneratedColumn = mapping.generatedColumn;
  8614. if (mapping.source != null) {
  8615. sourceIdx = this._sources.indexOf(mapping.source);
  8616. next += base64VLQ$1.encode(sourceIdx - previousSource);
  8617. previousSource = sourceIdx;
  8618. // lines are stored 0-based in SourceMap spec version 3
  8619. next += base64VLQ$1.encode(mapping.originalLine - 1
  8620. - previousOriginalLine);
  8621. previousOriginalLine = mapping.originalLine - 1;
  8622. next += base64VLQ$1.encode(mapping.originalColumn
  8623. - previousOriginalColumn);
  8624. previousOriginalColumn = mapping.originalColumn;
  8625. if (mapping.name != null) {
  8626. nameIdx = this._names.indexOf(mapping.name);
  8627. next += base64VLQ$1.encode(nameIdx - previousName);
  8628. previousName = nameIdx;
  8629. }
  8630. }
  8631. result += next;
  8632. }
  8633. return result;
  8634. };
  8635. SourceMapGenerator$2.prototype._generateSourcesContent =
  8636. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  8637. return aSources.map(function (source) {
  8638. if (!this._sourcesContents) {
  8639. return null;
  8640. }
  8641. if (aSourceRoot != null) {
  8642. source = util$2.relative(aSourceRoot, source);
  8643. }
  8644. var key = util$2.toSetString(source);
  8645. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  8646. ? this._sourcesContents[key]
  8647. : null;
  8648. }, this);
  8649. };
  8650. /**
  8651. * Externalize the source map.
  8652. */
  8653. SourceMapGenerator$2.prototype.toJSON =
  8654. function SourceMapGenerator_toJSON() {
  8655. var map = {
  8656. version: this._version,
  8657. sources: this._sources.toArray(),
  8658. names: this._names.toArray(),
  8659. mappings: this._serializeMappings()
  8660. };
  8661. if (this._file != null) {
  8662. map.file = this._file;
  8663. }
  8664. if (this._sourceRoot != null) {
  8665. map.sourceRoot = this._sourceRoot;
  8666. }
  8667. if (this._sourcesContents) {
  8668. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  8669. }
  8670. return map;
  8671. };
  8672. /**
  8673. * Render the source map being generated to a string.
  8674. */
  8675. SourceMapGenerator$2.prototype.toString =
  8676. function SourceMapGenerator_toString() {
  8677. return JSON.stringify(this.toJSON());
  8678. };
  8679. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$2;
  8680. var sourceMapConsumer = {};
  8681. var binarySearch$1 = {};
  8682. /* -*- Mode: js; js-indent-level: 2; -*- */
  8683. (function (exports) {
  8684. /*
  8685. * Copyright 2011 Mozilla Foundation and contributors
  8686. * Licensed under the New BSD license. See LICENSE or:
  8687. * http://opensource.org/licenses/BSD-3-Clause
  8688. */
  8689. exports.GREATEST_LOWER_BOUND = 1;
  8690. exports.LEAST_UPPER_BOUND = 2;
  8691. /**
  8692. * Recursive implementation of binary search.
  8693. *
  8694. * @param aLow Indices here and lower do not contain the needle.
  8695. * @param aHigh Indices here and higher do not contain the needle.
  8696. * @param aNeedle The element being searched for.
  8697. * @param aHaystack The non-empty array being searched.
  8698. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  8699. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8700. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8701. * closest element that is smaller than or greater than the one we are
  8702. * searching for, respectively, if the exact element cannot be found.
  8703. */
  8704. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  8705. // This function terminates when one of the following is true:
  8706. //
  8707. // 1. We find the exact element we are looking for.
  8708. //
  8709. // 2. We did not find the exact element, but we can return the index of
  8710. // the next-closest element.
  8711. //
  8712. // 3. We did not find the exact element, and there is no next-closest
  8713. // element than the one we are searching for, so we return -1.
  8714. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  8715. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  8716. if (cmp === 0) {
  8717. // Found the element we are looking for.
  8718. return mid;
  8719. }
  8720. else if (cmp > 0) {
  8721. // Our needle is greater than aHaystack[mid].
  8722. if (aHigh - mid > 1) {
  8723. // The element is in the upper half.
  8724. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  8725. }
  8726. // The exact needle element was not found in this haystack. Determine if
  8727. // we are in termination case (3) or (2) and return the appropriate thing.
  8728. if (aBias == exports.LEAST_UPPER_BOUND) {
  8729. return aHigh < aHaystack.length ? aHigh : -1;
  8730. } else {
  8731. return mid;
  8732. }
  8733. }
  8734. else {
  8735. // Our needle is less than aHaystack[mid].
  8736. if (mid - aLow > 1) {
  8737. // The element is in the lower half.
  8738. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  8739. }
  8740. // we are in termination case (3) or (2) and return the appropriate thing.
  8741. if (aBias == exports.LEAST_UPPER_BOUND) {
  8742. return mid;
  8743. } else {
  8744. return aLow < 0 ? -1 : aLow;
  8745. }
  8746. }
  8747. }
  8748. /**
  8749. * This is an implementation of binary search which will always try and return
  8750. * the index of the closest element if there is no exact hit. This is because
  8751. * mappings between original and generated line/col pairs are single points,
  8752. * and there is an implicit region between each of them, so a miss just means
  8753. * that you aren't on the very start of a region.
  8754. *
  8755. * @param aNeedle The element you are looking for.
  8756. * @param aHaystack The array that is being searched.
  8757. * @param aCompare A function which takes the needle and an element in the
  8758. * array and returns -1, 0, or 1 depending on whether the needle is less
  8759. * than, equal to, or greater than the element, respectively.
  8760. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8761. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8762. * closest element that is smaller than or greater than the one we are
  8763. * searching for, respectively, if the exact element cannot be found.
  8764. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  8765. */
  8766. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  8767. if (aHaystack.length === 0) {
  8768. return -1;
  8769. }
  8770. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  8771. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  8772. if (index < 0) {
  8773. return -1;
  8774. }
  8775. // We have found either the exact element, or the next-closest element than
  8776. // the one we are searching for. However, there may be more than one such
  8777. // element. Make sure we always return the smallest of these.
  8778. while (index - 1 >= 0) {
  8779. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  8780. break;
  8781. }
  8782. --index;
  8783. }
  8784. return index;
  8785. };
  8786. } (binarySearch$1));
  8787. var quickSort$1 = {};
  8788. /* -*- Mode: js; js-indent-level: 2; -*- */
  8789. /*
  8790. * Copyright 2011 Mozilla Foundation and contributors
  8791. * Licensed under the New BSD license. See LICENSE or:
  8792. * http://opensource.org/licenses/BSD-3-Clause
  8793. */
  8794. // It turns out that some (most?) JavaScript engines don't self-host
  8795. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  8796. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  8797. // custom comparator function, calling back and forth between the VM's C++ and
  8798. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  8799. // worse generated code for the comparator function than would be optimal. In
  8800. // fact, when sorting with a comparator, these costs outweigh the benefits of
  8801. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  8802. // a ~3500ms mean speed-up in `bench/bench.html`.
  8803. /**
  8804. * Swap the elements indexed by `x` and `y` in the array `ary`.
  8805. *
  8806. * @param {Array} ary
  8807. * The array.
  8808. * @param {Number} x
  8809. * The index of the first item.
  8810. * @param {Number} y
  8811. * The index of the second item.
  8812. */
  8813. function swap(ary, x, y) {
  8814. var temp = ary[x];
  8815. ary[x] = ary[y];
  8816. ary[y] = temp;
  8817. }
  8818. /**
  8819. * Returns a random integer within the range `low .. high` inclusive.
  8820. *
  8821. * @param {Number} low
  8822. * The lower bound on the range.
  8823. * @param {Number} high
  8824. * The upper bound on the range.
  8825. */
  8826. function randomIntInRange(low, high) {
  8827. return Math.round(low + (Math.random() * (high - low)));
  8828. }
  8829. /**
  8830. * The Quick Sort algorithm.
  8831. *
  8832. * @param {Array} ary
  8833. * An array to sort.
  8834. * @param {function} comparator
  8835. * Function to use to compare two items.
  8836. * @param {Number} p
  8837. * Start index of the array
  8838. * @param {Number} r
  8839. * End index of the array
  8840. */
  8841. function doQuickSort(ary, comparator, p, r) {
  8842. // If our lower bound is less than our upper bound, we (1) partition the
  8843. // array into two pieces and (2) recurse on each half. If it is not, this is
  8844. // the empty array and our base case.
  8845. if (p < r) {
  8846. // (1) Partitioning.
  8847. //
  8848. // The partitioning chooses a pivot between `p` and `r` and moves all
  8849. // elements that are less than or equal to the pivot to the before it, and
  8850. // all the elements that are greater than it after it. The effect is that
  8851. // once partition is done, the pivot is in the exact place it will be when
  8852. // the array is put in sorted order, and it will not need to be moved
  8853. // again. This runs in O(n) time.
  8854. // Always choose a random pivot so that an input array which is reverse
  8855. // sorted does not cause O(n^2) running time.
  8856. var pivotIndex = randomIntInRange(p, r);
  8857. var i = p - 1;
  8858. swap(ary, pivotIndex, r);
  8859. var pivot = ary[r];
  8860. // Immediately after `j` is incremented in this loop, the following hold
  8861. // true:
  8862. //
  8863. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  8864. //
  8865. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  8866. for (var j = p; j < r; j++) {
  8867. if (comparator(ary[j], pivot) <= 0) {
  8868. i += 1;
  8869. swap(ary, i, j);
  8870. }
  8871. }
  8872. swap(ary, i + 1, j);
  8873. var q = i + 1;
  8874. // (2) Recurse on each half.
  8875. doQuickSort(ary, comparator, p, q - 1);
  8876. doQuickSort(ary, comparator, q + 1, r);
  8877. }
  8878. }
  8879. /**
  8880. * Sort the given array in-place with the given comparator function.
  8881. *
  8882. * @param {Array} ary
  8883. * An array to sort.
  8884. * @param {function} comparator
  8885. * Function to use to compare two items.
  8886. */
  8887. quickSort$1.quickSort = function (ary, comparator) {
  8888. doQuickSort(ary, comparator, 0, ary.length - 1);
  8889. };
  8890. /* -*- Mode: js; js-indent-level: 2; -*- */
  8891. /*
  8892. * Copyright 2011 Mozilla Foundation and contributors
  8893. * Licensed under the New BSD license. See LICENSE or:
  8894. * http://opensource.org/licenses/BSD-3-Clause
  8895. */
  8896. var util$1 = util$5;
  8897. var binarySearch = binarySearch$1;
  8898. var ArraySet = arraySet.ArraySet;
  8899. var base64VLQ = base64Vlq;
  8900. var quickSort = quickSort$1.quickSort;
  8901. function SourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  8902. var sourceMap = aSourceMap;
  8903. if (typeof aSourceMap === 'string') {
  8904. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  8905. }
  8906. return sourceMap.sections != null
  8907. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  8908. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  8909. }
  8910. SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  8911. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  8912. };
  8913. /**
  8914. * The version of the source mapping spec that we are consuming.
  8915. */
  8916. SourceMapConsumer$1.prototype._version = 3;
  8917. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  8918. // parsed mapping coordinates from the source map's "mappings" attribute. They
  8919. // are lazily instantiated, accessed via the `_generatedMappings` and
  8920. // `_originalMappings` getters respectively, and we only parse the mappings
  8921. // and create these arrays once queried for a source location. We jump through
  8922. // these hoops because there can be many thousands of mappings, and parsing
  8923. // them is expensive, so we only want to do it if we must.
  8924. //
  8925. // Each object in the arrays is of the form:
  8926. //
  8927. // {
  8928. // generatedLine: The line number in the generated code,
  8929. // generatedColumn: The column number in the generated code,
  8930. // source: The path to the original source file that generated this
  8931. // chunk of code,
  8932. // originalLine: The line number in the original source that
  8933. // corresponds to this chunk of generated code,
  8934. // originalColumn: The column number in the original source that
  8935. // corresponds to this chunk of generated code,
  8936. // name: The name of the original symbol which generated this chunk of
  8937. // code.
  8938. // }
  8939. //
  8940. // All properties except for `generatedLine` and `generatedColumn` can be
  8941. // `null`.
  8942. //
  8943. // `_generatedMappings` is ordered by the generated positions.
  8944. //
  8945. // `_originalMappings` is ordered by the original positions.
  8946. SourceMapConsumer$1.prototype.__generatedMappings = null;
  8947. Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', {
  8948. configurable: true,
  8949. enumerable: true,
  8950. get: function () {
  8951. if (!this.__generatedMappings) {
  8952. this._parseMappings(this._mappings, this.sourceRoot);
  8953. }
  8954. return this.__generatedMappings;
  8955. }
  8956. });
  8957. SourceMapConsumer$1.prototype.__originalMappings = null;
  8958. Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', {
  8959. configurable: true,
  8960. enumerable: true,
  8961. get: function () {
  8962. if (!this.__originalMappings) {
  8963. this._parseMappings(this._mappings, this.sourceRoot);
  8964. }
  8965. return this.__originalMappings;
  8966. }
  8967. });
  8968. SourceMapConsumer$1.prototype._charIsMappingSeparator =
  8969. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  8970. var c = aStr.charAt(index);
  8971. return c === ";" || c === ",";
  8972. };
  8973. /**
  8974. * Parse the mappings in a string in to a data structure which we can easily
  8975. * query (the ordered arrays in the `this.__generatedMappings` and
  8976. * `this.__originalMappings` properties).
  8977. */
  8978. SourceMapConsumer$1.prototype._parseMappings =
  8979. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  8980. throw new Error("Subclasses must implement _parseMappings");
  8981. };
  8982. SourceMapConsumer$1.GENERATED_ORDER = 1;
  8983. SourceMapConsumer$1.ORIGINAL_ORDER = 2;
  8984. SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1;
  8985. SourceMapConsumer$1.LEAST_UPPER_BOUND = 2;
  8986. /**
  8987. * Iterate over each mapping between an original source/line/column and a
  8988. * generated line/column in this source map.
  8989. *
  8990. * @param Function aCallback
  8991. * The function that is called with each mapping.
  8992. * @param Object aContext
  8993. * Optional. If specified, this object will be the value of `this` every
  8994. * time that `aCallback` is called.
  8995. * @param aOrder
  8996. * Either `SourceMapConsumer.GENERATED_ORDER` or
  8997. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  8998. * iterate over the mappings sorted by the generated file's line/column
  8999. * order or the original's source/line/column order, respectively. Defaults to
  9000. * `SourceMapConsumer.GENERATED_ORDER`.
  9001. */
  9002. SourceMapConsumer$1.prototype.eachMapping =
  9003. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9004. var context = aContext || null;
  9005. var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER;
  9006. var mappings;
  9007. switch (order) {
  9008. case SourceMapConsumer$1.GENERATED_ORDER:
  9009. mappings = this._generatedMappings;
  9010. break;
  9011. case SourceMapConsumer$1.ORIGINAL_ORDER:
  9012. mappings = this._originalMappings;
  9013. break;
  9014. default:
  9015. throw new Error("Unknown order of iteration.");
  9016. }
  9017. var sourceRoot = this.sourceRoot;
  9018. mappings.map(function (mapping) {
  9019. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9020. source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9021. return {
  9022. source: source,
  9023. generatedLine: mapping.generatedLine,
  9024. generatedColumn: mapping.generatedColumn,
  9025. originalLine: mapping.originalLine,
  9026. originalColumn: mapping.originalColumn,
  9027. name: mapping.name === null ? null : this._names.at(mapping.name)
  9028. };
  9029. }, this).forEach(aCallback, context);
  9030. };
  9031. /**
  9032. * Returns all generated line and column information for the original source,
  9033. * line, and column provided. If no column is provided, returns all mappings
  9034. * corresponding to a either the line we are searching for or the next
  9035. * closest line that has any mappings. Otherwise, returns all mappings
  9036. * corresponding to the given line and either the column we are searching for
  9037. * or the next closest column that has any offsets.
  9038. *
  9039. * The only argument is an object with the following properties:
  9040. *
  9041. * - source: The filename of the original source.
  9042. * - line: The line number in the original source. The line number is 1-based.
  9043. * - column: Optional. the column number in the original source.
  9044. * The column number is 0-based.
  9045. *
  9046. * and an array of objects is returned, each with the following properties:
  9047. *
  9048. * - line: The line number in the generated source, or null. The
  9049. * line number is 1-based.
  9050. * - column: The column number in the generated source, or null.
  9051. * The column number is 0-based.
  9052. */
  9053. SourceMapConsumer$1.prototype.allGeneratedPositionsFor =
  9054. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9055. var line = util$1.getArg(aArgs, 'line');
  9056. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9057. // returns the index of the closest mapping less than the needle. By
  9058. // setting needle.originalColumn to 0, we thus find the last mapping for
  9059. // the given line, provided such a mapping exists.
  9060. var needle = {
  9061. source: util$1.getArg(aArgs, 'source'),
  9062. originalLine: line,
  9063. originalColumn: util$1.getArg(aArgs, 'column', 0)
  9064. };
  9065. needle.source = this._findSourceIndex(needle.source);
  9066. if (needle.source < 0) {
  9067. return [];
  9068. }
  9069. var mappings = [];
  9070. var index = this._findMapping(needle,
  9071. this._originalMappings,
  9072. "originalLine",
  9073. "originalColumn",
  9074. util$1.compareByOriginalPositions,
  9075. binarySearch.LEAST_UPPER_BOUND);
  9076. if (index >= 0) {
  9077. var mapping = this._originalMappings[index];
  9078. if (aArgs.column === undefined) {
  9079. var originalLine = mapping.originalLine;
  9080. // Iterate until either we run out of mappings, or we run into
  9081. // a mapping for a different line than the one we found. Since
  9082. // mappings are sorted, this is guaranteed to find all mappings for
  9083. // the line we found.
  9084. while (mapping && mapping.originalLine === originalLine) {
  9085. mappings.push({
  9086. line: util$1.getArg(mapping, 'generatedLine', null),
  9087. column: util$1.getArg(mapping, 'generatedColumn', null),
  9088. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  9089. });
  9090. mapping = this._originalMappings[++index];
  9091. }
  9092. } else {
  9093. var originalColumn = mapping.originalColumn;
  9094. // Iterate until either we run out of mappings, or we run into
  9095. // a mapping for a different line than the one we were searching for.
  9096. // Since mappings are sorted, this is guaranteed to find all mappings for
  9097. // the line we are searching for.
  9098. while (mapping &&
  9099. mapping.originalLine === line &&
  9100. mapping.originalColumn == originalColumn) {
  9101. mappings.push({
  9102. line: util$1.getArg(mapping, 'generatedLine', null),
  9103. column: util$1.getArg(mapping, 'generatedColumn', null),
  9104. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  9105. });
  9106. mapping = this._originalMappings[++index];
  9107. }
  9108. }
  9109. }
  9110. return mappings;
  9111. };
  9112. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1;
  9113. /**
  9114. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9115. * query for information about the original file positions by giving it a file
  9116. * position in the generated source.
  9117. *
  9118. * The first parameter is the raw source map (either as a JSON string, or
  9119. * already parsed to an object). According to the spec, source maps have the
  9120. * following attributes:
  9121. *
  9122. * - version: Which version of the source map spec this map is following.
  9123. * - sources: An array of URLs to the original source files.
  9124. * - names: An array of identifiers which can be referrenced by individual mappings.
  9125. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9126. * - sourcesContent: Optional. An array of contents of the original source files.
  9127. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9128. * - file: Optional. The generated file this source map is associated with.
  9129. *
  9130. * Here is an example source map, taken from the source map spec[0]:
  9131. *
  9132. * {
  9133. * version : 3,
  9134. * file: "out.js",
  9135. * sourceRoot : "",
  9136. * sources: ["foo.js", "bar.js"],
  9137. * names: ["src", "maps", "are", "fun"],
  9138. * mappings: "AA,AB;;ABCDE;"
  9139. * }
  9140. *
  9141. * The second parameter, if given, is a string whose value is the URL
  9142. * at which the source map was found. This URL is used to compute the
  9143. * sources array.
  9144. *
  9145. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9146. */
  9147. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9148. var sourceMap = aSourceMap;
  9149. if (typeof aSourceMap === 'string') {
  9150. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  9151. }
  9152. var version = util$1.getArg(sourceMap, 'version');
  9153. var sources = util$1.getArg(sourceMap, 'sources');
  9154. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9155. // requires the array) to play nice here.
  9156. var names = util$1.getArg(sourceMap, 'names', []);
  9157. var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
  9158. var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
  9159. var mappings = util$1.getArg(sourceMap, 'mappings');
  9160. var file = util$1.getArg(sourceMap, 'file', null);
  9161. // Once again, Sass deviates from the spec and supplies the version as a
  9162. // string rather than a number, so we use loose equality checking here.
  9163. if (version != this._version) {
  9164. throw new Error('Unsupported version: ' + version);
  9165. }
  9166. if (sourceRoot) {
  9167. sourceRoot = util$1.normalize(sourceRoot);
  9168. }
  9169. sources = sources
  9170. .map(String)
  9171. // Some source maps produce relative source paths like "./foo.js" instead of
  9172. // "foo.js". Normalize these first so that future comparisons will succeed.
  9173. // See bugzil.la/1090768.
  9174. .map(util$1.normalize)
  9175. // Always ensure that absolute sources are internally stored relative to
  9176. // the source root, if the source root is absolute. Not doing this would
  9177. // be particularly problematic when the source root is a prefix of the
  9178. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9179. .map(function (source) {
  9180. return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
  9181. ? util$1.relative(sourceRoot, source)
  9182. : source;
  9183. });
  9184. // Pass `true` below to allow duplicate names and sources. While source maps
  9185. // are intended to be compressed and deduplicated, the TypeScript compiler
  9186. // sometimes generates source maps with duplicates in them. See Github issue
  9187. // #72 and bugzil.la/889492.
  9188. this._names = ArraySet.fromArray(names.map(String), true);
  9189. this._sources = ArraySet.fromArray(sources, true);
  9190. this._absoluteSources = this._sources.toArray().map(function (s) {
  9191. return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9192. });
  9193. this.sourceRoot = sourceRoot;
  9194. this.sourcesContent = sourcesContent;
  9195. this._mappings = mappings;
  9196. this._sourceMapURL = aSourceMapURL;
  9197. this.file = file;
  9198. }
  9199. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  9200. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1;
  9201. /**
  9202. * Utility function to find the index of a source. Returns -1 if not
  9203. * found.
  9204. */
  9205. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9206. var relativeSource = aSource;
  9207. if (this.sourceRoot != null) {
  9208. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  9209. }
  9210. if (this._sources.has(relativeSource)) {
  9211. return this._sources.indexOf(relativeSource);
  9212. }
  9213. // Maybe aSource is an absolute URL as returned by |sources|. In
  9214. // this case we can't simply undo the transform.
  9215. var i;
  9216. for (i = 0; i < this._absoluteSources.length; ++i) {
  9217. if (this._absoluteSources[i] == aSource) {
  9218. return i;
  9219. }
  9220. }
  9221. return -1;
  9222. };
  9223. /**
  9224. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9225. *
  9226. * @param SourceMapGenerator aSourceMap
  9227. * The source map that will be consumed.
  9228. * @param String aSourceMapURL
  9229. * The URL at which the source map can be found (optional)
  9230. * @returns BasicSourceMapConsumer
  9231. */
  9232. BasicSourceMapConsumer.fromSourceMap =
  9233. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9234. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9235. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9236. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9237. smc.sourceRoot = aSourceMap._sourceRoot;
  9238. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9239. smc.sourceRoot);
  9240. smc.file = aSourceMap._file;
  9241. smc._sourceMapURL = aSourceMapURL;
  9242. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9243. return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9244. });
  9245. // Because we are modifying the entries (by converting string sources and
  9246. // names to indices into the sources and names ArraySets), we have to make
  9247. // a copy of the entry or else bad things happen. Shared mutable state
  9248. // strikes again! See github issue #191.
  9249. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9250. var destGeneratedMappings = smc.__generatedMappings = [];
  9251. var destOriginalMappings = smc.__originalMappings = [];
  9252. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9253. var srcMapping = generatedMappings[i];
  9254. var destMapping = new Mapping;
  9255. destMapping.generatedLine = srcMapping.generatedLine;
  9256. destMapping.generatedColumn = srcMapping.generatedColumn;
  9257. if (srcMapping.source) {
  9258. destMapping.source = sources.indexOf(srcMapping.source);
  9259. destMapping.originalLine = srcMapping.originalLine;
  9260. destMapping.originalColumn = srcMapping.originalColumn;
  9261. if (srcMapping.name) {
  9262. destMapping.name = names.indexOf(srcMapping.name);
  9263. }
  9264. destOriginalMappings.push(destMapping);
  9265. }
  9266. destGeneratedMappings.push(destMapping);
  9267. }
  9268. quickSort(smc.__originalMappings, util$1.compareByOriginalPositions);
  9269. return smc;
  9270. };
  9271. /**
  9272. * The version of the source mapping spec that we are consuming.
  9273. */
  9274. BasicSourceMapConsumer.prototype._version = 3;
  9275. /**
  9276. * The list of original sources.
  9277. */
  9278. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9279. get: function () {
  9280. return this._absoluteSources.slice();
  9281. }
  9282. });
  9283. /**
  9284. * Provide the JIT with a nice shape / hidden class.
  9285. */
  9286. function Mapping() {
  9287. this.generatedLine = 0;
  9288. this.generatedColumn = 0;
  9289. this.source = null;
  9290. this.originalLine = null;
  9291. this.originalColumn = null;
  9292. this.name = null;
  9293. }
  9294. /**
  9295. * Parse the mappings in a string in to a data structure which we can easily
  9296. * query (the ordered arrays in the `this.__generatedMappings` and
  9297. * `this.__originalMappings` properties).
  9298. */
  9299. BasicSourceMapConsumer.prototype._parseMappings =
  9300. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9301. var generatedLine = 1;
  9302. var previousGeneratedColumn = 0;
  9303. var previousOriginalLine = 0;
  9304. var previousOriginalColumn = 0;
  9305. var previousSource = 0;
  9306. var previousName = 0;
  9307. var length = aStr.length;
  9308. var index = 0;
  9309. var cachedSegments = {};
  9310. var temp = {};
  9311. var originalMappings = [];
  9312. var generatedMappings = [];
  9313. var mapping, str, segment, end, value;
  9314. while (index < length) {
  9315. if (aStr.charAt(index) === ';') {
  9316. generatedLine++;
  9317. index++;
  9318. previousGeneratedColumn = 0;
  9319. }
  9320. else if (aStr.charAt(index) === ',') {
  9321. index++;
  9322. }
  9323. else {
  9324. mapping = new Mapping();
  9325. mapping.generatedLine = generatedLine;
  9326. // Because each offset is encoded relative to the previous one,
  9327. // many segments often have the same encoding. We can exploit this
  9328. // fact by caching the parsed variable length fields of each segment,
  9329. // allowing us to avoid a second parse if we encounter the same
  9330. // segment again.
  9331. for (end = index; end < length; end++) {
  9332. if (this._charIsMappingSeparator(aStr, end)) {
  9333. break;
  9334. }
  9335. }
  9336. str = aStr.slice(index, end);
  9337. segment = cachedSegments[str];
  9338. if (segment) {
  9339. index += str.length;
  9340. } else {
  9341. segment = [];
  9342. while (index < end) {
  9343. base64VLQ.decode(aStr, index, temp);
  9344. value = temp.value;
  9345. index = temp.rest;
  9346. segment.push(value);
  9347. }
  9348. if (segment.length === 2) {
  9349. throw new Error('Found a source, but no line and column');
  9350. }
  9351. if (segment.length === 3) {
  9352. throw new Error('Found a source and line, but no column');
  9353. }
  9354. cachedSegments[str] = segment;
  9355. }
  9356. // Generated column.
  9357. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9358. previousGeneratedColumn = mapping.generatedColumn;
  9359. if (segment.length > 1) {
  9360. // Original source.
  9361. mapping.source = previousSource + segment[1];
  9362. previousSource += segment[1];
  9363. // Original line.
  9364. mapping.originalLine = previousOriginalLine + segment[2];
  9365. previousOriginalLine = mapping.originalLine;
  9366. // Lines are stored 0-based
  9367. mapping.originalLine += 1;
  9368. // Original column.
  9369. mapping.originalColumn = previousOriginalColumn + segment[3];
  9370. previousOriginalColumn = mapping.originalColumn;
  9371. if (segment.length > 4) {
  9372. // Original name.
  9373. mapping.name = previousName + segment[4];
  9374. previousName += segment[4];
  9375. }
  9376. }
  9377. generatedMappings.push(mapping);
  9378. if (typeof mapping.originalLine === 'number') {
  9379. originalMappings.push(mapping);
  9380. }
  9381. }
  9382. }
  9383. quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  9384. this.__generatedMappings = generatedMappings;
  9385. quickSort(originalMappings, util$1.compareByOriginalPositions);
  9386. this.__originalMappings = originalMappings;
  9387. };
  9388. /**
  9389. * Find the mapping that best matches the hypothetical "needle" mapping that
  9390. * we are searching for in the given "haystack" of mappings.
  9391. */
  9392. BasicSourceMapConsumer.prototype._findMapping =
  9393. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9394. aColumnName, aComparator, aBias) {
  9395. // To return the position we are searching for, we must first find the
  9396. // mapping for the given position and then return the opposite position it
  9397. // points to. Because the mappings are sorted, we can use binary search to
  9398. // find the best mapping.
  9399. if (aNeedle[aLineName] <= 0) {
  9400. throw new TypeError('Line must be greater than or equal to 1, got '
  9401. + aNeedle[aLineName]);
  9402. }
  9403. if (aNeedle[aColumnName] < 0) {
  9404. throw new TypeError('Column must be greater than or equal to 0, got '
  9405. + aNeedle[aColumnName]);
  9406. }
  9407. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9408. };
  9409. /**
  9410. * Compute the last column for each generated mapping. The last column is
  9411. * inclusive.
  9412. */
  9413. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9414. function SourceMapConsumer_computeColumnSpans() {
  9415. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9416. var mapping = this._generatedMappings[index];
  9417. // Mappings do not contain a field for the last generated columnt. We
  9418. // can come up with an optimistic estimate, however, by assuming that
  9419. // mappings are contiguous (i.e. given two consecutive mappings, the
  9420. // first mapping ends where the second one starts).
  9421. if (index + 1 < this._generatedMappings.length) {
  9422. var nextMapping = this._generatedMappings[index + 1];
  9423. if (mapping.generatedLine === nextMapping.generatedLine) {
  9424. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9425. continue;
  9426. }
  9427. }
  9428. // The last mapping for each line spans the entire line.
  9429. mapping.lastGeneratedColumn = Infinity;
  9430. }
  9431. };
  9432. /**
  9433. * Returns the original source, line, and column information for the generated
  9434. * source's line and column positions provided. The only argument is an object
  9435. * with the following properties:
  9436. *
  9437. * - line: The line number in the generated source. The line number
  9438. * is 1-based.
  9439. * - column: The column number in the generated source. The column
  9440. * number is 0-based.
  9441. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9442. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9443. * closest element that is smaller than or greater than the one we are
  9444. * searching for, respectively, if the exact element cannot be found.
  9445. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9446. *
  9447. * and an object is returned with the following properties:
  9448. *
  9449. * - source: The original source file, or null.
  9450. * - line: The line number in the original source, or null. The
  9451. * line number is 1-based.
  9452. * - column: The column number in the original source, or null. The
  9453. * column number is 0-based.
  9454. * - name: The original identifier, or null.
  9455. */
  9456. BasicSourceMapConsumer.prototype.originalPositionFor =
  9457. function SourceMapConsumer_originalPositionFor(aArgs) {
  9458. var needle = {
  9459. generatedLine: util$1.getArg(aArgs, 'line'),
  9460. generatedColumn: util$1.getArg(aArgs, 'column')
  9461. };
  9462. var index = this._findMapping(
  9463. needle,
  9464. this._generatedMappings,
  9465. "generatedLine",
  9466. "generatedColumn",
  9467. util$1.compareByGeneratedPositionsDeflated,
  9468. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  9469. );
  9470. if (index >= 0) {
  9471. var mapping = this._generatedMappings[index];
  9472. if (mapping.generatedLine === needle.generatedLine) {
  9473. var source = util$1.getArg(mapping, 'source', null);
  9474. if (source !== null) {
  9475. source = this._sources.at(source);
  9476. source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9477. }
  9478. var name = util$1.getArg(mapping, 'name', null);
  9479. if (name !== null) {
  9480. name = this._names.at(name);
  9481. }
  9482. return {
  9483. source: source,
  9484. line: util$1.getArg(mapping, 'originalLine', null),
  9485. column: util$1.getArg(mapping, 'originalColumn', null),
  9486. name: name
  9487. };
  9488. }
  9489. }
  9490. return {
  9491. source: null,
  9492. line: null,
  9493. column: null,
  9494. name: null
  9495. };
  9496. };
  9497. /**
  9498. * Return true if we have the source content for every source in the source
  9499. * map, false otherwise.
  9500. */
  9501. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9502. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9503. if (!this.sourcesContent) {
  9504. return false;
  9505. }
  9506. return this.sourcesContent.length >= this._sources.size() &&
  9507. !this.sourcesContent.some(function (sc) { return sc == null; });
  9508. };
  9509. /**
  9510. * Returns the original source content. The only argument is the url of the
  9511. * original source file. Returns null if no original source content is
  9512. * available.
  9513. */
  9514. BasicSourceMapConsumer.prototype.sourceContentFor =
  9515. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9516. if (!this.sourcesContent) {
  9517. return null;
  9518. }
  9519. var index = this._findSourceIndex(aSource);
  9520. if (index >= 0) {
  9521. return this.sourcesContent[index];
  9522. }
  9523. var relativeSource = aSource;
  9524. if (this.sourceRoot != null) {
  9525. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  9526. }
  9527. var url;
  9528. if (this.sourceRoot != null
  9529. && (url = util$1.urlParse(this.sourceRoot))) {
  9530. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9531. // many users. We can help them out when they expect file:// URIs to
  9532. // behave like it would if they were running a local HTTP server. See
  9533. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9534. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9535. if (url.scheme == "file"
  9536. && this._sources.has(fileUriAbsPath)) {
  9537. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9538. }
  9539. if ((!url.path || url.path == "/")
  9540. && this._sources.has("/" + relativeSource)) {
  9541. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9542. }
  9543. }
  9544. // This function is used recursively from
  9545. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9546. // don't want to throw if we can't find the source - we just want to
  9547. // return null, so we provide a flag to exit gracefully.
  9548. if (nullOnMissing) {
  9549. return null;
  9550. }
  9551. else {
  9552. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9553. }
  9554. };
  9555. /**
  9556. * Returns the generated line and column information for the original source,
  9557. * line, and column positions provided. The only argument is an object with
  9558. * the following properties:
  9559. *
  9560. * - source: The filename of the original source.
  9561. * - line: The line number in the original source. The line number
  9562. * is 1-based.
  9563. * - column: The column number in the original source. The column
  9564. * number is 0-based.
  9565. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9566. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9567. * closest element that is smaller than or greater than the one we are
  9568. * searching for, respectively, if the exact element cannot be found.
  9569. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9570. *
  9571. * and an object is returned with the following properties:
  9572. *
  9573. * - line: The line number in the generated source, or null. The
  9574. * line number is 1-based.
  9575. * - column: The column number in the generated source, or null.
  9576. * The column number is 0-based.
  9577. */
  9578. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9579. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9580. var source = util$1.getArg(aArgs, 'source');
  9581. source = this._findSourceIndex(source);
  9582. if (source < 0) {
  9583. return {
  9584. line: null,
  9585. column: null,
  9586. lastColumn: null
  9587. };
  9588. }
  9589. var needle = {
  9590. source: source,
  9591. originalLine: util$1.getArg(aArgs, 'line'),
  9592. originalColumn: util$1.getArg(aArgs, 'column')
  9593. };
  9594. var index = this._findMapping(
  9595. needle,
  9596. this._originalMappings,
  9597. "originalLine",
  9598. "originalColumn",
  9599. util$1.compareByOriginalPositions,
  9600. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  9601. );
  9602. if (index >= 0) {
  9603. var mapping = this._originalMappings[index];
  9604. if (mapping.source === needle.source) {
  9605. return {
  9606. line: util$1.getArg(mapping, 'generatedLine', null),
  9607. column: util$1.getArg(mapping, 'generatedColumn', null),
  9608. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  9609. };
  9610. }
  9611. }
  9612. return {
  9613. line: null,
  9614. column: null,
  9615. lastColumn: null
  9616. };
  9617. };
  9618. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  9619. /**
  9620. * An IndexedSourceMapConsumer instance represents a parsed source map which
  9621. * we can query for information. It differs from BasicSourceMapConsumer in
  9622. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  9623. * input.
  9624. *
  9625. * The first parameter is a raw source map (either as a JSON string, or already
  9626. * parsed to an object). According to the spec for indexed source maps, they
  9627. * have the following attributes:
  9628. *
  9629. * - version: Which version of the source map spec this map is following.
  9630. * - file: Optional. The generated file this source map is associated with.
  9631. * - sections: A list of section definitions.
  9632. *
  9633. * Each value under the "sections" field has two fields:
  9634. * - offset: The offset into the original specified at which this section
  9635. * begins to apply, defined as an object with a "line" and "column"
  9636. * field.
  9637. * - map: A source map definition. This source map could also be indexed,
  9638. * but doesn't have to be.
  9639. *
  9640. * Instead of the "map" field, it's also possible to have a "url" field
  9641. * specifying a URL to retrieve a source map from, but that's currently
  9642. * unsupported.
  9643. *
  9644. * Here's an example source map, taken from the source map spec[0], but
  9645. * modified to omit a section which uses the "url" field.
  9646. *
  9647. * {
  9648. * version : 3,
  9649. * file: "app.js",
  9650. * sections: [{
  9651. * offset: {line:100, column:10},
  9652. * map: {
  9653. * version : 3,
  9654. * file: "section.js",
  9655. * sources: ["foo.js", "bar.js"],
  9656. * names: ["src", "maps", "are", "fun"],
  9657. * mappings: "AAAA,E;;ABCDE;"
  9658. * }
  9659. * }],
  9660. * }
  9661. *
  9662. * The second parameter, if given, is a string whose value is the URL
  9663. * at which the source map was found. This URL is used to compute the
  9664. * sources array.
  9665. *
  9666. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  9667. */
  9668. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9669. var sourceMap = aSourceMap;
  9670. if (typeof aSourceMap === 'string') {
  9671. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  9672. }
  9673. var version = util$1.getArg(sourceMap, 'version');
  9674. var sections = util$1.getArg(sourceMap, 'sections');
  9675. if (version != this._version) {
  9676. throw new Error('Unsupported version: ' + version);
  9677. }
  9678. this._sources = new ArraySet();
  9679. this._names = new ArraySet();
  9680. var lastOffset = {
  9681. line: -1,
  9682. column: 0
  9683. };
  9684. this._sections = sections.map(function (s) {
  9685. if (s.url) {
  9686. // The url field will require support for asynchronicity.
  9687. // See https://github.com/mozilla/source-map/issues/16
  9688. throw new Error('Support for url field in sections not implemented.');
  9689. }
  9690. var offset = util$1.getArg(s, 'offset');
  9691. var offsetLine = util$1.getArg(offset, 'line');
  9692. var offsetColumn = util$1.getArg(offset, 'column');
  9693. if (offsetLine < lastOffset.line ||
  9694. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  9695. throw new Error('Section offsets must be ordered and non-overlapping.');
  9696. }
  9697. lastOffset = offset;
  9698. return {
  9699. generatedOffset: {
  9700. // The offset fields are 0-based, but we use 1-based indices when
  9701. // encoding/decoding from VLQ.
  9702. generatedLine: offsetLine + 1,
  9703. generatedColumn: offsetColumn + 1
  9704. },
  9705. consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL)
  9706. }
  9707. });
  9708. }
  9709. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  9710. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1;
  9711. /**
  9712. * The version of the source mapping spec that we are consuming.
  9713. */
  9714. IndexedSourceMapConsumer.prototype._version = 3;
  9715. /**
  9716. * The list of original sources.
  9717. */
  9718. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  9719. get: function () {
  9720. var sources = [];
  9721. for (var i = 0; i < this._sections.length; i++) {
  9722. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  9723. sources.push(this._sections[i].consumer.sources[j]);
  9724. }
  9725. }
  9726. return sources;
  9727. }
  9728. });
  9729. /**
  9730. * Returns the original source, line, and column information for the generated
  9731. * source's line and column positions provided. The only argument is an object
  9732. * with the following properties:
  9733. *
  9734. * - line: The line number in the generated source. The line number
  9735. * is 1-based.
  9736. * - column: The column number in the generated source. The column
  9737. * number is 0-based.
  9738. *
  9739. * and an object is returned with the following properties:
  9740. *
  9741. * - source: The original source file, or null.
  9742. * - line: The line number in the original source, or null. The
  9743. * line number is 1-based.
  9744. * - column: The column number in the original source, or null. The
  9745. * column number is 0-based.
  9746. * - name: The original identifier, or null.
  9747. */
  9748. IndexedSourceMapConsumer.prototype.originalPositionFor =
  9749. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  9750. var needle = {
  9751. generatedLine: util$1.getArg(aArgs, 'line'),
  9752. generatedColumn: util$1.getArg(aArgs, 'column')
  9753. };
  9754. // Find the section containing the generated position we're trying to map
  9755. // to an original position.
  9756. var sectionIndex = binarySearch.search(needle, this._sections,
  9757. function(needle, section) {
  9758. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  9759. if (cmp) {
  9760. return cmp;
  9761. }
  9762. return (needle.generatedColumn -
  9763. section.generatedOffset.generatedColumn);
  9764. });
  9765. var section = this._sections[sectionIndex];
  9766. if (!section) {
  9767. return {
  9768. source: null,
  9769. line: null,
  9770. column: null,
  9771. name: null
  9772. };
  9773. }
  9774. return section.consumer.originalPositionFor({
  9775. line: needle.generatedLine -
  9776. (section.generatedOffset.generatedLine - 1),
  9777. column: needle.generatedColumn -
  9778. (section.generatedOffset.generatedLine === needle.generatedLine
  9779. ? section.generatedOffset.generatedColumn - 1
  9780. : 0),
  9781. bias: aArgs.bias
  9782. });
  9783. };
  9784. /**
  9785. * Return true if we have the source content for every source in the source
  9786. * map, false otherwise.
  9787. */
  9788. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  9789. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  9790. return this._sections.every(function (s) {
  9791. return s.consumer.hasContentsOfAllSources();
  9792. });
  9793. };
  9794. /**
  9795. * Returns the original source content. The only argument is the url of the
  9796. * original source file. Returns null if no original source content is
  9797. * available.
  9798. */
  9799. IndexedSourceMapConsumer.prototype.sourceContentFor =
  9800. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9801. for (var i = 0; i < this._sections.length; i++) {
  9802. var section = this._sections[i];
  9803. var content = section.consumer.sourceContentFor(aSource, true);
  9804. if (content) {
  9805. return content;
  9806. }
  9807. }
  9808. if (nullOnMissing) {
  9809. return null;
  9810. }
  9811. else {
  9812. throw new Error('"' + aSource + '" is not in the SourceMap.');
  9813. }
  9814. };
  9815. /**
  9816. * Returns the generated line and column information for the original source,
  9817. * line, and column positions provided. The only argument is an object with
  9818. * the following properties:
  9819. *
  9820. * - source: The filename of the original source.
  9821. * - line: The line number in the original source. The line number
  9822. * is 1-based.
  9823. * - column: The column number in the original source. The column
  9824. * number is 0-based.
  9825. *
  9826. * and an object is returned with the following properties:
  9827. *
  9828. * - line: The line number in the generated source, or null. The
  9829. * line number is 1-based.
  9830. * - column: The column number in the generated source, or null.
  9831. * The column number is 0-based.
  9832. */
  9833. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  9834. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  9835. for (var i = 0; i < this._sections.length; i++) {
  9836. var section = this._sections[i];
  9837. // Only consider this section if the requested source is in the list of
  9838. // sources of the consumer.
  9839. if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) {
  9840. continue;
  9841. }
  9842. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  9843. if (generatedPosition) {
  9844. var ret = {
  9845. line: generatedPosition.line +
  9846. (section.generatedOffset.generatedLine - 1),
  9847. column: generatedPosition.column +
  9848. (section.generatedOffset.generatedLine === generatedPosition.line
  9849. ? section.generatedOffset.generatedColumn - 1
  9850. : 0)
  9851. };
  9852. return ret;
  9853. }
  9854. }
  9855. return {
  9856. line: null,
  9857. column: null
  9858. };
  9859. };
  9860. /**
  9861. * Parse the mappings in a string in to a data structure which we can easily
  9862. * query (the ordered arrays in the `this.__generatedMappings` and
  9863. * `this.__originalMappings` properties).
  9864. */
  9865. IndexedSourceMapConsumer.prototype._parseMappings =
  9866. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9867. this.__generatedMappings = [];
  9868. this.__originalMappings = [];
  9869. for (var i = 0; i < this._sections.length; i++) {
  9870. var section = this._sections[i];
  9871. var sectionMappings = section.consumer._generatedMappings;
  9872. for (var j = 0; j < sectionMappings.length; j++) {
  9873. var mapping = sectionMappings[j];
  9874. var source = section.consumer._sources.at(mapping.source);
  9875. source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  9876. this._sources.add(source);
  9877. source = this._sources.indexOf(source);
  9878. var name = null;
  9879. if (mapping.name) {
  9880. name = section.consumer._names.at(mapping.name);
  9881. this._names.add(name);
  9882. name = this._names.indexOf(name);
  9883. }
  9884. // The mappings coming from the consumer for the section have
  9885. // generated positions relative to the start of the section, so we
  9886. // need to offset them to be relative to the start of the concatenated
  9887. // generated file.
  9888. var adjustedMapping = {
  9889. source: source,
  9890. generatedLine: mapping.generatedLine +
  9891. (section.generatedOffset.generatedLine - 1),
  9892. generatedColumn: mapping.generatedColumn +
  9893. (section.generatedOffset.generatedLine === mapping.generatedLine
  9894. ? section.generatedOffset.generatedColumn - 1
  9895. : 0),
  9896. originalLine: mapping.originalLine,
  9897. originalColumn: mapping.originalColumn,
  9898. name: name
  9899. };
  9900. this.__generatedMappings.push(adjustedMapping);
  9901. if (typeof adjustedMapping.originalLine === 'number') {
  9902. this.__originalMappings.push(adjustedMapping);
  9903. }
  9904. }
  9905. }
  9906. quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  9907. quickSort(this.__originalMappings, util$1.compareByOriginalPositions);
  9908. };
  9909. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  9910. var sourceNode = {};
  9911. /* -*- Mode: js; js-indent-level: 2; -*- */
  9912. /*
  9913. * Copyright 2011 Mozilla Foundation and contributors
  9914. * Licensed under the New BSD license. See LICENSE or:
  9915. * http://opensource.org/licenses/BSD-3-Clause
  9916. */
  9917. var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
  9918. var util = util$5;
  9919. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  9920. // operating systems these days (capturing the result).
  9921. var REGEX_NEWLINE = /(\r?\n)/;
  9922. // Newline character code for charCodeAt() comparisons
  9923. var NEWLINE_CODE = 10;
  9924. // Private symbol for identifying `SourceNode`s when multiple versions of
  9925. // the source-map library are loaded. This MUST NOT CHANGE across
  9926. // versions!
  9927. var isSourceNode = "$$$isSourceNode$$$";
  9928. /**
  9929. * SourceNodes provide a way to abstract over interpolating/concatenating
  9930. * snippets of generated JavaScript source code while maintaining the line and
  9931. * column information associated with the original source code.
  9932. *
  9933. * @param aLine The original line number.
  9934. * @param aColumn The original column number.
  9935. * @param aSource The original source's filename.
  9936. * @param aChunks Optional. An array of strings which are snippets of
  9937. * generated JS, or other SourceNodes.
  9938. * @param aName The original identifier.
  9939. */
  9940. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  9941. this.children = [];
  9942. this.sourceContents = {};
  9943. this.line = aLine == null ? null : aLine;
  9944. this.column = aColumn == null ? null : aColumn;
  9945. this.source = aSource == null ? null : aSource;
  9946. this.name = aName == null ? null : aName;
  9947. this[isSourceNode] = true;
  9948. if (aChunks != null) this.add(aChunks);
  9949. }
  9950. /**
  9951. * Creates a SourceNode from generated code and a SourceMapConsumer.
  9952. *
  9953. * @param aGeneratedCode The generated code
  9954. * @param aSourceMapConsumer The SourceMap for the generated code
  9955. * @param aRelativePath Optional. The path that relative sources in the
  9956. * SourceMapConsumer should be relative to.
  9957. */
  9958. SourceNode.fromStringWithSourceMap =
  9959. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  9960. // The SourceNode we want to fill with the generated code
  9961. // and the SourceMap
  9962. var node = new SourceNode();
  9963. // All even indices of this array are one line of the generated code,
  9964. // while all odd indices are the newlines between two adjacent lines
  9965. // (since `REGEX_NEWLINE` captures its match).
  9966. // Processed fragments are accessed by calling `shiftNextLine`.
  9967. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  9968. var remainingLinesIndex = 0;
  9969. var shiftNextLine = function() {
  9970. var lineContents = getNextLine();
  9971. // The last line of a file might not have a newline.
  9972. var newLine = getNextLine() || "";
  9973. return lineContents + newLine;
  9974. function getNextLine() {
  9975. return remainingLinesIndex < remainingLines.length ?
  9976. remainingLines[remainingLinesIndex++] : undefined;
  9977. }
  9978. };
  9979. // We need to remember the position of "remainingLines"
  9980. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  9981. // The generate SourceNodes we need a code range.
  9982. // To extract it current and last mapping is used.
  9983. // Here we store the last mapping.
  9984. var lastMapping = null;
  9985. aSourceMapConsumer.eachMapping(function (mapping) {
  9986. if (lastMapping !== null) {
  9987. // We add the code from "lastMapping" to "mapping":
  9988. // First check if there is a new line in between.
  9989. if (lastGeneratedLine < mapping.generatedLine) {
  9990. // Associate first line with "lastMapping"
  9991. addMappingWithCode(lastMapping, shiftNextLine());
  9992. lastGeneratedLine++;
  9993. lastGeneratedColumn = 0;
  9994. // The remaining code is added without mapping
  9995. } else {
  9996. // There is no new line in between.
  9997. // Associate the code between "lastGeneratedColumn" and
  9998. // "mapping.generatedColumn" with "lastMapping"
  9999. var nextLine = remainingLines[remainingLinesIndex] || '';
  10000. var code = nextLine.substr(0, mapping.generatedColumn -
  10001. lastGeneratedColumn);
  10002. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10003. lastGeneratedColumn);
  10004. lastGeneratedColumn = mapping.generatedColumn;
  10005. addMappingWithCode(lastMapping, code);
  10006. // No more remaining code, continue
  10007. lastMapping = mapping;
  10008. return;
  10009. }
  10010. }
  10011. // We add the generated code until the first mapping
  10012. // to the SourceNode without any mapping.
  10013. // Each line is added as separate string.
  10014. while (lastGeneratedLine < mapping.generatedLine) {
  10015. node.add(shiftNextLine());
  10016. lastGeneratedLine++;
  10017. }
  10018. if (lastGeneratedColumn < mapping.generatedColumn) {
  10019. var nextLine = remainingLines[remainingLinesIndex] || '';
  10020. node.add(nextLine.substr(0, mapping.generatedColumn));
  10021. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10022. lastGeneratedColumn = mapping.generatedColumn;
  10023. }
  10024. lastMapping = mapping;
  10025. }, this);
  10026. // We have processed all mappings.
  10027. if (remainingLinesIndex < remainingLines.length) {
  10028. if (lastMapping) {
  10029. // Associate the remaining code in the current line with "lastMapping"
  10030. addMappingWithCode(lastMapping, shiftNextLine());
  10031. }
  10032. // and add the remaining lines without any mapping
  10033. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10034. }
  10035. // Copy sourcesContent into SourceNode
  10036. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10037. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10038. if (content != null) {
  10039. if (aRelativePath != null) {
  10040. sourceFile = util.join(aRelativePath, sourceFile);
  10041. }
  10042. node.setSourceContent(sourceFile, content);
  10043. }
  10044. });
  10045. return node;
  10046. function addMappingWithCode(mapping, code) {
  10047. if (mapping === null || mapping.source === undefined) {
  10048. node.add(code);
  10049. } else {
  10050. var source = aRelativePath
  10051. ? util.join(aRelativePath, mapping.source)
  10052. : mapping.source;
  10053. node.add(new SourceNode(mapping.originalLine,
  10054. mapping.originalColumn,
  10055. source,
  10056. code,
  10057. mapping.name));
  10058. }
  10059. }
  10060. };
  10061. /**
  10062. * Add a chunk of generated JS to this source node.
  10063. *
  10064. * @param aChunk A string snippet of generated JS code, another instance of
  10065. * SourceNode, or an array where each member is one of those things.
  10066. */
  10067. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10068. if (Array.isArray(aChunk)) {
  10069. aChunk.forEach(function (chunk) {
  10070. this.add(chunk);
  10071. }, this);
  10072. }
  10073. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10074. if (aChunk) {
  10075. this.children.push(aChunk);
  10076. }
  10077. }
  10078. else {
  10079. throw new TypeError(
  10080. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10081. );
  10082. }
  10083. return this;
  10084. };
  10085. /**
  10086. * Add a chunk of generated JS to the beginning of this source node.
  10087. *
  10088. * @param aChunk A string snippet of generated JS code, another instance of
  10089. * SourceNode, or an array where each member is one of those things.
  10090. */
  10091. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10092. if (Array.isArray(aChunk)) {
  10093. for (var i = aChunk.length-1; i >= 0; i--) {
  10094. this.prepend(aChunk[i]);
  10095. }
  10096. }
  10097. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10098. this.children.unshift(aChunk);
  10099. }
  10100. else {
  10101. throw new TypeError(
  10102. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10103. );
  10104. }
  10105. return this;
  10106. };
  10107. /**
  10108. * Walk over the tree of JS snippets in this node and its children. The
  10109. * walking function is called once for each snippet of JS and is passed that
  10110. * snippet and the its original associated source's line/column location.
  10111. *
  10112. * @param aFn The traversal function.
  10113. */
  10114. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10115. var chunk;
  10116. for (var i = 0, len = this.children.length; i < len; i++) {
  10117. chunk = this.children[i];
  10118. if (chunk[isSourceNode]) {
  10119. chunk.walk(aFn);
  10120. }
  10121. else {
  10122. if (chunk !== '') {
  10123. aFn(chunk, { source: this.source,
  10124. line: this.line,
  10125. column: this.column,
  10126. name: this.name });
  10127. }
  10128. }
  10129. }
  10130. };
  10131. /**
  10132. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10133. * each of `this.children`.
  10134. *
  10135. * @param aSep The separator.
  10136. */
  10137. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10138. var newChildren;
  10139. var i;
  10140. var len = this.children.length;
  10141. if (len > 0) {
  10142. newChildren = [];
  10143. for (i = 0; i < len-1; i++) {
  10144. newChildren.push(this.children[i]);
  10145. newChildren.push(aSep);
  10146. }
  10147. newChildren.push(this.children[i]);
  10148. this.children = newChildren;
  10149. }
  10150. return this;
  10151. };
  10152. /**
  10153. * Call String.prototype.replace on the very right-most source snippet. Useful
  10154. * for trimming whitespace from the end of a source node, etc.
  10155. *
  10156. * @param aPattern The pattern to replace.
  10157. * @param aReplacement The thing to replace the pattern with.
  10158. */
  10159. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10160. var lastChild = this.children[this.children.length - 1];
  10161. if (lastChild[isSourceNode]) {
  10162. lastChild.replaceRight(aPattern, aReplacement);
  10163. }
  10164. else if (typeof lastChild === 'string') {
  10165. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10166. }
  10167. else {
  10168. this.children.push(''.replace(aPattern, aReplacement));
  10169. }
  10170. return this;
  10171. };
  10172. /**
  10173. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10174. * in the sourcesContent field.
  10175. *
  10176. * @param aSourceFile The filename of the source file
  10177. * @param aSourceContent The content of the source file
  10178. */
  10179. SourceNode.prototype.setSourceContent =
  10180. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10181. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10182. };
  10183. /**
  10184. * Walk over the tree of SourceNodes. The walking function is called for each
  10185. * source file content and is passed the filename and source content.
  10186. *
  10187. * @param aFn The traversal function.
  10188. */
  10189. SourceNode.prototype.walkSourceContents =
  10190. function SourceNode_walkSourceContents(aFn) {
  10191. for (var i = 0, len = this.children.length; i < len; i++) {
  10192. if (this.children[i][isSourceNode]) {
  10193. this.children[i].walkSourceContents(aFn);
  10194. }
  10195. }
  10196. var sources = Object.keys(this.sourceContents);
  10197. for (var i = 0, len = sources.length; i < len; i++) {
  10198. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10199. }
  10200. };
  10201. /**
  10202. * Return the string representation of this source node. Walks over the tree
  10203. * and concatenates all the various snippets together to one string.
  10204. */
  10205. SourceNode.prototype.toString = function SourceNode_toString() {
  10206. var str = "";
  10207. this.walk(function (chunk) {
  10208. str += chunk;
  10209. });
  10210. return str;
  10211. };
  10212. /**
  10213. * Returns the string representation of this source node along with a source
  10214. * map.
  10215. */
  10216. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10217. var generated = {
  10218. code: "",
  10219. line: 1,
  10220. column: 0
  10221. };
  10222. var map = new SourceMapGenerator$1(aArgs);
  10223. var sourceMappingActive = false;
  10224. var lastOriginalSource = null;
  10225. var lastOriginalLine = null;
  10226. var lastOriginalColumn = null;
  10227. var lastOriginalName = null;
  10228. this.walk(function (chunk, original) {
  10229. generated.code += chunk;
  10230. if (original.source !== null
  10231. && original.line !== null
  10232. && original.column !== null) {
  10233. if(lastOriginalSource !== original.source
  10234. || lastOriginalLine !== original.line
  10235. || lastOriginalColumn !== original.column
  10236. || lastOriginalName !== original.name) {
  10237. map.addMapping({
  10238. source: original.source,
  10239. original: {
  10240. line: original.line,
  10241. column: original.column
  10242. },
  10243. generated: {
  10244. line: generated.line,
  10245. column: generated.column
  10246. },
  10247. name: original.name
  10248. });
  10249. }
  10250. lastOriginalSource = original.source;
  10251. lastOriginalLine = original.line;
  10252. lastOriginalColumn = original.column;
  10253. lastOriginalName = original.name;
  10254. sourceMappingActive = true;
  10255. } else if (sourceMappingActive) {
  10256. map.addMapping({
  10257. generated: {
  10258. line: generated.line,
  10259. column: generated.column
  10260. }
  10261. });
  10262. lastOriginalSource = null;
  10263. sourceMappingActive = false;
  10264. }
  10265. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10266. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10267. generated.line++;
  10268. generated.column = 0;
  10269. // Mappings end at eol
  10270. if (idx + 1 === length) {
  10271. lastOriginalSource = null;
  10272. sourceMappingActive = false;
  10273. } else if (sourceMappingActive) {
  10274. map.addMapping({
  10275. source: original.source,
  10276. original: {
  10277. line: original.line,
  10278. column: original.column
  10279. },
  10280. generated: {
  10281. line: generated.line,
  10282. column: generated.column
  10283. },
  10284. name: original.name
  10285. });
  10286. }
  10287. } else {
  10288. generated.column++;
  10289. }
  10290. }
  10291. });
  10292. this.walkSourceContents(function (sourceFile, sourceContent) {
  10293. map.setSourceContent(sourceFile, sourceContent);
  10294. });
  10295. return { code: generated.code, map: map };
  10296. };
  10297. sourceNode.SourceNode = SourceNode;
  10298. /*
  10299. * Copyright 2009-2011 Mozilla Foundation and contributors
  10300. * Licensed under the New BSD license. See LICENSE.txt or:
  10301. * http://opensource.org/licenses/BSD-3-Clause
  10302. */
  10303. sourceMap$1.SourceMapGenerator = sourceMapGenerator.SourceMapGenerator;
  10304. sourceMap$1.SourceMapConsumer = sourceMapConsumer.SourceMapConsumer;
  10305. sourceMap$1.SourceNode = sourceNode.SourceNode;
  10306. var sourceMap = sourceMap$1;
  10307. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10308. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10309. var mergeSourceMap = merge;
  10310. /**
  10311. * Merge old source map and new source map and return merged.
  10312. * If old or new source map value is falsy, return another one as it is.
  10313. *
  10314. * @param {object|string} [oldMap] old source map object
  10315. * @param {object|string} [newmap] new source map object
  10316. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10317. */
  10318. function merge(oldMap, newMap) {
  10319. if (!oldMap) return newMap
  10320. if (!newMap) return oldMap
  10321. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10322. var newMapConsumer = new SourceMapConsumer(newMap);
  10323. var mergedMapGenerator = new SourceMapGenerator();
  10324. // iterate on new map and overwrite original position of new map with one of old map
  10325. newMapConsumer.eachMapping(function(m) {
  10326. // pass when `originalLine` is null.
  10327. // It occurs in case that the node does not have origin in original code.
  10328. if (m.originalLine == null) return
  10329. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10330. line: m.originalLine,
  10331. column: m.originalColumn
  10332. });
  10333. if (origPosInOldMap.source == null) return
  10334. mergedMapGenerator.addMapping({
  10335. original: {
  10336. line: origPosInOldMap.line,
  10337. column: origPosInOldMap.column
  10338. },
  10339. generated: {
  10340. line: m.generatedLine,
  10341. column: m.generatedColumn
  10342. },
  10343. source: origPosInOldMap.source,
  10344. name: origPosInOldMap.name
  10345. });
  10346. });
  10347. var consumers = [oldMapConsumer, newMapConsumer];
  10348. consumers.forEach(function(consumer) {
  10349. consumer.sources.forEach(function(sourceFile) {
  10350. mergedMapGenerator._sources.add(sourceFile);
  10351. var sourceContent = consumer.sourceContentFor(sourceFile);
  10352. if (sourceContent != null) {
  10353. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10354. }
  10355. });
  10356. });
  10357. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10358. mergedMapGenerator._file = oldMap.file;
  10359. return JSON.parse(mergedMapGenerator.toString())
  10360. }
  10361. var merge$1 = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMap);
  10362. const scss = (source, map, options, load = require) => {
  10363. const nodeSass = load("sass");
  10364. const finalOptions = {
  10365. ...options,
  10366. data: getSource(source, options.filename, options.additionalData),
  10367. file: options.filename,
  10368. outFile: options.filename,
  10369. sourceMap: !!map
  10370. };
  10371. try {
  10372. const result = nodeSass.renderSync(finalOptions);
  10373. const dependencies = result.stats.includedFiles;
  10374. if (map) {
  10375. return {
  10376. code: result.css.toString(),
  10377. map: merge$1(map, JSON.parse(result.map.toString())),
  10378. errors: [],
  10379. dependencies
  10380. };
  10381. }
  10382. return { code: result.css.toString(), errors: [], dependencies };
  10383. } catch (e) {
  10384. return { code: "", errors: [e], dependencies: [] };
  10385. }
  10386. };
  10387. const sass = (source, map, options, load) => scss(
  10388. source,
  10389. map,
  10390. {
  10391. ...options,
  10392. indentedSyntax: true
  10393. },
  10394. load
  10395. );
  10396. const less = (source, map, options, load = require) => {
  10397. const nodeLess = load("less");
  10398. let result;
  10399. let error = null;
  10400. nodeLess.render(
  10401. getSource(source, options.filename, options.additionalData),
  10402. { ...options, syncImport: true },
  10403. (err, output) => {
  10404. error = err;
  10405. result = output;
  10406. }
  10407. );
  10408. if (error) return { code: "", errors: [error], dependencies: [] };
  10409. const dependencies = result.imports;
  10410. if (map) {
  10411. return {
  10412. code: result.css.toString(),
  10413. map: merge$1(map, result.map),
  10414. errors: [],
  10415. dependencies
  10416. };
  10417. }
  10418. return {
  10419. code: result.css.toString(),
  10420. errors: [],
  10421. dependencies
  10422. };
  10423. };
  10424. const styl = (source, map, options, load = require) => {
  10425. const nodeStylus = load("stylus");
  10426. try {
  10427. const ref = nodeStylus(source, options);
  10428. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10429. const result = ref.render();
  10430. const dependencies = ref.deps();
  10431. if (map) {
  10432. return {
  10433. code: result,
  10434. map: merge$1(map, ref.sourcemap),
  10435. errors: [],
  10436. dependencies
  10437. };
  10438. }
  10439. return { code: result, errors: [], dependencies };
  10440. } catch (e) {
  10441. return { code: "", errors: [e], dependencies: [] };
  10442. }
  10443. };
  10444. function getSource(source, filename, additionalData) {
  10445. if (!additionalData) return source;
  10446. if (shared.isFunction(additionalData)) {
  10447. return additionalData(source, filename);
  10448. }
  10449. return additionalData + source;
  10450. }
  10451. const processors = {
  10452. less,
  10453. sass,
  10454. scss,
  10455. styl,
  10456. stylus: styl
  10457. };
  10458. var build = {exports: {}};
  10459. var fs = {};
  10460. Object.defineProperty(fs, "__esModule", {
  10461. value: true
  10462. });
  10463. fs.getFileSystem = getFileSystem;
  10464. fs.setFileSystem = setFileSystem;
  10465. let fileSystem = {
  10466. readFile: () => {
  10467. throw Error("readFile not implemented");
  10468. },
  10469. writeFile: () => {
  10470. throw Error("writeFile not implemented");
  10471. }
  10472. };
  10473. function setFileSystem(fs) {
  10474. fileSystem.readFile = fs.readFile;
  10475. fileSystem.writeFile = fs.writeFile;
  10476. }
  10477. function getFileSystem() {
  10478. return fileSystem;
  10479. }
  10480. var pluginFactory = {};
  10481. var unquote$1 = {};
  10482. Object.defineProperty(unquote$1, "__esModule", {
  10483. value: true
  10484. });
  10485. unquote$1.default = unquote;
  10486. // copied from https://github.com/lakenen/node-unquote
  10487. const reg = /['"]/;
  10488. function unquote(str) {
  10489. if (!str) {
  10490. return "";
  10491. }
  10492. if (reg.test(str.charAt(0))) {
  10493. str = str.substr(1);
  10494. }
  10495. if (reg.test(str.charAt(str.length - 1))) {
  10496. str = str.substr(0, str.length - 1);
  10497. }
  10498. return str;
  10499. }
  10500. var Parser$1 = {};
  10501. const matchValueName = /[$]?[\w-]+/g;
  10502. const replaceValueSymbols$2 = (value, replacements) => {
  10503. let matches;
  10504. while ((matches = matchValueName.exec(value))) {
  10505. const replacement = replacements[matches[0]];
  10506. if (replacement) {
  10507. value =
  10508. value.slice(0, matches.index) +
  10509. replacement +
  10510. value.slice(matchValueName.lastIndex);
  10511. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10512. }
  10513. }
  10514. return value;
  10515. };
  10516. var replaceValueSymbols_1 = replaceValueSymbols$2;
  10517. const replaceValueSymbols$1 = replaceValueSymbols_1;
  10518. const replaceSymbols$1 = (css, replacements) => {
  10519. css.walk((node) => {
  10520. if (node.type === "decl" && node.value) {
  10521. node.value = replaceValueSymbols$1(node.value.toString(), replacements);
  10522. } else if (node.type === "rule" && node.selector) {
  10523. node.selector = replaceValueSymbols$1(
  10524. node.selector.toString(),
  10525. replacements
  10526. );
  10527. } else if (node.type === "atrule" && node.params) {
  10528. node.params = replaceValueSymbols$1(node.params.toString(), replacements);
  10529. }
  10530. });
  10531. };
  10532. var replaceSymbols_1 = replaceSymbols$1;
  10533. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10534. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10535. const getDeclsObject = (rule) => {
  10536. const object = {};
  10537. rule.walkDecls((decl) => {
  10538. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10539. object[before + decl.prop] = decl.value;
  10540. });
  10541. return object;
  10542. };
  10543. /**
  10544. *
  10545. * @param {string} css
  10546. * @param {boolean} removeRules
  10547. * @param {'auto' | 'rule' | 'at-rule'} mode
  10548. */
  10549. const extractICSS$2 = (css, removeRules = true, mode = "auto") => {
  10550. const icssImports = {};
  10551. const icssExports = {};
  10552. function addImports(node, path) {
  10553. const unquoted = path.replace(/'|"/g, "");
  10554. icssImports[unquoted] = Object.assign(
  10555. icssImports[unquoted] || {},
  10556. getDeclsObject(node)
  10557. );
  10558. if (removeRules) {
  10559. node.remove();
  10560. }
  10561. }
  10562. function addExports(node) {
  10563. Object.assign(icssExports, getDeclsObject(node));
  10564. if (removeRules) {
  10565. node.remove();
  10566. }
  10567. }
  10568. css.each((node) => {
  10569. if (node.type === "rule" && mode !== "at-rule") {
  10570. if (node.selector.slice(0, 7) === ":import") {
  10571. const matches = importPattern.exec(node.selector);
  10572. if (matches) {
  10573. addImports(node, matches[1]);
  10574. }
  10575. }
  10576. if (node.selector === ":export") {
  10577. addExports(node);
  10578. }
  10579. }
  10580. if (node.type === "atrule" && mode !== "rule") {
  10581. if (node.name === "icss-import") {
  10582. const matches = balancedQuotes.exec(node.params);
  10583. if (matches) {
  10584. addImports(node, matches[1]);
  10585. }
  10586. }
  10587. if (node.name === "icss-export") {
  10588. addExports(node);
  10589. }
  10590. }
  10591. });
  10592. return { icssImports, icssExports };
  10593. };
  10594. var extractICSS_1 = extractICSS$2;
  10595. const createImports = (imports, postcss, mode = "rule") => {
  10596. return Object.keys(imports).map((path) => {
  10597. const aliases = imports[path];
  10598. const declarations = Object.keys(aliases).map((key) =>
  10599. postcss.decl({
  10600. prop: key,
  10601. value: aliases[key],
  10602. raws: { before: "\n " },
  10603. })
  10604. );
  10605. const hasDeclarations = declarations.length > 0;
  10606. const rule =
  10607. mode === "rule"
  10608. ? postcss.rule({
  10609. selector: `:import('${path}')`,
  10610. raws: { after: hasDeclarations ? "\n" : "" },
  10611. })
  10612. : postcss.atRule({
  10613. name: "icss-import",
  10614. params: `'${path}'`,
  10615. raws: { after: hasDeclarations ? "\n" : "" },
  10616. });
  10617. if (hasDeclarations) {
  10618. rule.append(declarations);
  10619. }
  10620. return rule;
  10621. });
  10622. };
  10623. const createExports = (exports, postcss, mode = "rule") => {
  10624. const declarations = Object.keys(exports).map((key) =>
  10625. postcss.decl({
  10626. prop: key,
  10627. value: exports[key],
  10628. raws: { before: "\n " },
  10629. })
  10630. );
  10631. if (declarations.length === 0) {
  10632. return [];
  10633. }
  10634. const rule =
  10635. mode === "rule"
  10636. ? postcss.rule({
  10637. selector: `:export`,
  10638. raws: { after: "\n" },
  10639. })
  10640. : postcss.atRule({
  10641. name: "icss-export",
  10642. raws: { after: "\n" },
  10643. });
  10644. rule.append(declarations);
  10645. return [rule];
  10646. };
  10647. const createICSSRules$1 = (imports, exports, postcss, mode) => [
  10648. ...createImports(imports, postcss, mode),
  10649. ...createExports(exports, postcss, mode),
  10650. ];
  10651. var createICSSRules_1 = createICSSRules$1;
  10652. const replaceValueSymbols = replaceValueSymbols_1;
  10653. const replaceSymbols = replaceSymbols_1;
  10654. const extractICSS$1 = extractICSS_1;
  10655. const createICSSRules = createICSSRules_1;
  10656. var src$4 = {
  10657. replaceValueSymbols,
  10658. replaceSymbols,
  10659. extractICSS: extractICSS$1,
  10660. createICSSRules,
  10661. };
  10662. Object.defineProperty(Parser$1, "__esModule", {
  10663. value: true
  10664. });
  10665. Parser$1.default = void 0;
  10666. var _icssUtils = src$4;
  10667. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  10668. const importRegexp = /^:import\((.+)\)$/;
  10669. class Parser {
  10670. constructor(pathFetcher, trace) {
  10671. this.pathFetcher = pathFetcher;
  10672. this.plugin = this.plugin.bind(this);
  10673. this.exportTokens = {};
  10674. this.translations = {};
  10675. this.trace = trace;
  10676. }
  10677. plugin() {
  10678. const parser = this;
  10679. return {
  10680. postcssPlugin: "css-modules-parser",
  10681. async OnceExit(css) {
  10682. await Promise.all(parser.fetchAllImports(css));
  10683. parser.linkImportedSymbols(css);
  10684. return parser.extractExports(css);
  10685. }
  10686. };
  10687. }
  10688. fetchAllImports(css) {
  10689. let imports = [];
  10690. css.each(node => {
  10691. if (node.type == "rule" && node.selector.match(importRegexp)) {
  10692. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  10693. }
  10694. });
  10695. return imports;
  10696. }
  10697. linkImportedSymbols(css) {
  10698. (0, _icssUtils.replaceSymbols)(css, this.translations);
  10699. }
  10700. extractExports(css) {
  10701. css.each(node => {
  10702. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  10703. });
  10704. }
  10705. handleExport(exportNode) {
  10706. exportNode.each(decl => {
  10707. if (decl.type == "decl") {
  10708. Object.keys(this.translations).forEach(translation => {
  10709. decl.value = decl.value.replace(translation, this.translations[translation]);
  10710. });
  10711. this.exportTokens[decl.prop] = decl.value;
  10712. }
  10713. });
  10714. exportNode.remove();
  10715. }
  10716. async fetchImport(importNode, relativeTo, depNr) {
  10717. const file = importNode.selector.match(importRegexp)[1];
  10718. const depTrace = this.trace + String.fromCharCode(depNr);
  10719. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  10720. try {
  10721. importNode.each(decl => {
  10722. if (decl.type == "decl") {
  10723. this.translations[decl.prop] = exports[decl.value];
  10724. }
  10725. });
  10726. importNode.remove();
  10727. } catch (err) {
  10728. console.log(err);
  10729. }
  10730. }
  10731. }
  10732. Parser$1.default = Parser;
  10733. var saveJSON$1 = {};
  10734. Object.defineProperty(saveJSON$1, "__esModule", {
  10735. value: true
  10736. });
  10737. saveJSON$1.default = saveJSON;
  10738. var _fs$2 = fs;
  10739. function saveJSON(cssFile, json) {
  10740. return new Promise((resolve, reject) => {
  10741. const {
  10742. writeFile
  10743. } = (0, _fs$2.getFileSystem)();
  10744. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  10745. });
  10746. }
  10747. var localsConvention = {};
  10748. /**
  10749. * lodash (Custom Build) <https://lodash.com/>
  10750. * Build: `lodash modularize exports="npm" -o ./`
  10751. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  10752. * Released under MIT license <https://lodash.com/license>
  10753. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  10754. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  10755. */
  10756. /** Used as references for various `Number` constants. */
  10757. var INFINITY = 1 / 0;
  10758. /** `Object#toString` result references. */
  10759. var symbolTag = '[object Symbol]';
  10760. /** Used to match words composed of alphanumeric characters. */
  10761. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  10762. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  10763. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  10764. /** Used to compose unicode character classes. */
  10765. var rsAstralRange = '\\ud800-\\udfff',
  10766. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  10767. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  10768. rsDingbatRange = '\\u2700-\\u27bf',
  10769. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  10770. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  10771. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  10772. rsPunctuationRange = '\\u2000-\\u206f',
  10773. 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',
  10774. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  10775. rsVarRange = '\\ufe0e\\ufe0f',
  10776. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  10777. /** Used to compose unicode capture groups. */
  10778. var rsApos = "['\u2019]",
  10779. rsAstral = '[' + rsAstralRange + ']',
  10780. rsBreak = '[' + rsBreakRange + ']',
  10781. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  10782. rsDigits = '\\d+',
  10783. rsDingbat = '[' + rsDingbatRange + ']',
  10784. rsLower = '[' + rsLowerRange + ']',
  10785. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  10786. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  10787. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  10788. rsNonAstral = '[^' + rsAstralRange + ']',
  10789. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  10790. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  10791. rsUpper = '[' + rsUpperRange + ']',
  10792. rsZWJ = '\\u200d';
  10793. /** Used to compose unicode regexes. */
  10794. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  10795. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  10796. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  10797. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  10798. reOptMod = rsModifier + '?',
  10799. rsOptVar = '[' + rsVarRange + ']?',
  10800. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  10801. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  10802. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  10803. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  10804. /** Used to match apostrophes. */
  10805. var reApos = RegExp(rsApos, 'g');
  10806. /**
  10807. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  10808. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  10809. */
  10810. var reComboMark = RegExp(rsCombo, 'g');
  10811. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  10812. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  10813. /** Used to match complex or compound words. */
  10814. var reUnicodeWord = RegExp([
  10815. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  10816. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  10817. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  10818. rsUpper + '+' + rsOptUpperContr,
  10819. rsDigits,
  10820. rsEmoji
  10821. ].join('|'), 'g');
  10822. /** 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/). */
  10823. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  10824. /** Used to detect strings that need a more robust regexp to match words. */
  10825. 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 ]/;
  10826. /** Used to map Latin Unicode letters to basic Latin letters. */
  10827. var deburredLetters = {
  10828. // Latin-1 Supplement block.
  10829. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  10830. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  10831. '\xc7': 'C', '\xe7': 'c',
  10832. '\xd0': 'D', '\xf0': 'd',
  10833. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  10834. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  10835. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  10836. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  10837. '\xd1': 'N', '\xf1': 'n',
  10838. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  10839. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  10840. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  10841. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  10842. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  10843. '\xc6': 'Ae', '\xe6': 'ae',
  10844. '\xde': 'Th', '\xfe': 'th',
  10845. '\xdf': 'ss',
  10846. // Latin Extended-A block.
  10847. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  10848. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  10849. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  10850. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  10851. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  10852. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  10853. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  10854. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  10855. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  10856. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  10857. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  10858. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  10859. '\u0134': 'J', '\u0135': 'j',
  10860. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  10861. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  10862. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  10863. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  10864. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  10865. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  10866. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  10867. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  10868. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  10869. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  10870. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  10871. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  10872. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  10873. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  10874. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  10875. '\u0174': 'W', '\u0175': 'w',
  10876. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  10877. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  10878. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  10879. '\u0132': 'IJ', '\u0133': 'ij',
  10880. '\u0152': 'Oe', '\u0153': 'oe',
  10881. '\u0149': "'n", '\u017f': 'ss'
  10882. };
  10883. /** Detect free variable `global` from Node.js. */
  10884. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  10885. /** Detect free variable `self`. */
  10886. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  10887. /** Used as a reference to the global object. */
  10888. var root = freeGlobal || freeSelf || Function('return this')();
  10889. /**
  10890. * A specialized version of `_.reduce` for arrays without support for
  10891. * iteratee shorthands.
  10892. *
  10893. * @private
  10894. * @param {Array} [array] The array to iterate over.
  10895. * @param {Function} iteratee The function invoked per iteration.
  10896. * @param {*} [accumulator] The initial value.
  10897. * @param {boolean} [initAccum] Specify using the first element of `array` as
  10898. * the initial value.
  10899. * @returns {*} Returns the accumulated value.
  10900. */
  10901. function arrayReduce(array, iteratee, accumulator, initAccum) {
  10902. var index = -1,
  10903. length = array ? array.length : 0;
  10904. while (++index < length) {
  10905. accumulator = iteratee(accumulator, array[index], index, array);
  10906. }
  10907. return accumulator;
  10908. }
  10909. /**
  10910. * Converts an ASCII `string` to an array.
  10911. *
  10912. * @private
  10913. * @param {string} string The string to convert.
  10914. * @returns {Array} Returns the converted array.
  10915. */
  10916. function asciiToArray(string) {
  10917. return string.split('');
  10918. }
  10919. /**
  10920. * Splits an ASCII `string` into an array of its words.
  10921. *
  10922. * @private
  10923. * @param {string} The string to inspect.
  10924. * @returns {Array} Returns the words of `string`.
  10925. */
  10926. function asciiWords(string) {
  10927. return string.match(reAsciiWord) || [];
  10928. }
  10929. /**
  10930. * The base implementation of `_.propertyOf` without support for deep paths.
  10931. *
  10932. * @private
  10933. * @param {Object} object The object to query.
  10934. * @returns {Function} Returns the new accessor function.
  10935. */
  10936. function basePropertyOf(object) {
  10937. return function(key) {
  10938. return object == null ? undefined : object[key];
  10939. };
  10940. }
  10941. /**
  10942. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  10943. * letters to basic Latin letters.
  10944. *
  10945. * @private
  10946. * @param {string} letter The matched letter to deburr.
  10947. * @returns {string} Returns the deburred letter.
  10948. */
  10949. var deburrLetter = basePropertyOf(deburredLetters);
  10950. /**
  10951. * Checks if `string` contains Unicode symbols.
  10952. *
  10953. * @private
  10954. * @param {string} string The string to inspect.
  10955. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  10956. */
  10957. function hasUnicode(string) {
  10958. return reHasUnicode.test(string);
  10959. }
  10960. /**
  10961. * Checks if `string` contains a word composed of Unicode symbols.
  10962. *
  10963. * @private
  10964. * @param {string} string The string to inspect.
  10965. * @returns {boolean} Returns `true` if a word is found, else `false`.
  10966. */
  10967. function hasUnicodeWord(string) {
  10968. return reHasUnicodeWord.test(string);
  10969. }
  10970. /**
  10971. * Converts `string` to an array.
  10972. *
  10973. * @private
  10974. * @param {string} string The string to convert.
  10975. * @returns {Array} Returns the converted array.
  10976. */
  10977. function stringToArray(string) {
  10978. return hasUnicode(string)
  10979. ? unicodeToArray(string)
  10980. : asciiToArray(string);
  10981. }
  10982. /**
  10983. * Converts a Unicode `string` to an array.
  10984. *
  10985. * @private
  10986. * @param {string} string The string to convert.
  10987. * @returns {Array} Returns the converted array.
  10988. */
  10989. function unicodeToArray(string) {
  10990. return string.match(reUnicode) || [];
  10991. }
  10992. /**
  10993. * Splits a Unicode `string` into an array of its words.
  10994. *
  10995. * @private
  10996. * @param {string} The string to inspect.
  10997. * @returns {Array} Returns the words of `string`.
  10998. */
  10999. function unicodeWords(string) {
  11000. return string.match(reUnicodeWord) || [];
  11001. }
  11002. /** Used for built-in method references. */
  11003. var objectProto = Object.prototype;
  11004. /**
  11005. * Used to resolve the
  11006. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11007. * of values.
  11008. */
  11009. var objectToString = objectProto.toString;
  11010. /** Built-in value references. */
  11011. var Symbol$1 = root.Symbol;
  11012. /** Used to convert symbols to primitives and strings. */
  11013. var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
  11014. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11015. /**
  11016. * The base implementation of `_.slice` without an iteratee call guard.
  11017. *
  11018. * @private
  11019. * @param {Array} array The array to slice.
  11020. * @param {number} [start=0] The start position.
  11021. * @param {number} [end=array.length] The end position.
  11022. * @returns {Array} Returns the slice of `array`.
  11023. */
  11024. function baseSlice(array, start, end) {
  11025. var index = -1,
  11026. length = array.length;
  11027. if (start < 0) {
  11028. start = -start > length ? 0 : (length + start);
  11029. }
  11030. end = end > length ? length : end;
  11031. if (end < 0) {
  11032. end += length;
  11033. }
  11034. length = start > end ? 0 : ((end - start) >>> 0);
  11035. start >>>= 0;
  11036. var result = Array(length);
  11037. while (++index < length) {
  11038. result[index] = array[index + start];
  11039. }
  11040. return result;
  11041. }
  11042. /**
  11043. * The base implementation of `_.toString` which doesn't convert nullish
  11044. * values to empty strings.
  11045. *
  11046. * @private
  11047. * @param {*} value The value to process.
  11048. * @returns {string} Returns the string.
  11049. */
  11050. function baseToString(value) {
  11051. // Exit early for strings to avoid a performance hit in some environments.
  11052. if (typeof value == 'string') {
  11053. return value;
  11054. }
  11055. if (isSymbol(value)) {
  11056. return symbolToString ? symbolToString.call(value) : '';
  11057. }
  11058. var result = (value + '');
  11059. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  11060. }
  11061. /**
  11062. * Casts `array` to a slice if it's needed.
  11063. *
  11064. * @private
  11065. * @param {Array} array The array to inspect.
  11066. * @param {number} start The start position.
  11067. * @param {number} [end=array.length] The end position.
  11068. * @returns {Array} Returns the cast slice.
  11069. */
  11070. function castSlice(array, start, end) {
  11071. var length = array.length;
  11072. end = end === undefined ? length : end;
  11073. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11074. }
  11075. /**
  11076. * Creates a function like `_.lowerFirst`.
  11077. *
  11078. * @private
  11079. * @param {string} methodName The name of the `String` case method to use.
  11080. * @returns {Function} Returns the new case function.
  11081. */
  11082. function createCaseFirst(methodName) {
  11083. return function(string) {
  11084. string = toString(string);
  11085. var strSymbols = hasUnicode(string)
  11086. ? stringToArray(string)
  11087. : undefined;
  11088. var chr = strSymbols
  11089. ? strSymbols[0]
  11090. : string.charAt(0);
  11091. var trailing = strSymbols
  11092. ? castSlice(strSymbols, 1).join('')
  11093. : string.slice(1);
  11094. return chr[methodName]() + trailing;
  11095. };
  11096. }
  11097. /**
  11098. * Creates a function like `_.camelCase`.
  11099. *
  11100. * @private
  11101. * @param {Function} callback The function to combine each word.
  11102. * @returns {Function} Returns the new compounder function.
  11103. */
  11104. function createCompounder(callback) {
  11105. return function(string) {
  11106. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11107. };
  11108. }
  11109. /**
  11110. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11111. * and has a `typeof` result of "object".
  11112. *
  11113. * @static
  11114. * @memberOf _
  11115. * @since 4.0.0
  11116. * @category Lang
  11117. * @param {*} value The value to check.
  11118. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11119. * @example
  11120. *
  11121. * _.isObjectLike({});
  11122. * // => true
  11123. *
  11124. * _.isObjectLike([1, 2, 3]);
  11125. * // => true
  11126. *
  11127. * _.isObjectLike(_.noop);
  11128. * // => false
  11129. *
  11130. * _.isObjectLike(null);
  11131. * // => false
  11132. */
  11133. function isObjectLike(value) {
  11134. return !!value && typeof value == 'object';
  11135. }
  11136. /**
  11137. * Checks if `value` is classified as a `Symbol` primitive or object.
  11138. *
  11139. * @static
  11140. * @memberOf _
  11141. * @since 4.0.0
  11142. * @category Lang
  11143. * @param {*} value The value to check.
  11144. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11145. * @example
  11146. *
  11147. * _.isSymbol(Symbol.iterator);
  11148. * // => true
  11149. *
  11150. * _.isSymbol('abc');
  11151. * // => false
  11152. */
  11153. function isSymbol(value) {
  11154. return typeof value == 'symbol' ||
  11155. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11156. }
  11157. /**
  11158. * Converts `value` to a string. An empty string is returned for `null`
  11159. * and `undefined` values. The sign of `-0` is preserved.
  11160. *
  11161. * @static
  11162. * @memberOf _
  11163. * @since 4.0.0
  11164. * @category Lang
  11165. * @param {*} value The value to process.
  11166. * @returns {string} Returns the string.
  11167. * @example
  11168. *
  11169. * _.toString(null);
  11170. * // => ''
  11171. *
  11172. * _.toString(-0);
  11173. * // => '-0'
  11174. *
  11175. * _.toString([1, 2, 3]);
  11176. * // => '1,2,3'
  11177. */
  11178. function toString(value) {
  11179. return value == null ? '' : baseToString(value);
  11180. }
  11181. /**
  11182. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11183. *
  11184. * @static
  11185. * @memberOf _
  11186. * @since 3.0.0
  11187. * @category String
  11188. * @param {string} [string=''] The string to convert.
  11189. * @returns {string} Returns the camel cased string.
  11190. * @example
  11191. *
  11192. * _.camelCase('Foo Bar');
  11193. * // => 'fooBar'
  11194. *
  11195. * _.camelCase('--foo-bar--');
  11196. * // => 'fooBar'
  11197. *
  11198. * _.camelCase('__FOO_BAR__');
  11199. * // => 'fooBar'
  11200. */
  11201. var camelCase = createCompounder(function(result, word, index) {
  11202. word = word.toLowerCase();
  11203. return result + (index ? capitalize(word) : word);
  11204. });
  11205. /**
  11206. * Converts the first character of `string` to upper case and the remaining
  11207. * to lower case.
  11208. *
  11209. * @static
  11210. * @memberOf _
  11211. * @since 3.0.0
  11212. * @category String
  11213. * @param {string} [string=''] The string to capitalize.
  11214. * @returns {string} Returns the capitalized string.
  11215. * @example
  11216. *
  11217. * _.capitalize('FRED');
  11218. * // => 'Fred'
  11219. */
  11220. function capitalize(string) {
  11221. return upperFirst(toString(string).toLowerCase());
  11222. }
  11223. /**
  11224. * Deburrs `string` by converting
  11225. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11226. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11227. * letters to basic Latin letters and removing
  11228. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11229. *
  11230. * @static
  11231. * @memberOf _
  11232. * @since 3.0.0
  11233. * @category String
  11234. * @param {string} [string=''] The string to deburr.
  11235. * @returns {string} Returns the deburred string.
  11236. * @example
  11237. *
  11238. * _.deburr('déjà vu');
  11239. * // => 'deja vu'
  11240. */
  11241. function deburr(string) {
  11242. string = toString(string);
  11243. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11244. }
  11245. /**
  11246. * Converts the first character of `string` to upper case.
  11247. *
  11248. * @static
  11249. * @memberOf _
  11250. * @since 4.0.0
  11251. * @category String
  11252. * @param {string} [string=''] The string to convert.
  11253. * @returns {string} Returns the converted string.
  11254. * @example
  11255. *
  11256. * _.upperFirst('fred');
  11257. * // => 'Fred'
  11258. *
  11259. * _.upperFirst('FRED');
  11260. * // => 'FRED'
  11261. */
  11262. var upperFirst = createCaseFirst('toUpperCase');
  11263. /**
  11264. * Splits `string` into an array of its words.
  11265. *
  11266. * @static
  11267. * @memberOf _
  11268. * @since 3.0.0
  11269. * @category String
  11270. * @param {string} [string=''] The string to inspect.
  11271. * @param {RegExp|string} [pattern] The pattern to match words.
  11272. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11273. * @returns {Array} Returns the words of `string`.
  11274. * @example
  11275. *
  11276. * _.words('fred, barney, & pebbles');
  11277. * // => ['fred', 'barney', 'pebbles']
  11278. *
  11279. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11280. * // => ['fred', 'barney', '&', 'pebbles']
  11281. */
  11282. function words(string, pattern, guard) {
  11283. string = toString(string);
  11284. pattern = pattern;
  11285. if (pattern === undefined) {
  11286. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11287. }
  11288. return string.match(pattern) || [];
  11289. }
  11290. var lodash_camelcase = camelCase;
  11291. Object.defineProperty(localsConvention, "__esModule", {
  11292. value: true
  11293. });
  11294. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11295. var _lodash = _interopRequireDefault$3(lodash_camelcase);
  11296. function _interopRequireDefault$3(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11297. function dashesCamelCase(string) {
  11298. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11299. }
  11300. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11301. const isFunc = typeof localsConvention === "function";
  11302. return (tokens, [className, value]) => {
  11303. if (isFunc) {
  11304. const convention = localsConvention(className, value, inputFile);
  11305. tokens[convention] = value;
  11306. return tokens;
  11307. }
  11308. switch (localsConvention) {
  11309. case "camelCase":
  11310. tokens[className] = value;
  11311. tokens[(0, _lodash.default)(className)] = value;
  11312. break;
  11313. case "camelCaseOnly":
  11314. tokens[(0, _lodash.default)(className)] = value;
  11315. break;
  11316. case "dashes":
  11317. tokens[className] = value;
  11318. tokens[dashesCamelCase(className)] = value;
  11319. break;
  11320. case "dashesOnly":
  11321. tokens[dashesCamelCase(className)] = value;
  11322. break;
  11323. }
  11324. return tokens;
  11325. };
  11326. }
  11327. var FileSystemLoader$1 = {};
  11328. Object.defineProperty(FileSystemLoader$1, "__esModule", {
  11329. value: true
  11330. });
  11331. FileSystemLoader$1.default = void 0;
  11332. var _postcss$1 = _interopRequireDefault$2(require$$0$1);
  11333. var _path = _interopRequireDefault$2(path$3);
  11334. var _Parser$1 = _interopRequireDefault$2(Parser$1);
  11335. var _fs$1 = fs;
  11336. function _interopRequireDefault$2(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11337. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11338. class Core {
  11339. constructor(plugins) {
  11340. this.plugins = plugins || Core.defaultPlugins;
  11341. }
  11342. async load(sourceString, sourcePath, trace, pathFetcher) {
  11343. const parser = new _Parser$1.default(pathFetcher, trace);
  11344. const plugins = this.plugins.concat([parser.plugin()]);
  11345. const result = await (0, _postcss$1.default)(plugins).process(sourceString, {
  11346. from: sourcePath
  11347. });
  11348. return {
  11349. injectableSource: result.css,
  11350. exportTokens: parser.exportTokens
  11351. };
  11352. }
  11353. } // Sorts dependencies in the following way:
  11354. // AAA comes before AA and A
  11355. // AB comes after AA and before A
  11356. // All Bs come after all As
  11357. // This ensures that the files are always returned in the following order:
  11358. // - In the order they were required, except
  11359. // - After all their dependencies
  11360. const traceKeySorter = (a, b) => {
  11361. if (a.length < b.length) {
  11362. return a < b.substring(0, a.length) ? -1 : 1;
  11363. }
  11364. if (a.length > b.length) {
  11365. return a.substring(0, b.length) <= b ? -1 : 1;
  11366. }
  11367. return a < b ? -1 : 1;
  11368. };
  11369. class FileSystemLoader {
  11370. constructor(root, plugins, fileResolve) {
  11371. if (root === "/" && process.platform === "win32") {
  11372. const cwdDrive = process.cwd().slice(0, 3);
  11373. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11374. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11375. }
  11376. root = cwdDrive;
  11377. }
  11378. this.root = root;
  11379. this.fileResolve = fileResolve;
  11380. this.sources = {};
  11381. this.traces = {};
  11382. this.importNr = 0;
  11383. this.core = new Core(plugins);
  11384. this.tokensByFile = {};
  11385. this.fs = (0, _fs$1.getFileSystem)();
  11386. }
  11387. async fetch(_newPath, relativeTo, _trace) {
  11388. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11389. const trace = _trace || String.fromCharCode(this.importNr++);
  11390. const useFileResolve = typeof this.fileResolve === "function";
  11391. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11392. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11393. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11394. }
  11395. const relativeDir = _path.default.dirname(relativeTo);
  11396. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11397. 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
  11398. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11399. try {
  11400. fileRelativePath = require.resolve(newPath);
  11401. } catch (e) {// noop
  11402. }
  11403. }
  11404. const tokens = this.tokensByFile[fileRelativePath];
  11405. if (tokens) return tokens;
  11406. return new Promise((resolve, reject) => {
  11407. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11408. if (err) reject(err);
  11409. const {
  11410. injectableSource,
  11411. exportTokens
  11412. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11413. this.sources[fileRelativePath] = injectableSource;
  11414. this.traces[trace] = fileRelativePath;
  11415. this.tokensByFile[fileRelativePath] = exportTokens;
  11416. resolve(exportTokens);
  11417. });
  11418. });
  11419. }
  11420. get finalSource() {
  11421. const traces = this.traces;
  11422. const sources = this.sources;
  11423. let written = new Set();
  11424. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11425. const filename = traces[key];
  11426. if (written.has(filename)) {
  11427. return null;
  11428. }
  11429. written.add(filename);
  11430. return sources[filename];
  11431. }).join("");
  11432. }
  11433. }
  11434. FileSystemLoader$1.default = FileSystemLoader;
  11435. var scoping = {};
  11436. var src$3 = {exports: {}};
  11437. const PERMANENT_MARKER = 2;
  11438. const TEMPORARY_MARKER = 1;
  11439. function createError(node, graph) {
  11440. const er = new Error("Nondeterministic import's order");
  11441. const related = graph[node];
  11442. const relatedNode = related.find(
  11443. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11444. );
  11445. er.nodes = [node, relatedNode];
  11446. return er;
  11447. }
  11448. function walkGraph(node, graph, state, result, strict) {
  11449. if (state[node] === PERMANENT_MARKER) {
  11450. return;
  11451. }
  11452. if (state[node] === TEMPORARY_MARKER) {
  11453. if (strict) {
  11454. return createError(node, graph);
  11455. }
  11456. return;
  11457. }
  11458. state[node] = TEMPORARY_MARKER;
  11459. const children = graph[node];
  11460. const length = children.length;
  11461. for (let i = 0; i < length; ++i) {
  11462. const error = walkGraph(children[i], graph, state, result, strict);
  11463. if (error instanceof Error) {
  11464. return error;
  11465. }
  11466. }
  11467. state[node] = PERMANENT_MARKER;
  11468. result.push(node);
  11469. }
  11470. function topologicalSort$1(graph, strict) {
  11471. const result = [];
  11472. const state = {};
  11473. const nodes = Object.keys(graph);
  11474. const length = nodes.length;
  11475. for (let i = 0; i < length; ++i) {
  11476. const er = walkGraph(nodes[i], graph, state, result, strict);
  11477. if (er instanceof Error) {
  11478. return er;
  11479. }
  11480. }
  11481. return result;
  11482. }
  11483. var topologicalSort_1 = topologicalSort$1;
  11484. const topologicalSort = topologicalSort_1;
  11485. const matchImports$1 = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11486. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11487. const VISITED_MARKER = 1;
  11488. /**
  11489. * :import('G') {}
  11490. *
  11491. * Rule
  11492. * composes: ... from 'A'
  11493. * composes: ... from 'B'
  11494. * Rule
  11495. * composes: ... from 'A'
  11496. * composes: ... from 'A'
  11497. * composes: ... from 'C'
  11498. *
  11499. * Results in:
  11500. *
  11501. * graph: {
  11502. * G: [],
  11503. * A: [],
  11504. * B: ['A'],
  11505. * C: ['A'],
  11506. * }
  11507. */
  11508. function addImportToGraph(importId, parentId, graph, visited) {
  11509. const siblingsId = parentId + "_" + "siblings";
  11510. const visitedId = parentId + "_" + importId;
  11511. if (visited[visitedId] !== VISITED_MARKER) {
  11512. if (!Array.isArray(visited[siblingsId])) {
  11513. visited[siblingsId] = [];
  11514. }
  11515. const siblings = visited[siblingsId];
  11516. if (Array.isArray(graph[importId])) {
  11517. graph[importId] = graph[importId].concat(siblings);
  11518. } else {
  11519. graph[importId] = siblings.slice();
  11520. }
  11521. visited[visitedId] = VISITED_MARKER;
  11522. siblings.push(importId);
  11523. }
  11524. }
  11525. src$3.exports = (options = {}) => {
  11526. let importIndex = 0;
  11527. const createImportedName =
  11528. typeof options.createImportedName !== "function"
  11529. ? (importName /*, path*/) =>
  11530. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  11531. : options.createImportedName;
  11532. const failOnWrongOrder = options.failOnWrongOrder;
  11533. return {
  11534. postcssPlugin: "postcss-modules-extract-imports",
  11535. prepare() {
  11536. const graph = {};
  11537. const visited = {};
  11538. const existingImports = {};
  11539. const importDecls = {};
  11540. const imports = {};
  11541. return {
  11542. Once(root, postcss) {
  11543. // Check the existing imports order and save refs
  11544. root.walkRules((rule) => {
  11545. const matches = icssImport.exec(rule.selector);
  11546. if (matches) {
  11547. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  11548. const importPath = doubleQuotePath || singleQuotePath;
  11549. addImportToGraph(importPath, "root", graph, visited);
  11550. existingImports[importPath] = rule;
  11551. }
  11552. });
  11553. root.walkDecls(/^composes$/, (declaration) => {
  11554. const multiple = declaration.value.split(",");
  11555. const values = [];
  11556. multiple.forEach((value) => {
  11557. const matches = value.trim().match(matchImports$1);
  11558. if (!matches) {
  11559. values.push(value);
  11560. return;
  11561. }
  11562. let tmpSymbols;
  11563. let [
  11564. ,
  11565. /*match*/ symbols,
  11566. doubleQuotePath,
  11567. singleQuotePath,
  11568. global,
  11569. ] = matches;
  11570. if (global) {
  11571. // Composing globals simply means changing these classes to wrap them in global(name)
  11572. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  11573. } else {
  11574. const importPath = doubleQuotePath || singleQuotePath;
  11575. let parent = declaration.parent;
  11576. let parentIndexes = "";
  11577. while (parent.type !== "root") {
  11578. parentIndexes =
  11579. parent.parent.index(parent) + "_" + parentIndexes;
  11580. parent = parent.parent;
  11581. }
  11582. const { selector } = declaration.parent;
  11583. const parentRule = `_${parentIndexes}${selector}`;
  11584. addImportToGraph(importPath, parentRule, graph, visited);
  11585. importDecls[importPath] = declaration;
  11586. imports[importPath] = imports[importPath] || {};
  11587. tmpSymbols = symbols.split(/\s+/).map((s) => {
  11588. if (!imports[importPath][s]) {
  11589. imports[importPath][s] = createImportedName(s, importPath);
  11590. }
  11591. return imports[importPath][s];
  11592. });
  11593. }
  11594. values.push(tmpSymbols.join(" "));
  11595. });
  11596. declaration.value = values.join(", ");
  11597. });
  11598. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  11599. if (importsOrder instanceof Error) {
  11600. const importPath = importsOrder.nodes.find((importPath) =>
  11601. // eslint-disable-next-line no-prototype-builtins
  11602. importDecls.hasOwnProperty(importPath)
  11603. );
  11604. const decl = importDecls[importPath];
  11605. throw decl.error(
  11606. "Failed to resolve order of composed modules " +
  11607. importsOrder.nodes
  11608. .map((importPath) => "`" + importPath + "`")
  11609. .join(", ") +
  11610. ".",
  11611. {
  11612. plugin: "postcss-modules-extract-imports",
  11613. word: "composes",
  11614. }
  11615. );
  11616. }
  11617. let lastImportRule;
  11618. importsOrder.forEach((path) => {
  11619. const importedSymbols = imports[path];
  11620. let rule = existingImports[path];
  11621. if (!rule && importedSymbols) {
  11622. rule = postcss.rule({
  11623. selector: `:import("${path}")`,
  11624. raws: { after: "\n" },
  11625. });
  11626. if (lastImportRule) {
  11627. root.insertAfter(lastImportRule, rule);
  11628. } else {
  11629. root.prepend(rule);
  11630. }
  11631. }
  11632. lastImportRule = rule;
  11633. if (!importedSymbols) {
  11634. return;
  11635. }
  11636. Object.keys(importedSymbols).forEach((importedSymbol) => {
  11637. rule.append(
  11638. postcss.decl({
  11639. value: importedSymbol,
  11640. prop: importedSymbols[importedSymbol],
  11641. raws: { before: "\n " },
  11642. })
  11643. );
  11644. });
  11645. });
  11646. },
  11647. };
  11648. },
  11649. };
  11650. };
  11651. src$3.exports.postcss = true;
  11652. var srcExports$2 = src$3.exports;
  11653. var wasmHash = {exports: {}};
  11654. /*
  11655. MIT License http://www.opensource.org/licenses/mit-license.php
  11656. Author Tobias Koppers @sokra
  11657. */
  11658. var hasRequiredWasmHash;
  11659. function requireWasmHash () {
  11660. if (hasRequiredWasmHash) return wasmHash.exports;
  11661. hasRequiredWasmHash = 1;
  11662. // 65536 is the size of a wasm memory page
  11663. // 64 is the maximum chunk size for every possible wasm hash implementation
  11664. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  11665. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  11666. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
  11667. class WasmHash {
  11668. /**
  11669. * @param {WebAssembly.Instance} instance wasm instance
  11670. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  11671. * @param {number} chunkSize size of data chunks passed to wasm
  11672. * @param {number} digestSize size of digest returned by wasm
  11673. */
  11674. constructor(instance, instancesPool, chunkSize, digestSize) {
  11675. const exports = /** @type {any} */ (instance.exports);
  11676. exports.init();
  11677. this.exports = exports;
  11678. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  11679. this.buffered = 0;
  11680. this.instancesPool = instancesPool;
  11681. this.chunkSize = chunkSize;
  11682. this.digestSize = digestSize;
  11683. }
  11684. reset() {
  11685. this.buffered = 0;
  11686. this.exports.init();
  11687. }
  11688. /**
  11689. * @param {Buffer | string} data data
  11690. * @param {BufferEncoding=} encoding encoding
  11691. * @returns {this} itself
  11692. */
  11693. update(data, encoding) {
  11694. if (typeof data === "string") {
  11695. while (data.length > MAX_SHORT_STRING) {
  11696. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  11697. data = data.slice(MAX_SHORT_STRING);
  11698. }
  11699. this._updateWithShortString(data, encoding);
  11700. return this;
  11701. }
  11702. this._updateWithBuffer(data);
  11703. return this;
  11704. }
  11705. /**
  11706. * @param {string} data data
  11707. * @param {BufferEncoding=} encoding encoding
  11708. * @returns {void}
  11709. */
  11710. _updateWithShortString(data, encoding) {
  11711. const { exports, buffered, mem, chunkSize } = this;
  11712. let endPos;
  11713. if (data.length < 70) {
  11714. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  11715. endPos = buffered;
  11716. for (let i = 0; i < data.length; i++) {
  11717. const cc = data.charCodeAt(i);
  11718. if (cc < 0x80) {
  11719. mem[endPos++] = cc;
  11720. } else if (cc < 0x800) {
  11721. mem[endPos] = (cc >> 6) | 0xc0;
  11722. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  11723. endPos += 2;
  11724. } else {
  11725. // bail-out for weird chars
  11726. endPos += mem.write(data.slice(i), endPos, encoding);
  11727. break;
  11728. }
  11729. }
  11730. } else if (encoding === "latin1") {
  11731. endPos = buffered;
  11732. for (let i = 0; i < data.length; i++) {
  11733. const cc = data.charCodeAt(i);
  11734. mem[endPos++] = cc;
  11735. }
  11736. } else {
  11737. endPos = buffered + mem.write(data, buffered, encoding);
  11738. }
  11739. } else {
  11740. endPos = buffered + mem.write(data, buffered, encoding);
  11741. }
  11742. if (endPos < chunkSize) {
  11743. this.buffered = endPos;
  11744. } else {
  11745. const l = endPos & ~(this.chunkSize - 1);
  11746. exports.update(l);
  11747. const newBuffered = endPos - l;
  11748. this.buffered = newBuffered;
  11749. if (newBuffered > 0) {
  11750. mem.copyWithin(0, l, endPos);
  11751. }
  11752. }
  11753. }
  11754. /**
  11755. * @param {Buffer} data data
  11756. * @returns {void}
  11757. */
  11758. _updateWithBuffer(data) {
  11759. const { exports, buffered, mem } = this;
  11760. const length = data.length;
  11761. if (buffered + length < this.chunkSize) {
  11762. data.copy(mem, buffered, 0, length);
  11763. this.buffered += length;
  11764. } else {
  11765. const l = (buffered + length) & ~(this.chunkSize - 1);
  11766. if (l > 65536) {
  11767. let i = 65536 - buffered;
  11768. data.copy(mem, buffered, 0, i);
  11769. exports.update(65536);
  11770. const stop = l - buffered - 65536;
  11771. while (i < stop) {
  11772. data.copy(mem, 0, i, i + 65536);
  11773. exports.update(65536);
  11774. i += 65536;
  11775. }
  11776. data.copy(mem, 0, i, l - buffered);
  11777. exports.update(l - buffered - i);
  11778. } else {
  11779. data.copy(mem, buffered, 0, l - buffered);
  11780. exports.update(l);
  11781. }
  11782. const newBuffered = length + buffered - l;
  11783. this.buffered = newBuffered;
  11784. if (newBuffered > 0) {
  11785. data.copy(mem, 0, length - newBuffered, length);
  11786. }
  11787. }
  11788. }
  11789. digest(type) {
  11790. const { exports, buffered, mem, digestSize } = this;
  11791. exports.final(buffered);
  11792. this.instancesPool.push(this);
  11793. const hex = mem.toString("latin1", 0, digestSize);
  11794. if (type === "hex") {
  11795. return hex;
  11796. }
  11797. if (type === "binary" || !type) {
  11798. return Buffer.from(hex, "hex");
  11799. }
  11800. return Buffer.from(hex, "hex").toString(type);
  11801. }
  11802. }
  11803. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  11804. if (instancesPool.length > 0) {
  11805. const old = instancesPool.pop();
  11806. old.reset();
  11807. return old;
  11808. } else {
  11809. return new WasmHash(
  11810. new WebAssembly.Instance(wasmModule),
  11811. instancesPool,
  11812. chunkSize,
  11813. digestSize
  11814. );
  11815. }
  11816. };
  11817. wasmHash.exports = create;
  11818. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  11819. return wasmHash.exports;
  11820. }
  11821. /*
  11822. MIT License http://www.opensource.org/licenses/mit-license.php
  11823. Author Tobias Koppers @sokra
  11824. */
  11825. var xxhash64_1;
  11826. var hasRequiredXxhash64;
  11827. function requireXxhash64 () {
  11828. if (hasRequiredXxhash64) return xxhash64_1;
  11829. hasRequiredXxhash64 = 1;
  11830. const create = requireWasmHash();
  11831. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  11832. const xxhash64 = new WebAssembly.Module(
  11833. Buffer.from(
  11834. // 1173 bytes
  11835. "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",
  11836. "base64"
  11837. )
  11838. );
  11839. //#endregion
  11840. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  11841. return xxhash64_1;
  11842. }
  11843. var BatchedHash_1;
  11844. var hasRequiredBatchedHash;
  11845. function requireBatchedHash () {
  11846. if (hasRequiredBatchedHash) return BatchedHash_1;
  11847. hasRequiredBatchedHash = 1;
  11848. const MAX_SHORT_STRING = requireWasmHash().MAX_SHORT_STRING;
  11849. class BatchedHash {
  11850. constructor(hash) {
  11851. this.string = undefined;
  11852. this.encoding = undefined;
  11853. this.hash = hash;
  11854. }
  11855. /**
  11856. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  11857. * @param {string|Buffer} data data
  11858. * @param {string=} inputEncoding data encoding
  11859. * @returns {this} updated hash
  11860. */
  11861. update(data, inputEncoding) {
  11862. if (this.string !== undefined) {
  11863. if (
  11864. typeof data === "string" &&
  11865. inputEncoding === this.encoding &&
  11866. this.string.length + data.length < MAX_SHORT_STRING
  11867. ) {
  11868. this.string += data;
  11869. return this;
  11870. }
  11871. this.hash.update(this.string, this.encoding);
  11872. this.string = undefined;
  11873. }
  11874. if (typeof data === "string") {
  11875. if (
  11876. data.length < MAX_SHORT_STRING &&
  11877. // base64 encoding is not valid since it may contain padding chars
  11878. (!inputEncoding || !inputEncoding.startsWith("ba"))
  11879. ) {
  11880. this.string = data;
  11881. this.encoding = inputEncoding;
  11882. } else {
  11883. this.hash.update(data, inputEncoding);
  11884. }
  11885. } else {
  11886. this.hash.update(data);
  11887. }
  11888. return this;
  11889. }
  11890. /**
  11891. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  11892. * @param {string=} encoding encoding of the return value
  11893. * @returns {string|Buffer} digest
  11894. */
  11895. digest(encoding) {
  11896. if (this.string !== undefined) {
  11897. this.hash.update(this.string, this.encoding);
  11898. }
  11899. return this.hash.digest(encoding);
  11900. }
  11901. }
  11902. BatchedHash_1 = BatchedHash;
  11903. return BatchedHash_1;
  11904. }
  11905. /*
  11906. MIT License http://www.opensource.org/licenses/mit-license.php
  11907. Author Tobias Koppers @sokra
  11908. */
  11909. var md4_1;
  11910. var hasRequiredMd4;
  11911. function requireMd4 () {
  11912. if (hasRequiredMd4) return md4_1;
  11913. hasRequiredMd4 = 1;
  11914. const create = requireWasmHash();
  11915. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  11916. const md4 = new WebAssembly.Module(
  11917. Buffer.from(
  11918. // 2150 bytes
  11919. "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=",
  11920. "base64"
  11921. )
  11922. );
  11923. //#endregion
  11924. md4_1 = create.bind(null, md4, [], 64, 32);
  11925. return md4_1;
  11926. }
  11927. var BulkUpdateDecorator_1;
  11928. var hasRequiredBulkUpdateDecorator;
  11929. function requireBulkUpdateDecorator () {
  11930. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  11931. hasRequiredBulkUpdateDecorator = 1;
  11932. const BULK_SIZE = 2000;
  11933. // We are using an object instead of a Map as this will stay static during the runtime
  11934. // so access to it can be optimized by v8
  11935. const digestCaches = {};
  11936. class BulkUpdateDecorator {
  11937. /**
  11938. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  11939. * @param {string=} hashKey key for caching
  11940. */
  11941. constructor(hashOrFactory, hashKey) {
  11942. this.hashKey = hashKey;
  11943. if (typeof hashOrFactory === "function") {
  11944. this.hashFactory = hashOrFactory;
  11945. this.hash = undefined;
  11946. } else {
  11947. this.hashFactory = undefined;
  11948. this.hash = hashOrFactory;
  11949. }
  11950. this.buffer = "";
  11951. }
  11952. /**
  11953. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  11954. * @param {string|Buffer} data data
  11955. * @param {string=} inputEncoding data encoding
  11956. * @returns {this} updated hash
  11957. */
  11958. update(data, inputEncoding) {
  11959. if (
  11960. inputEncoding !== undefined ||
  11961. typeof data !== "string" ||
  11962. data.length > BULK_SIZE
  11963. ) {
  11964. if (this.hash === undefined) {
  11965. this.hash = this.hashFactory();
  11966. }
  11967. if (this.buffer.length > 0) {
  11968. this.hash.update(this.buffer);
  11969. this.buffer = "";
  11970. }
  11971. this.hash.update(data, inputEncoding);
  11972. } else {
  11973. this.buffer += data;
  11974. if (this.buffer.length > BULK_SIZE) {
  11975. if (this.hash === undefined) {
  11976. this.hash = this.hashFactory();
  11977. }
  11978. this.hash.update(this.buffer);
  11979. this.buffer = "";
  11980. }
  11981. }
  11982. return this;
  11983. }
  11984. /**
  11985. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  11986. * @param {string=} encoding encoding of the return value
  11987. * @returns {string|Buffer} digest
  11988. */
  11989. digest(encoding) {
  11990. let digestCache;
  11991. const buffer = this.buffer;
  11992. if (this.hash === undefined) {
  11993. // short data for hash, we can use caching
  11994. const cacheKey = `${this.hashKey}-${encoding}`;
  11995. digestCache = digestCaches[cacheKey];
  11996. if (digestCache === undefined) {
  11997. digestCache = digestCaches[cacheKey] = new Map();
  11998. }
  11999. const cacheEntry = digestCache.get(buffer);
  12000. if (cacheEntry !== undefined) {
  12001. return cacheEntry;
  12002. }
  12003. this.hash = this.hashFactory();
  12004. }
  12005. if (buffer.length > 0) {
  12006. this.hash.update(buffer);
  12007. }
  12008. const digestResult = this.hash.digest(encoding);
  12009. if (digestCache !== undefined) {
  12010. digestCache.set(buffer, digestResult);
  12011. }
  12012. return digestResult;
  12013. }
  12014. }
  12015. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12016. return BulkUpdateDecorator_1;
  12017. }
  12018. const baseEncodeTables = {
  12019. 26: "abcdefghijklmnopqrstuvwxyz",
  12020. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12021. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12022. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12023. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12024. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12025. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12026. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12027. };
  12028. /**
  12029. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12030. * @param {number} divisor The divisor
  12031. * @return {number} Modulo (remainder) of the division
  12032. */
  12033. function divmod32(uint32Array, divisor) {
  12034. let carry = 0;
  12035. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12036. const value = carry * 0x100000000 + uint32Array[i];
  12037. carry = value % divisor;
  12038. uint32Array[i] = Math.floor(value / divisor);
  12039. }
  12040. return carry;
  12041. }
  12042. function encodeBufferToBase(buffer, base, length) {
  12043. const encodeTable = baseEncodeTables[base];
  12044. if (!encodeTable) {
  12045. throw new Error("Unknown encoding base" + base);
  12046. }
  12047. // Input bits are only enough to generate this many characters
  12048. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12049. length = Math.min(length, limit);
  12050. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12051. // Fewer numbers in the array means faster math.
  12052. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12053. // Make sure the input buffer data is copied and is not mutated by reference.
  12054. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12055. buffer.copy(Buffer.from(uint32Array.buffer));
  12056. let output = "";
  12057. for (let i = 0; i < length; i++) {
  12058. output = encodeTable[divmod32(uint32Array, base)] + output;
  12059. }
  12060. return output;
  12061. }
  12062. let crypto = undefined;
  12063. let createXXHash64 = undefined;
  12064. let createMd4 = undefined;
  12065. let BatchedHash = undefined;
  12066. let BulkUpdateDecorator = undefined;
  12067. function getHashDigest$1(buffer, algorithm, digestType, maxLength) {
  12068. algorithm = algorithm || "xxhash64";
  12069. maxLength = maxLength || 9999;
  12070. let hash;
  12071. if (algorithm === "xxhash64") {
  12072. if (createXXHash64 === undefined) {
  12073. createXXHash64 = requireXxhash64();
  12074. if (BatchedHash === undefined) {
  12075. BatchedHash = requireBatchedHash();
  12076. }
  12077. }
  12078. hash = new BatchedHash(createXXHash64());
  12079. } else if (algorithm === "md4") {
  12080. if (createMd4 === undefined) {
  12081. createMd4 = requireMd4();
  12082. if (BatchedHash === undefined) {
  12083. BatchedHash = requireBatchedHash();
  12084. }
  12085. }
  12086. hash = new BatchedHash(createMd4());
  12087. } else if (algorithm === "native-md4") {
  12088. if (typeof crypto === "undefined") {
  12089. crypto = require("crypto");
  12090. if (BulkUpdateDecorator === undefined) {
  12091. BulkUpdateDecorator = requireBulkUpdateDecorator();
  12092. }
  12093. }
  12094. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12095. } else {
  12096. if (typeof crypto === "undefined") {
  12097. crypto = require("crypto");
  12098. if (BulkUpdateDecorator === undefined) {
  12099. BulkUpdateDecorator = requireBulkUpdateDecorator();
  12100. }
  12101. }
  12102. hash = new BulkUpdateDecorator(
  12103. () => crypto.createHash(algorithm),
  12104. algorithm
  12105. );
  12106. }
  12107. hash.update(buffer);
  12108. if (
  12109. digestType === "base26" ||
  12110. digestType === "base32" ||
  12111. digestType === "base36" ||
  12112. digestType === "base49" ||
  12113. digestType === "base52" ||
  12114. digestType === "base58" ||
  12115. digestType === "base62" ||
  12116. digestType === "base64safe"
  12117. ) {
  12118. return encodeBufferToBase(
  12119. hash.digest(),
  12120. digestType === "base64safe" ? 64 : digestType.substr(4),
  12121. maxLength
  12122. );
  12123. }
  12124. return hash.digest(digestType || "hex").substr(0, maxLength);
  12125. }
  12126. var getHashDigest_1 = getHashDigest$1;
  12127. const path$2 = path$3;
  12128. const getHashDigest = getHashDigest_1;
  12129. function interpolateName$1(loaderContext, name, options = {}) {
  12130. let filename;
  12131. const hasQuery =
  12132. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12133. if (typeof name === "function") {
  12134. filename = name(
  12135. loaderContext.resourcePath,
  12136. hasQuery ? loaderContext.resourceQuery : undefined
  12137. );
  12138. } else {
  12139. filename = name || "[hash].[ext]";
  12140. }
  12141. const context = options.context;
  12142. const content = options.content;
  12143. const regExp = options.regExp;
  12144. let ext = "bin";
  12145. let basename = "file";
  12146. let directory = "";
  12147. let folder = "";
  12148. let query = "";
  12149. if (loaderContext.resourcePath) {
  12150. const parsed = path$2.parse(loaderContext.resourcePath);
  12151. let resourcePath = loaderContext.resourcePath;
  12152. if (parsed.ext) {
  12153. ext = parsed.ext.substr(1);
  12154. }
  12155. if (parsed.dir) {
  12156. basename = parsed.name;
  12157. resourcePath = parsed.dir + path$2.sep;
  12158. }
  12159. if (typeof context !== "undefined") {
  12160. directory = path$2
  12161. .relative(context, resourcePath + "_")
  12162. .replace(/\\/g, "/")
  12163. .replace(/\.\.(\/)?/g, "_$1");
  12164. directory = directory.substr(0, directory.length - 1);
  12165. } else {
  12166. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12167. }
  12168. if (directory.length <= 1) {
  12169. directory = "";
  12170. } else {
  12171. // directory.length > 1
  12172. folder = path$2.basename(directory);
  12173. }
  12174. }
  12175. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12176. query = loaderContext.resourceQuery;
  12177. const hashIdx = query.indexOf("#");
  12178. if (hashIdx >= 0) {
  12179. query = query.substr(0, hashIdx);
  12180. }
  12181. }
  12182. let url = filename;
  12183. if (content) {
  12184. // Match hash template
  12185. url = url
  12186. // `hash` and `contenthash` are same in `loader-utils` context
  12187. // let's keep `hash` for backward compatibility
  12188. .replace(
  12189. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12190. (all, hashType, digestType, maxLength) =>
  12191. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12192. );
  12193. }
  12194. url = url
  12195. .replace(/\[ext\]/gi, () => ext)
  12196. .replace(/\[name\]/gi, () => basename)
  12197. .replace(/\[path\]/gi, () => directory)
  12198. .replace(/\[folder\]/gi, () => folder)
  12199. .replace(/\[query\]/gi, () => query);
  12200. if (regExp && loaderContext.resourcePath) {
  12201. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12202. match &&
  12203. match.forEach((matched, i) => {
  12204. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12205. });
  12206. }
  12207. if (
  12208. typeof loaderContext.options === "object" &&
  12209. typeof loaderContext.options.customInterpolateName === "function"
  12210. ) {
  12211. url = loaderContext.options.customInterpolateName.call(
  12212. loaderContext,
  12213. url,
  12214. name,
  12215. options
  12216. );
  12217. }
  12218. return url;
  12219. }
  12220. var interpolateName_1 = interpolateName$1;
  12221. var interpolateName = interpolateName_1;
  12222. var path$1 = path$3;
  12223. /**
  12224. * @param {string} pattern
  12225. * @param {object} options
  12226. * @param {string} options.context
  12227. * @param {string} options.hashPrefix
  12228. * @return {function}
  12229. */
  12230. var genericNames = function createGenerator(pattern, options) {
  12231. options = options || {};
  12232. var context =
  12233. options && typeof options.context === "string"
  12234. ? options.context
  12235. : process.cwd();
  12236. var hashPrefix =
  12237. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12238. /**
  12239. * @param {string} localName Usually a class name
  12240. * @param {string} filepath Absolute path
  12241. * @return {string}
  12242. */
  12243. return function generate(localName, filepath) {
  12244. var name = pattern.replace(/\[local\]/gi, localName);
  12245. var loaderContext = {
  12246. resourcePath: filepath,
  12247. };
  12248. var loaderOptions = {
  12249. content:
  12250. hashPrefix +
  12251. path$1.relative(context, filepath).replace(/\\/g, "/") +
  12252. "\x00" +
  12253. localName,
  12254. context: context,
  12255. };
  12256. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12257. return genericName
  12258. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12259. .replace(/^((-?[0-9])|--)/, "_$1");
  12260. };
  12261. };
  12262. var src$2 = {exports: {}};
  12263. var openParentheses = "(".charCodeAt(0);
  12264. var closeParentheses = ")".charCodeAt(0);
  12265. var singleQuote = "'".charCodeAt(0);
  12266. var doubleQuote = '"'.charCodeAt(0);
  12267. var backslash = "\\".charCodeAt(0);
  12268. var slash = "/".charCodeAt(0);
  12269. var comma = ",".charCodeAt(0);
  12270. var colon = ":".charCodeAt(0);
  12271. var star$2 = "*".charCodeAt(0);
  12272. var uLower = "u".charCodeAt(0);
  12273. var uUpper = "U".charCodeAt(0);
  12274. var plus = "+".charCodeAt(0);
  12275. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  12276. var parse$1 = function(input) {
  12277. var tokens = [];
  12278. var value = input;
  12279. var next,
  12280. quote,
  12281. prev,
  12282. token,
  12283. escape,
  12284. escapePos,
  12285. whitespacePos,
  12286. parenthesesOpenPos;
  12287. var pos = 0;
  12288. var code = value.charCodeAt(pos);
  12289. var max = value.length;
  12290. var stack = [{ nodes: tokens }];
  12291. var balanced = 0;
  12292. var parent;
  12293. var name = "";
  12294. var before = "";
  12295. var after = "";
  12296. while (pos < max) {
  12297. // Whitespaces
  12298. if (code <= 32) {
  12299. next = pos;
  12300. do {
  12301. next += 1;
  12302. code = value.charCodeAt(next);
  12303. } while (code <= 32);
  12304. token = value.slice(pos, next);
  12305. prev = tokens[tokens.length - 1];
  12306. if (code === closeParentheses && balanced) {
  12307. after = token;
  12308. } else if (prev && prev.type === "div") {
  12309. prev.after = token;
  12310. prev.sourceEndIndex += token.length;
  12311. } else if (
  12312. code === comma ||
  12313. code === colon ||
  12314. (code === slash &&
  12315. value.charCodeAt(next + 1) !== star$2 &&
  12316. (!parent ||
  12317. (parent && parent.type === "function" && parent.value !== "calc")))
  12318. ) {
  12319. before = token;
  12320. } else {
  12321. tokens.push({
  12322. type: "space",
  12323. sourceIndex: pos,
  12324. sourceEndIndex: next,
  12325. value: token
  12326. });
  12327. }
  12328. pos = next;
  12329. // Quotes
  12330. } else if (code === singleQuote || code === doubleQuote) {
  12331. next = pos;
  12332. quote = code === singleQuote ? "'" : '"';
  12333. token = {
  12334. type: "string",
  12335. sourceIndex: pos,
  12336. quote: quote
  12337. };
  12338. do {
  12339. escape = false;
  12340. next = value.indexOf(quote, next + 1);
  12341. if (~next) {
  12342. escapePos = next;
  12343. while (value.charCodeAt(escapePos - 1) === backslash) {
  12344. escapePos -= 1;
  12345. escape = !escape;
  12346. }
  12347. } else {
  12348. value += quote;
  12349. next = value.length - 1;
  12350. token.unclosed = true;
  12351. }
  12352. } while (escape);
  12353. token.value = value.slice(pos + 1, next);
  12354. token.sourceEndIndex = token.unclosed ? next : next + 1;
  12355. tokens.push(token);
  12356. pos = next + 1;
  12357. code = value.charCodeAt(pos);
  12358. // Comments
  12359. } else if (code === slash && value.charCodeAt(pos + 1) === star$2) {
  12360. next = value.indexOf("*/", pos);
  12361. token = {
  12362. type: "comment",
  12363. sourceIndex: pos,
  12364. sourceEndIndex: next + 2
  12365. };
  12366. if (next === -1) {
  12367. token.unclosed = true;
  12368. next = value.length;
  12369. token.sourceEndIndex = next;
  12370. }
  12371. token.value = value.slice(pos + 2, next);
  12372. tokens.push(token);
  12373. pos = next + 2;
  12374. code = value.charCodeAt(pos);
  12375. // Operation within calc
  12376. } else if (
  12377. (code === slash || code === star$2) &&
  12378. parent &&
  12379. parent.type === "function" &&
  12380. parent.value === "calc"
  12381. ) {
  12382. token = value[pos];
  12383. tokens.push({
  12384. type: "word",
  12385. sourceIndex: pos - before.length,
  12386. sourceEndIndex: pos + token.length,
  12387. value: token
  12388. });
  12389. pos += 1;
  12390. code = value.charCodeAt(pos);
  12391. // Dividers
  12392. } else if (code === slash || code === comma || code === colon) {
  12393. token = value[pos];
  12394. tokens.push({
  12395. type: "div",
  12396. sourceIndex: pos - before.length,
  12397. sourceEndIndex: pos + token.length,
  12398. value: token,
  12399. before: before,
  12400. after: ""
  12401. });
  12402. before = "";
  12403. pos += 1;
  12404. code = value.charCodeAt(pos);
  12405. // Open parentheses
  12406. } else if (openParentheses === code) {
  12407. // Whitespaces after open parentheses
  12408. next = pos;
  12409. do {
  12410. next += 1;
  12411. code = value.charCodeAt(next);
  12412. } while (code <= 32);
  12413. parenthesesOpenPos = pos;
  12414. token = {
  12415. type: "function",
  12416. sourceIndex: pos - name.length,
  12417. value: name,
  12418. before: value.slice(parenthesesOpenPos + 1, next)
  12419. };
  12420. pos = next;
  12421. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  12422. next -= 1;
  12423. do {
  12424. escape = false;
  12425. next = value.indexOf(")", next + 1);
  12426. if (~next) {
  12427. escapePos = next;
  12428. while (value.charCodeAt(escapePos - 1) === backslash) {
  12429. escapePos -= 1;
  12430. escape = !escape;
  12431. }
  12432. } else {
  12433. value += ")";
  12434. next = value.length - 1;
  12435. token.unclosed = true;
  12436. }
  12437. } while (escape);
  12438. // Whitespaces before closed
  12439. whitespacePos = next;
  12440. do {
  12441. whitespacePos -= 1;
  12442. code = value.charCodeAt(whitespacePos);
  12443. } while (code <= 32);
  12444. if (parenthesesOpenPos < whitespacePos) {
  12445. if (pos !== whitespacePos + 1) {
  12446. token.nodes = [
  12447. {
  12448. type: "word",
  12449. sourceIndex: pos,
  12450. sourceEndIndex: whitespacePos + 1,
  12451. value: value.slice(pos, whitespacePos + 1)
  12452. }
  12453. ];
  12454. } else {
  12455. token.nodes = [];
  12456. }
  12457. if (token.unclosed && whitespacePos + 1 !== next) {
  12458. token.after = "";
  12459. token.nodes.push({
  12460. type: "space",
  12461. sourceIndex: whitespacePos + 1,
  12462. sourceEndIndex: next,
  12463. value: value.slice(whitespacePos + 1, next)
  12464. });
  12465. } else {
  12466. token.after = value.slice(whitespacePos + 1, next);
  12467. token.sourceEndIndex = next;
  12468. }
  12469. } else {
  12470. token.after = "";
  12471. token.nodes = [];
  12472. }
  12473. pos = next + 1;
  12474. token.sourceEndIndex = token.unclosed ? next : pos;
  12475. code = value.charCodeAt(pos);
  12476. tokens.push(token);
  12477. } else {
  12478. balanced += 1;
  12479. token.after = "";
  12480. token.sourceEndIndex = pos + 1;
  12481. tokens.push(token);
  12482. stack.push(token);
  12483. tokens = token.nodes = [];
  12484. parent = token;
  12485. }
  12486. name = "";
  12487. // Close parentheses
  12488. } else if (closeParentheses === code && balanced) {
  12489. pos += 1;
  12490. code = value.charCodeAt(pos);
  12491. parent.after = after;
  12492. parent.sourceEndIndex += after.length;
  12493. after = "";
  12494. balanced -= 1;
  12495. stack[stack.length - 1].sourceEndIndex = pos;
  12496. stack.pop();
  12497. parent = stack[balanced];
  12498. tokens = parent.nodes;
  12499. // Words
  12500. } else {
  12501. next = pos;
  12502. do {
  12503. if (code === backslash) {
  12504. next += 1;
  12505. }
  12506. next += 1;
  12507. code = value.charCodeAt(next);
  12508. } while (
  12509. next < max &&
  12510. !(
  12511. code <= 32 ||
  12512. code === singleQuote ||
  12513. code === doubleQuote ||
  12514. code === comma ||
  12515. code === colon ||
  12516. code === slash ||
  12517. code === openParentheses ||
  12518. (code === star$2 &&
  12519. parent &&
  12520. parent.type === "function" &&
  12521. parent.value === "calc") ||
  12522. (code === slash &&
  12523. parent.type === "function" &&
  12524. parent.value === "calc") ||
  12525. (code === closeParentheses && balanced)
  12526. )
  12527. );
  12528. token = value.slice(pos, next);
  12529. if (openParentheses === code) {
  12530. name = token;
  12531. } else if (
  12532. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  12533. plus === token.charCodeAt(1) &&
  12534. isUnicodeRange.test(token.slice(2))
  12535. ) {
  12536. tokens.push({
  12537. type: "unicode-range",
  12538. sourceIndex: pos,
  12539. sourceEndIndex: next,
  12540. value: token
  12541. });
  12542. } else {
  12543. tokens.push({
  12544. type: "word",
  12545. sourceIndex: pos,
  12546. sourceEndIndex: next,
  12547. value: token
  12548. });
  12549. }
  12550. pos = next;
  12551. }
  12552. }
  12553. for (pos = stack.length - 1; pos; pos -= 1) {
  12554. stack[pos].unclosed = true;
  12555. stack[pos].sourceEndIndex = value.length;
  12556. }
  12557. return stack[0].nodes;
  12558. };
  12559. var walk$2 = function walk(nodes, cb, bubble) {
  12560. var i, max, node, result;
  12561. for (i = 0, max = nodes.length; i < max; i += 1) {
  12562. node = nodes[i];
  12563. if (!bubble) {
  12564. result = cb(node, i, nodes);
  12565. }
  12566. if (
  12567. result !== false &&
  12568. node.type === "function" &&
  12569. Array.isArray(node.nodes)
  12570. ) {
  12571. walk(node.nodes, cb, bubble);
  12572. }
  12573. if (bubble) {
  12574. cb(node, i, nodes);
  12575. }
  12576. }
  12577. };
  12578. function stringifyNode(node, custom) {
  12579. var type = node.type;
  12580. var value = node.value;
  12581. var buf;
  12582. var customResult;
  12583. if (custom && (customResult = custom(node)) !== undefined) {
  12584. return customResult;
  12585. } else if (type === "word" || type === "space") {
  12586. return value;
  12587. } else if (type === "string") {
  12588. buf = node.quote || "";
  12589. return buf + value + (node.unclosed ? "" : buf);
  12590. } else if (type === "comment") {
  12591. return "/*" + value + (node.unclosed ? "" : "*/");
  12592. } else if (type === "div") {
  12593. return (node.before || "") + value + (node.after || "");
  12594. } else if (Array.isArray(node.nodes)) {
  12595. buf = stringify$1(node.nodes, custom);
  12596. if (type !== "function") {
  12597. return buf;
  12598. }
  12599. return (
  12600. value +
  12601. "(" +
  12602. (node.before || "") +
  12603. buf +
  12604. (node.after || "") +
  12605. (node.unclosed ? "" : ")")
  12606. );
  12607. }
  12608. return value;
  12609. }
  12610. function stringify$1(nodes, custom) {
  12611. var result, i;
  12612. if (Array.isArray(nodes)) {
  12613. result = "";
  12614. for (i = nodes.length - 1; ~i; i -= 1) {
  12615. result = stringifyNode(nodes[i], custom) + result;
  12616. }
  12617. return result;
  12618. }
  12619. return stringifyNode(nodes, custom);
  12620. }
  12621. var stringify_1 = stringify$1;
  12622. var unit;
  12623. var hasRequiredUnit;
  12624. function requireUnit () {
  12625. if (hasRequiredUnit) return unit;
  12626. hasRequiredUnit = 1;
  12627. var minus = "-".charCodeAt(0);
  12628. var plus = "+".charCodeAt(0);
  12629. var dot = ".".charCodeAt(0);
  12630. var exp = "e".charCodeAt(0);
  12631. var EXP = "E".charCodeAt(0);
  12632. // Check if three code points would start a number
  12633. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  12634. function likeNumber(value) {
  12635. var code = value.charCodeAt(0);
  12636. var nextCode;
  12637. if (code === plus || code === minus) {
  12638. nextCode = value.charCodeAt(1);
  12639. if (nextCode >= 48 && nextCode <= 57) {
  12640. return true;
  12641. }
  12642. var nextNextCode = value.charCodeAt(2);
  12643. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  12644. return true;
  12645. }
  12646. return false;
  12647. }
  12648. if (code === dot) {
  12649. nextCode = value.charCodeAt(1);
  12650. if (nextCode >= 48 && nextCode <= 57) {
  12651. return true;
  12652. }
  12653. return false;
  12654. }
  12655. if (code >= 48 && code <= 57) {
  12656. return true;
  12657. }
  12658. return false;
  12659. }
  12660. // Consume a number
  12661. // https://www.w3.org/TR/css-syntax-3/#consume-number
  12662. unit = function(value) {
  12663. var pos = 0;
  12664. var length = value.length;
  12665. var code;
  12666. var nextCode;
  12667. var nextNextCode;
  12668. if (length === 0 || !likeNumber(value)) {
  12669. return false;
  12670. }
  12671. code = value.charCodeAt(pos);
  12672. if (code === plus || code === minus) {
  12673. pos++;
  12674. }
  12675. while (pos < length) {
  12676. code = value.charCodeAt(pos);
  12677. if (code < 48 || code > 57) {
  12678. break;
  12679. }
  12680. pos += 1;
  12681. }
  12682. code = value.charCodeAt(pos);
  12683. nextCode = value.charCodeAt(pos + 1);
  12684. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  12685. pos += 2;
  12686. while (pos < length) {
  12687. code = value.charCodeAt(pos);
  12688. if (code < 48 || code > 57) {
  12689. break;
  12690. }
  12691. pos += 1;
  12692. }
  12693. }
  12694. code = value.charCodeAt(pos);
  12695. nextCode = value.charCodeAt(pos + 1);
  12696. nextNextCode = value.charCodeAt(pos + 2);
  12697. if (
  12698. (code === exp || code === EXP) &&
  12699. ((nextCode >= 48 && nextCode <= 57) ||
  12700. ((nextCode === plus || nextCode === minus) &&
  12701. nextNextCode >= 48 &&
  12702. nextNextCode <= 57))
  12703. ) {
  12704. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  12705. while (pos < length) {
  12706. code = value.charCodeAt(pos);
  12707. if (code < 48 || code > 57) {
  12708. break;
  12709. }
  12710. pos += 1;
  12711. }
  12712. }
  12713. return {
  12714. number: value.slice(0, pos),
  12715. unit: value.slice(pos)
  12716. };
  12717. };
  12718. return unit;
  12719. }
  12720. var parse = parse$1;
  12721. var walk$1 = walk$2;
  12722. var stringify = stringify_1;
  12723. function ValueParser(value) {
  12724. if (this instanceof ValueParser) {
  12725. this.nodes = parse(value);
  12726. return this;
  12727. }
  12728. return new ValueParser(value);
  12729. }
  12730. ValueParser.prototype.toString = function() {
  12731. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  12732. };
  12733. ValueParser.prototype.walk = function(cb, bubble) {
  12734. walk$1(this.nodes, cb, bubble);
  12735. return this;
  12736. };
  12737. ValueParser.unit = requireUnit();
  12738. ValueParser.walk = walk$1;
  12739. ValueParser.stringify = stringify;
  12740. var lib = ValueParser;
  12741. const selectorParser$1 = distExports;
  12742. const valueParser = lib;
  12743. const { extractICSS } = src$4;
  12744. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  12745. function normalizeNodeArray(nodes) {
  12746. const array = [];
  12747. nodes.forEach((x) => {
  12748. if (Array.isArray(x)) {
  12749. normalizeNodeArray(x).forEach((item) => {
  12750. array.push(item);
  12751. });
  12752. } else if (x) {
  12753. array.push(x);
  12754. }
  12755. });
  12756. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  12757. array.pop();
  12758. }
  12759. return array;
  12760. }
  12761. function localizeNode(rule, mode, localAliasMap) {
  12762. const transform = (node, context) => {
  12763. if (context.ignoreNextSpacing && !isSpacing(node)) {
  12764. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  12765. }
  12766. if (context.enforceNoSpacing && isSpacing(node)) {
  12767. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  12768. }
  12769. let newNodes;
  12770. switch (node.type) {
  12771. case "root": {
  12772. let resultingGlobal;
  12773. context.hasPureGlobals = false;
  12774. newNodes = node.nodes.map((n) => {
  12775. const nContext = {
  12776. global: context.global,
  12777. lastWasSpacing: true,
  12778. hasLocals: false,
  12779. explicit: false,
  12780. };
  12781. n = transform(n, nContext);
  12782. if (typeof resultingGlobal === "undefined") {
  12783. resultingGlobal = nContext.global;
  12784. } else if (resultingGlobal !== nContext.global) {
  12785. throw new Error(
  12786. 'Inconsistent rule global/local result in rule "' +
  12787. node +
  12788. '" (multiple selectors must result in the same mode for the rule)'
  12789. );
  12790. }
  12791. if (!nContext.hasLocals) {
  12792. context.hasPureGlobals = true;
  12793. }
  12794. return n;
  12795. });
  12796. context.global = resultingGlobal;
  12797. node.nodes = normalizeNodeArray(newNodes);
  12798. break;
  12799. }
  12800. case "selector": {
  12801. newNodes = node.map((childNode) => transform(childNode, context));
  12802. node = node.clone();
  12803. node.nodes = normalizeNodeArray(newNodes);
  12804. break;
  12805. }
  12806. case "combinator": {
  12807. if (isSpacing(node)) {
  12808. if (context.ignoreNextSpacing) {
  12809. context.ignoreNextSpacing = false;
  12810. context.lastWasSpacing = false;
  12811. context.enforceNoSpacing = false;
  12812. return null;
  12813. }
  12814. context.lastWasSpacing = true;
  12815. return node;
  12816. }
  12817. break;
  12818. }
  12819. case "pseudo": {
  12820. let childContext;
  12821. const isNested = !!node.length;
  12822. const isScoped = node.value === ":local" || node.value === ":global";
  12823. const isImportExport =
  12824. node.value === ":import" || node.value === ":export";
  12825. if (isImportExport) {
  12826. context.hasLocals = true;
  12827. // :local(.foo)
  12828. } else if (isNested) {
  12829. if (isScoped) {
  12830. if (node.nodes.length === 0) {
  12831. throw new Error(`${node.value}() can't be empty`);
  12832. }
  12833. if (context.inside) {
  12834. throw new Error(
  12835. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  12836. );
  12837. }
  12838. childContext = {
  12839. global: node.value === ":global",
  12840. inside: node.value,
  12841. hasLocals: false,
  12842. explicit: true,
  12843. };
  12844. newNodes = node
  12845. .map((childNode) => transform(childNode, childContext))
  12846. .reduce((acc, next) => acc.concat(next.nodes), []);
  12847. if (newNodes.length) {
  12848. const { before, after } = node.spaces;
  12849. const first = newNodes[0];
  12850. const last = newNodes[newNodes.length - 1];
  12851. first.spaces = { before, after: first.spaces.after };
  12852. last.spaces = { before: last.spaces.before, after };
  12853. }
  12854. node = newNodes;
  12855. break;
  12856. } else {
  12857. childContext = {
  12858. global: context.global,
  12859. inside: context.inside,
  12860. lastWasSpacing: true,
  12861. hasLocals: false,
  12862. explicit: context.explicit,
  12863. };
  12864. newNodes = node.map((childNode) => {
  12865. const newContext = {
  12866. ...childContext,
  12867. enforceNoSpacing: false,
  12868. };
  12869. const result = transform(childNode, newContext);
  12870. childContext.global = newContext.global;
  12871. childContext.hasLocals = newContext.hasLocals;
  12872. return result;
  12873. });
  12874. node = node.clone();
  12875. node.nodes = normalizeNodeArray(newNodes);
  12876. if (childContext.hasLocals) {
  12877. context.hasLocals = true;
  12878. }
  12879. }
  12880. break;
  12881. //:local .foo .bar
  12882. } else if (isScoped) {
  12883. if (context.inside) {
  12884. throw new Error(
  12885. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  12886. );
  12887. }
  12888. const addBackSpacing = !!node.spaces.before;
  12889. context.ignoreNextSpacing = context.lastWasSpacing
  12890. ? node.value
  12891. : false;
  12892. context.enforceNoSpacing = context.lastWasSpacing
  12893. ? false
  12894. : node.value;
  12895. context.global = node.value === ":global";
  12896. context.explicit = true;
  12897. // because this node has spacing that is lost when we remove it
  12898. // we make up for it by adding an extra combinator in since adding
  12899. // spacing on the parent selector doesn't work
  12900. return addBackSpacing
  12901. ? selectorParser$1.combinator({ value: " " })
  12902. : null;
  12903. }
  12904. break;
  12905. }
  12906. case "id":
  12907. case "class": {
  12908. if (!node.value) {
  12909. throw new Error("Invalid class or id selector syntax");
  12910. }
  12911. if (context.global) {
  12912. break;
  12913. }
  12914. const isImportedValue = localAliasMap.has(node.value);
  12915. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  12916. if (!isImportedValue || isImportedWithExplicitScope) {
  12917. const innerNode = node.clone();
  12918. innerNode.spaces = { before: "", after: "" };
  12919. node = selectorParser$1.pseudo({
  12920. value: ":local",
  12921. nodes: [innerNode],
  12922. spaces: node.spaces,
  12923. });
  12924. context.hasLocals = true;
  12925. }
  12926. break;
  12927. }
  12928. case "nesting": {
  12929. if (node.value === "&") {
  12930. context.hasLocals = true;
  12931. }
  12932. }
  12933. }
  12934. context.lastWasSpacing = false;
  12935. context.ignoreNextSpacing = false;
  12936. context.enforceNoSpacing = false;
  12937. return node;
  12938. };
  12939. const rootContext = {
  12940. global: mode === "global",
  12941. hasPureGlobals: false,
  12942. };
  12943. rootContext.selector = selectorParser$1((root) => {
  12944. transform(root, rootContext);
  12945. }).processSync(rule, { updateSelector: false, lossless: true });
  12946. return rootContext;
  12947. }
  12948. function localizeDeclNode(node, context) {
  12949. switch (node.type) {
  12950. case "word":
  12951. if (context.localizeNextItem) {
  12952. if (!context.localAliasMap.has(node.value)) {
  12953. node.value = ":local(" + node.value + ")";
  12954. context.localizeNextItem = false;
  12955. }
  12956. }
  12957. break;
  12958. case "function":
  12959. if (
  12960. context.options &&
  12961. context.options.rewriteUrl &&
  12962. node.value.toLowerCase() === "url"
  12963. ) {
  12964. node.nodes.map((nestedNode) => {
  12965. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  12966. return;
  12967. }
  12968. let newUrl = context.options.rewriteUrl(
  12969. context.global,
  12970. nestedNode.value
  12971. );
  12972. switch (nestedNode.type) {
  12973. case "string":
  12974. if (nestedNode.quote === "'") {
  12975. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  12976. }
  12977. if (nestedNode.quote === '"') {
  12978. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  12979. }
  12980. break;
  12981. case "word":
  12982. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  12983. break;
  12984. }
  12985. nestedNode.value = newUrl;
  12986. });
  12987. }
  12988. break;
  12989. }
  12990. return node;
  12991. }
  12992. // `none` is special value, other is global values
  12993. const specialKeywords = [
  12994. "none",
  12995. "inherit",
  12996. "initial",
  12997. "revert",
  12998. "revert-layer",
  12999. "unset",
  13000. ];
  13001. function localizeDeclarationValues(localize, declaration, context) {
  13002. const valueNodes = valueParser(declaration.value);
  13003. valueNodes.walk((node, index, nodes) => {
  13004. if (
  13005. node.type === "function" &&
  13006. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  13007. ) {
  13008. return false;
  13009. }
  13010. if (
  13011. node.type === "word" &&
  13012. specialKeywords.includes(node.value.toLowerCase())
  13013. ) {
  13014. return;
  13015. }
  13016. const subContext = {
  13017. options: context.options,
  13018. global: context.global,
  13019. localizeNextItem: localize && !context.global,
  13020. localAliasMap: context.localAliasMap,
  13021. };
  13022. nodes[index] = localizeDeclNode(node, subContext);
  13023. });
  13024. declaration.value = valueNodes.toString();
  13025. }
  13026. function localizeDeclaration(declaration, context) {
  13027. const isAnimation = /animation$/i.test(declaration.prop);
  13028. if (isAnimation) {
  13029. // letter
  13030. // An uppercase letter or a lowercase letter.
  13031. //
  13032. // ident-start code point
  13033. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  13034. //
  13035. // ident code point
  13036. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  13037. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  13038. const validIdent =
  13039. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  13040. /*
  13041. The spec defines some keywords that you can use to describe properties such as the timing
  13042. function. These are still valid animation names, so as long as there is a property that accepts
  13043. a keyword, it is given priority. Only when all the properties that can take a keyword are
  13044. exhausted can the animation name be set to the keyword. I.e.
  13045. animation: infinite infinite;
  13046. The animation will repeat an infinite number of times from the first argument, and will have an
  13047. animation name of infinite from the second.
  13048. */
  13049. const animationKeywords = {
  13050. // animation-direction
  13051. $normal: 1,
  13052. $reverse: 1,
  13053. $alternate: 1,
  13054. "$alternate-reverse": 1,
  13055. // animation-fill-mode
  13056. $forwards: 1,
  13057. $backwards: 1,
  13058. $both: 1,
  13059. // animation-iteration-count
  13060. $infinite: 1,
  13061. // animation-play-state
  13062. $paused: 1,
  13063. $running: 1,
  13064. // animation-timing-function
  13065. $ease: 1,
  13066. "$ease-in": 1,
  13067. "$ease-out": 1,
  13068. "$ease-in-out": 1,
  13069. $linear: 1,
  13070. "$step-end": 1,
  13071. "$step-start": 1,
  13072. // Special
  13073. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  13074. // Global values
  13075. $initial: Infinity,
  13076. $inherit: Infinity,
  13077. $unset: Infinity,
  13078. $revert: Infinity,
  13079. "$revert-layer": Infinity,
  13080. };
  13081. let parsedAnimationKeywords = {};
  13082. const valueNodes = valueParser(declaration.value).walk((node) => {
  13083. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  13084. if (node.type === "div") {
  13085. parsedAnimationKeywords = {};
  13086. return;
  13087. }
  13088. // Do not handle nested functions
  13089. else if (node.type === "function") {
  13090. return false;
  13091. }
  13092. // Ignore all except word
  13093. else if (node.type !== "word") {
  13094. return;
  13095. }
  13096. const value = node.type === "word" ? node.value.toLowerCase() : null;
  13097. let shouldParseAnimationName = false;
  13098. if (value && validIdent.test(value)) {
  13099. if ("$" + value in animationKeywords) {
  13100. parsedAnimationKeywords["$" + value] =
  13101. "$" + value in parsedAnimationKeywords
  13102. ? parsedAnimationKeywords["$" + value] + 1
  13103. : 0;
  13104. shouldParseAnimationName =
  13105. parsedAnimationKeywords["$" + value] >=
  13106. animationKeywords["$" + value];
  13107. } else {
  13108. shouldParseAnimationName = true;
  13109. }
  13110. }
  13111. const subContext = {
  13112. options: context.options,
  13113. global: context.global,
  13114. localizeNextItem: shouldParseAnimationName && !context.global,
  13115. localAliasMap: context.localAliasMap,
  13116. };
  13117. return localizeDeclNode(node, subContext);
  13118. });
  13119. declaration.value = valueNodes.toString();
  13120. return;
  13121. }
  13122. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  13123. if (isAnimationName) {
  13124. return localizeDeclarationValues(true, declaration, context);
  13125. }
  13126. const hasUrl = /url\(/i.test(declaration.value);
  13127. if (hasUrl) {
  13128. return localizeDeclarationValues(false, declaration, context);
  13129. }
  13130. }
  13131. src$2.exports = (options = {}) => {
  13132. if (
  13133. options &&
  13134. options.mode &&
  13135. options.mode !== "global" &&
  13136. options.mode !== "local" &&
  13137. options.mode !== "pure"
  13138. ) {
  13139. throw new Error(
  13140. 'options.mode must be either "global", "local" or "pure" (default "local")'
  13141. );
  13142. }
  13143. const pureMode = options && options.mode === "pure";
  13144. const globalMode = options && options.mode === "global";
  13145. return {
  13146. postcssPlugin: "postcss-modules-local-by-default",
  13147. prepare() {
  13148. const localAliasMap = new Map();
  13149. return {
  13150. Once(root) {
  13151. const { icssImports } = extractICSS(root, false);
  13152. Object.keys(icssImports).forEach((key) => {
  13153. Object.keys(icssImports[key]).forEach((prop) => {
  13154. localAliasMap.set(prop, icssImports[key][prop]);
  13155. });
  13156. });
  13157. root.walkAtRules((atRule) => {
  13158. if (/keyframes$/i.test(atRule.name)) {
  13159. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  13160. atRule.params
  13161. );
  13162. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  13163. atRule.params
  13164. );
  13165. let globalKeyframes = globalMode;
  13166. if (globalMatch) {
  13167. if (pureMode) {
  13168. throw atRule.error(
  13169. "@keyframes :global(...) is not allowed in pure mode"
  13170. );
  13171. }
  13172. atRule.params = globalMatch[1];
  13173. globalKeyframes = true;
  13174. } else if (localMatch) {
  13175. atRule.params = localMatch[0];
  13176. globalKeyframes = false;
  13177. } else if (
  13178. atRule.params &&
  13179. !globalMode &&
  13180. !localAliasMap.has(atRule.params)
  13181. ) {
  13182. atRule.params = ":local(" + atRule.params + ")";
  13183. }
  13184. atRule.walkDecls((declaration) => {
  13185. localizeDeclaration(declaration, {
  13186. localAliasMap,
  13187. options: options,
  13188. global: globalKeyframes,
  13189. });
  13190. });
  13191. } else if (/scope$/i.test(atRule.name)) {
  13192. if (atRule.params) {
  13193. atRule.params = atRule.params
  13194. .split("to")
  13195. .map((item) => {
  13196. const selector = item.trim().slice(1, -1).trim();
  13197. const context = localizeNode(
  13198. selector,
  13199. options.mode,
  13200. localAliasMap
  13201. );
  13202. context.options = options;
  13203. context.localAliasMap = localAliasMap;
  13204. if (pureMode && context.hasPureGlobals) {
  13205. throw atRule.error(
  13206. 'Selector in at-rule"' +
  13207. selector +
  13208. '" is not pure ' +
  13209. "(pure selectors must contain at least one local class or id)"
  13210. );
  13211. }
  13212. return `(${context.selector})`;
  13213. })
  13214. .join(" to ");
  13215. }
  13216. atRule.nodes.forEach((declaration) => {
  13217. if (declaration.type === "decl") {
  13218. localizeDeclaration(declaration, {
  13219. localAliasMap,
  13220. options: options,
  13221. global: globalMode,
  13222. });
  13223. }
  13224. });
  13225. } else if (atRule.nodes) {
  13226. atRule.nodes.forEach((declaration) => {
  13227. if (declaration.type === "decl") {
  13228. localizeDeclaration(declaration, {
  13229. localAliasMap,
  13230. options: options,
  13231. global: globalMode,
  13232. });
  13233. }
  13234. });
  13235. }
  13236. });
  13237. root.walkRules((rule) => {
  13238. if (
  13239. rule.parent &&
  13240. rule.parent.type === "atrule" &&
  13241. /keyframes$/i.test(rule.parent.name)
  13242. ) {
  13243. // ignore keyframe rules
  13244. return;
  13245. }
  13246. const context = localizeNode(rule, options.mode, localAliasMap);
  13247. context.options = options;
  13248. context.localAliasMap = localAliasMap;
  13249. if (pureMode && context.hasPureGlobals) {
  13250. throw rule.error(
  13251. 'Selector "' +
  13252. rule.selector +
  13253. '" is not pure ' +
  13254. "(pure selectors must contain at least one local class or id)"
  13255. );
  13256. }
  13257. rule.selector = context.selector;
  13258. // Less-syntax mixins parse as rules with no nodes
  13259. if (rule.nodes) {
  13260. rule.nodes.forEach((declaration) =>
  13261. localizeDeclaration(declaration, context)
  13262. );
  13263. }
  13264. });
  13265. },
  13266. };
  13267. },
  13268. };
  13269. };
  13270. src$2.exports.postcss = true;
  13271. var srcExports$1 = src$2.exports;
  13272. const selectorParser = distExports;
  13273. const hasOwnProperty = Object.prototype.hasOwnProperty;
  13274. function isNestedRule(rule) {
  13275. if (!rule.parent || rule.parent.type === "root") {
  13276. return false;
  13277. }
  13278. if (rule.parent.type === "rule") {
  13279. return true;
  13280. }
  13281. return isNestedRule(rule.parent);
  13282. }
  13283. function getSingleLocalNamesForComposes(root, rule) {
  13284. if (isNestedRule(rule)) {
  13285. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  13286. }
  13287. return root.nodes.map((node) => {
  13288. if (node.type !== "selector" || node.nodes.length !== 1) {
  13289. throw new Error(
  13290. `composition is only allowed when selector is single :local class name not in "${root}"`
  13291. );
  13292. }
  13293. node = node.nodes[0];
  13294. if (
  13295. node.type !== "pseudo" ||
  13296. node.value !== ":local" ||
  13297. node.nodes.length !== 1
  13298. ) {
  13299. throw new Error(
  13300. 'composition is only allowed when selector is single :local class name not in "' +
  13301. root +
  13302. '", "' +
  13303. node +
  13304. '" is weird'
  13305. );
  13306. }
  13307. node = node.first;
  13308. if (node.type !== "selector" || node.length !== 1) {
  13309. throw new Error(
  13310. 'composition is only allowed when selector is single :local class name not in "' +
  13311. root +
  13312. '", "' +
  13313. node +
  13314. '" is weird'
  13315. );
  13316. }
  13317. node = node.first;
  13318. if (node.type !== "class") {
  13319. // 'id' is not possible, because you can't compose ids
  13320. throw new Error(
  13321. 'composition is only allowed when selector is single :local class name not in "' +
  13322. root +
  13323. '", "' +
  13324. node +
  13325. '" is weird'
  13326. );
  13327. }
  13328. return node.value;
  13329. });
  13330. }
  13331. const whitespace = "[\\x20\\t\\r\\n\\f]";
  13332. const unescapeRegExp = new RegExp(
  13333. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  13334. "ig"
  13335. );
  13336. function unescape$1(str) {
  13337. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  13338. const high = "0x" + escaped - 0x10000;
  13339. // NaN means non-codepoint
  13340. // Workaround erroneous numeric interpretation of +"0x"
  13341. return high !== high || escapedWhitespace
  13342. ? escaped
  13343. : high < 0
  13344. ? // BMP codepoint
  13345. String.fromCharCode(high + 0x10000)
  13346. : // Supplemental Plane codepoint (surrogate pair)
  13347. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  13348. });
  13349. }
  13350. const plugin = (options = {}) => {
  13351. const generateScopedName =
  13352. (options && options.generateScopedName) || plugin.generateScopedName;
  13353. const generateExportEntry =
  13354. (options && options.generateExportEntry) || plugin.generateExportEntry;
  13355. const exportGlobals = options && options.exportGlobals;
  13356. return {
  13357. postcssPlugin: "postcss-modules-scope",
  13358. Once(root, { rule }) {
  13359. const exports = Object.create(null);
  13360. function exportScopedName(name, rawName, node) {
  13361. const scopedName = generateScopedName(
  13362. rawName ? rawName : name,
  13363. root.source.input.from,
  13364. root.source.input.css,
  13365. node
  13366. );
  13367. const exportEntry = generateExportEntry(
  13368. rawName ? rawName : name,
  13369. scopedName,
  13370. root.source.input.from,
  13371. root.source.input.css,
  13372. node
  13373. );
  13374. const { key, value } = exportEntry;
  13375. exports[key] = exports[key] || [];
  13376. if (exports[key].indexOf(value) < 0) {
  13377. exports[key].push(value);
  13378. }
  13379. return scopedName;
  13380. }
  13381. function localizeNode(node) {
  13382. switch (node.type) {
  13383. case "selector":
  13384. node.nodes = node.map((item) => localizeNode(item));
  13385. return node;
  13386. case "class":
  13387. return selectorParser.className({
  13388. value: exportScopedName(
  13389. node.value,
  13390. node.raws && node.raws.value ? node.raws.value : null,
  13391. node
  13392. ),
  13393. });
  13394. case "id": {
  13395. return selectorParser.id({
  13396. value: exportScopedName(
  13397. node.value,
  13398. node.raws && node.raws.value ? node.raws.value : null,
  13399. node
  13400. ),
  13401. });
  13402. }
  13403. case "attribute": {
  13404. if (node.attribute === "class" && node.operator === "=") {
  13405. return selectorParser.attribute({
  13406. attribute: node.attribute,
  13407. operator: node.operator,
  13408. quoteMark: "'",
  13409. value: exportScopedName(node.value, null, null),
  13410. });
  13411. }
  13412. }
  13413. }
  13414. throw new Error(
  13415. `${node.type} ("${node}") is not allowed in a :local block`
  13416. );
  13417. }
  13418. function traverseNode(node) {
  13419. switch (node.type) {
  13420. case "pseudo":
  13421. if (node.value === ":local") {
  13422. if (node.nodes.length !== 1) {
  13423. throw new Error('Unexpected comma (",") in :local block');
  13424. }
  13425. const selector = localizeNode(node.first);
  13426. // move the spaces that were around the pseudo selector to the first
  13427. // non-container node
  13428. selector.first.spaces = node.spaces;
  13429. const nextNode = node.next();
  13430. if (
  13431. nextNode &&
  13432. nextNode.type === "combinator" &&
  13433. nextNode.value === " " &&
  13434. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  13435. ) {
  13436. selector.last.spaces.after = " ";
  13437. }
  13438. node.replaceWith(selector);
  13439. return;
  13440. }
  13441. /* falls through */
  13442. case "root":
  13443. case "selector": {
  13444. node.each((item) => traverseNode(item));
  13445. break;
  13446. }
  13447. case "id":
  13448. case "class":
  13449. if (exportGlobals) {
  13450. exports[node.value] = [node.value];
  13451. }
  13452. break;
  13453. }
  13454. return node;
  13455. }
  13456. // Find any :import and remember imported names
  13457. const importedNames = {};
  13458. root.walkRules(/^:import\(.+\)$/, (rule) => {
  13459. rule.walkDecls((decl) => {
  13460. importedNames[decl.prop] = true;
  13461. });
  13462. });
  13463. // Find any :local selectors
  13464. root.walkRules((rule) => {
  13465. let parsedSelector = selectorParser().astSync(rule);
  13466. rule.selector = traverseNode(parsedSelector.clone()).toString();
  13467. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  13468. const localNames = getSingleLocalNamesForComposes(
  13469. parsedSelector,
  13470. decl.parent
  13471. );
  13472. const multiple = decl.value.split(",");
  13473. multiple.forEach((value) => {
  13474. const classes = value.trim().split(/\s+/);
  13475. classes.forEach((className) => {
  13476. const global = /^global\(([^)]+)\)$/.exec(className);
  13477. if (global) {
  13478. localNames.forEach((exportedName) => {
  13479. exports[exportedName].push(global[1]);
  13480. });
  13481. } else if (hasOwnProperty.call(importedNames, className)) {
  13482. localNames.forEach((exportedName) => {
  13483. exports[exportedName].push(className);
  13484. });
  13485. } else if (hasOwnProperty.call(exports, className)) {
  13486. localNames.forEach((exportedName) => {
  13487. exports[className].forEach((item) => {
  13488. exports[exportedName].push(item);
  13489. });
  13490. });
  13491. } else {
  13492. throw decl.error(
  13493. `referenced class name "${className}" in ${decl.prop} not found`
  13494. );
  13495. }
  13496. });
  13497. });
  13498. decl.remove();
  13499. });
  13500. // Find any :local values
  13501. rule.walkDecls((decl) => {
  13502. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  13503. return;
  13504. }
  13505. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  13506. tokens = tokens.map((token, idx) => {
  13507. if (idx === 0 || tokens[idx - 1] === ",") {
  13508. let result = token;
  13509. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  13510. if (localMatch) {
  13511. const input = localMatch.input;
  13512. const matchPattern = localMatch[0];
  13513. const matchVal = localMatch[1];
  13514. const newVal = exportScopedName(matchVal);
  13515. result = input.replace(matchPattern, newVal);
  13516. } else {
  13517. return token;
  13518. }
  13519. return result;
  13520. } else {
  13521. return token;
  13522. }
  13523. });
  13524. decl.value = tokens.join("");
  13525. });
  13526. });
  13527. // Find any :local keyframes
  13528. root.walkAtRules(/keyframes$/i, (atRule) => {
  13529. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  13530. if (!localMatch) {
  13531. return;
  13532. }
  13533. atRule.params = exportScopedName(localMatch[1]);
  13534. });
  13535. root.walkAtRules(/scope$/i, (atRule) => {
  13536. if (atRule.params) {
  13537. atRule.params = atRule.params
  13538. .split("to")
  13539. .map((item) => {
  13540. const selector = item.trim().slice(1, -1).trim();
  13541. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  13542. if (!localMatch) {
  13543. return `(${selector})`;
  13544. }
  13545. let parsedSelector = selectorParser().astSync(selector);
  13546. return `(${traverseNode(parsedSelector).toString()})`;
  13547. })
  13548. .join(" to ");
  13549. }
  13550. });
  13551. // If we found any :locals, insert an :export rule
  13552. const exportedNames = Object.keys(exports);
  13553. if (exportedNames.length > 0) {
  13554. const exportRule = rule({ selector: ":export" });
  13555. exportedNames.forEach((exportedName) =>
  13556. exportRule.append({
  13557. prop: exportedName,
  13558. value: exports[exportedName].join(" "),
  13559. raws: { before: "\n " },
  13560. })
  13561. );
  13562. root.append(exportRule);
  13563. }
  13564. },
  13565. };
  13566. };
  13567. plugin.postcss = true;
  13568. plugin.generateScopedName = function (name, path) {
  13569. const sanitisedPath = path
  13570. .replace(/\.[^./\\]+$/, "")
  13571. .replace(/[\W_]+/g, "_")
  13572. .replace(/^_|_$/g, "");
  13573. return `_${sanitisedPath}__${name}`.trim();
  13574. };
  13575. plugin.generateExportEntry = function (name, scopedName) {
  13576. return {
  13577. key: unescape$1(name),
  13578. value: unescape$1(scopedName),
  13579. };
  13580. };
  13581. var src$1 = plugin;
  13582. function hash(str) {
  13583. var hash = 5381,
  13584. i = str.length;
  13585. while(i) {
  13586. hash = (hash * 33) ^ str.charCodeAt(--i);
  13587. }
  13588. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  13589. * integers. Since we want the results to be always positive, convert the
  13590. * signed int to an unsigned by doing an unsigned bitshift. */
  13591. return hash >>> 0;
  13592. }
  13593. var stringHash = hash;
  13594. var src = {exports: {}};
  13595. const ICSSUtils = src$4;
  13596. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  13597. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  13598. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  13599. src.exports = (options) => {
  13600. let importIndex = 0;
  13601. const createImportedName =
  13602. (options && options.createImportedName) ||
  13603. ((importName /*, path*/) =>
  13604. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  13605. return {
  13606. postcssPlugin: "postcss-modules-values",
  13607. prepare(result) {
  13608. const importAliases = [];
  13609. const definitions = {};
  13610. return {
  13611. Once(root, postcss) {
  13612. root.walkAtRules(/value/i, (atRule) => {
  13613. const matches = atRule.params.match(matchImports);
  13614. if (matches) {
  13615. let [, /*match*/ aliases, path] = matches;
  13616. // We can use constants for path names
  13617. if (definitions[path]) {
  13618. path = definitions[path];
  13619. }
  13620. const imports = aliases
  13621. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  13622. .split(/\s*,\s*/)
  13623. .map((alias) => {
  13624. const tokens = matchImport.exec(alias);
  13625. if (tokens) {
  13626. const [, /*match*/ theirName, myName = theirName] = tokens;
  13627. const importedName = createImportedName(myName);
  13628. definitions[myName] = importedName;
  13629. return { theirName, importedName };
  13630. } else {
  13631. throw new Error(`@import statement "${alias}" is invalid!`);
  13632. }
  13633. });
  13634. importAliases.push({ path, imports });
  13635. atRule.remove();
  13636. return;
  13637. }
  13638. if (atRule.params.indexOf("@value") !== -1) {
  13639. result.warn("Invalid value definition: " + atRule.params);
  13640. }
  13641. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  13642. matchValueDefinition
  13643. );
  13644. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  13645. if (normalizedValue.length === 0) {
  13646. result.warn("Invalid value definition: " + atRule.params);
  13647. atRule.remove();
  13648. return;
  13649. }
  13650. let isOnlySpace = /^\s+$/.test(normalizedValue);
  13651. if (!isOnlySpace) {
  13652. value = value.trim();
  13653. }
  13654. // Add to the definitions, knowing that values can refer to each other
  13655. definitions[key] = ICSSUtils.replaceValueSymbols(
  13656. value,
  13657. definitions
  13658. );
  13659. atRule.remove();
  13660. });
  13661. /* If we have no definitions, don't continue */
  13662. if (!Object.keys(definitions).length) {
  13663. return;
  13664. }
  13665. /* Perform replacements */
  13666. ICSSUtils.replaceSymbols(root, definitions);
  13667. /* 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 */
  13668. const exportDeclarations = Object.keys(definitions).map((key) =>
  13669. postcss.decl({
  13670. value: definitions[key],
  13671. prop: key,
  13672. raws: { before: "\n " },
  13673. })
  13674. );
  13675. /* Add export rules if any */
  13676. if (exportDeclarations.length > 0) {
  13677. const exportRule = postcss.rule({
  13678. selector: ":export",
  13679. raws: { after: "\n" },
  13680. });
  13681. exportRule.append(exportDeclarations);
  13682. root.prepend(exportRule);
  13683. }
  13684. /* Add import rules */
  13685. importAliases.reverse().forEach(({ path, imports }) => {
  13686. const importRule = postcss.rule({
  13687. selector: `:import(${path})`,
  13688. raws: { after: "\n" },
  13689. });
  13690. imports.forEach(({ theirName, importedName }) => {
  13691. importRule.append({
  13692. value: theirName,
  13693. prop: importedName,
  13694. raws: { before: "\n " },
  13695. });
  13696. });
  13697. root.prepend(importRule);
  13698. });
  13699. },
  13700. };
  13701. },
  13702. };
  13703. };
  13704. src.exports.postcss = true;
  13705. var srcExports = src.exports;
  13706. Object.defineProperty(scoping, "__esModule", {
  13707. value: true
  13708. });
  13709. scoping.behaviours = void 0;
  13710. scoping.getDefaultPlugins = getDefaultPlugins;
  13711. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  13712. scoping.getScopedNameGenerator = getScopedNameGenerator;
  13713. var _postcssModulesExtractImports = _interopRequireDefault$1(srcExports$2);
  13714. var _genericNames = _interopRequireDefault$1(genericNames);
  13715. var _postcssModulesLocalByDefault = _interopRequireDefault$1(srcExports$1);
  13716. var _postcssModulesScope = _interopRequireDefault$1(src$1);
  13717. var _stringHash = _interopRequireDefault$1(stringHash);
  13718. var _postcssModulesValues = _interopRequireDefault$1(srcExports);
  13719. function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13720. const behaviours = {
  13721. LOCAL: "local",
  13722. GLOBAL: "global"
  13723. };
  13724. scoping.behaviours = behaviours;
  13725. function getDefaultPlugins({
  13726. behaviour,
  13727. generateScopedName,
  13728. exportGlobals
  13729. }) {
  13730. const scope = (0, _postcssModulesScope.default)({
  13731. generateScopedName,
  13732. exportGlobals
  13733. });
  13734. const plugins = {
  13735. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  13736. mode: "local"
  13737. }), _postcssModulesExtractImports.default, scope],
  13738. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  13739. mode: "global"
  13740. }), _postcssModulesExtractImports.default, scope]
  13741. };
  13742. return plugins[behaviour];
  13743. }
  13744. function isValidBehaviour(behaviour) {
  13745. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  13746. }
  13747. function getDefaultScopeBehaviour(scopeBehaviour) {
  13748. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  13749. }
  13750. function generateScopedNameDefault(name, filename, css) {
  13751. const i = css.indexOf(`.${name}`);
  13752. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  13753. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  13754. return `_${name}_${hash}_${lineNumber}`;
  13755. }
  13756. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  13757. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  13758. if (typeof scopedNameGenerator === "function") {
  13759. return scopedNameGenerator;
  13760. }
  13761. return (0, _genericNames.default)(scopedNameGenerator, {
  13762. context: process.cwd(),
  13763. hashPrefix: hashPrefix
  13764. });
  13765. }
  13766. Object.defineProperty(pluginFactory, "__esModule", {
  13767. value: true
  13768. });
  13769. pluginFactory.makePlugin = makePlugin;
  13770. var _postcss = _interopRequireDefault(require$$0$1);
  13771. var _unquote = _interopRequireDefault(unquote$1);
  13772. var _Parser = _interopRequireDefault(Parser$1);
  13773. var _saveJSON = _interopRequireDefault(saveJSON$1);
  13774. var _localsConvention = localsConvention;
  13775. var _FileSystemLoader = _interopRequireDefault(FileSystemLoader$1);
  13776. var _scoping = scoping;
  13777. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13778. const PLUGIN_NAME = "postcss-modules";
  13779. function isGlobalModule(globalModules, inputFile) {
  13780. return globalModules.some(regex => inputFile.match(regex));
  13781. }
  13782. function getDefaultPluginsList(opts, inputFile) {
  13783. const globalModulesList = opts.globalModulePaths || null;
  13784. const exportGlobals = opts.exportGlobals || false;
  13785. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  13786. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  13787. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  13788. return (0, _scoping.getDefaultPlugins)({
  13789. behaviour: _scoping.behaviours.GLOBAL,
  13790. generateScopedName,
  13791. exportGlobals
  13792. });
  13793. }
  13794. return (0, _scoping.getDefaultPlugins)({
  13795. behaviour: defaultBehaviour,
  13796. generateScopedName,
  13797. exportGlobals
  13798. });
  13799. }
  13800. function getLoader(opts, plugins) {
  13801. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  13802. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  13803. }
  13804. function isOurPlugin(plugin) {
  13805. return plugin.postcssPlugin === PLUGIN_NAME;
  13806. }
  13807. function makePlugin(opts) {
  13808. return {
  13809. postcssPlugin: PLUGIN_NAME,
  13810. async OnceExit(css, {
  13811. result
  13812. }) {
  13813. const getJSON = opts.getJSON || _saveJSON.default;
  13814. const inputFile = css.source.input.file;
  13815. const pluginList = getDefaultPluginsList(opts, inputFile);
  13816. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  13817. if (resultPluginIndex === -1) {
  13818. throw new Error("Plugin missing from options.");
  13819. }
  13820. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  13821. const loaderPlugins = [...earlierPlugins, ...pluginList];
  13822. const loader = getLoader(opts, loaderPlugins);
  13823. const fetcher = async (file, relativeTo, depTrace) => {
  13824. const unquoteFile = (0, _unquote.default)(file);
  13825. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  13826. };
  13827. const parser = new _Parser.default(fetcher);
  13828. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  13829. from: inputFile
  13830. });
  13831. const out = loader.finalSource;
  13832. if (out) css.prepend(out);
  13833. if (opts.localsConvention) {
  13834. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  13835. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  13836. }
  13837. result.messages.push({
  13838. type: "export",
  13839. plugin: "postcss-modules",
  13840. exportTokens: parser.exportTokens
  13841. }); // getJSON may return a promise
  13842. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  13843. }
  13844. };
  13845. }
  13846. var _fs = require$$0;
  13847. var _fs2 = fs;
  13848. var _pluginFactory = pluginFactory;
  13849. (0, _fs2.setFileSystem)({
  13850. readFile: _fs.readFile,
  13851. writeFile: _fs.writeFile
  13852. });
  13853. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  13854. build.exports.postcss = true;
  13855. var buildExports = build.exports;
  13856. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  13857. function compileStyle(options) {
  13858. return doCompileStyle({
  13859. ...options,
  13860. isAsync: false
  13861. });
  13862. }
  13863. function compileStyleAsync(options) {
  13864. return doCompileStyle({
  13865. ...options,
  13866. isAsync: true
  13867. });
  13868. }
  13869. function doCompileStyle(options) {
  13870. const {
  13871. filename,
  13872. id,
  13873. scoped = false,
  13874. trim = true,
  13875. isProd = false,
  13876. modules = false,
  13877. modulesOptions = {},
  13878. preprocessLang,
  13879. postcssOptions,
  13880. postcssPlugins
  13881. } = options;
  13882. const preprocessor = preprocessLang && processors[preprocessLang];
  13883. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  13884. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  13885. const source = preProcessedSource ? preProcessedSource.code : options.source;
  13886. const shortId = id.replace(/^data-v-/, "");
  13887. const longId = `data-v-${shortId}`;
  13888. const plugins = (postcssPlugins || []).slice();
  13889. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  13890. if (trim) {
  13891. plugins.push(trimPlugin());
  13892. }
  13893. if (scoped) {
  13894. plugins.push(scopedPlugin(longId));
  13895. }
  13896. let cssModules;
  13897. if (modules) {
  13898. if (!options.isAsync) {
  13899. throw new Error(
  13900. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  13901. );
  13902. }
  13903. plugins.push(
  13904. postcssModules({
  13905. ...modulesOptions,
  13906. getJSON: (_cssFileName, json) => {
  13907. cssModules = json;
  13908. }
  13909. })
  13910. );
  13911. }
  13912. const postCSSOptions = {
  13913. ...postcssOptions,
  13914. to: filename,
  13915. from: filename
  13916. };
  13917. if (map) {
  13918. postCSSOptions.map = {
  13919. inline: false,
  13920. annotation: false,
  13921. prev: map
  13922. };
  13923. }
  13924. let result;
  13925. let code;
  13926. let outMap;
  13927. const dependencies = new Set(
  13928. preProcessedSource ? preProcessedSource.dependencies : []
  13929. );
  13930. dependencies.delete(filename);
  13931. const errors = [];
  13932. if (preProcessedSource && preProcessedSource.errors.length) {
  13933. errors.push(...preProcessedSource.errors);
  13934. }
  13935. const recordPlainCssDependencies = (messages) => {
  13936. messages.forEach((msg) => {
  13937. if (msg.type === "dependency") {
  13938. dependencies.add(msg.file);
  13939. }
  13940. });
  13941. return dependencies;
  13942. };
  13943. try {
  13944. result = require$$0$1(plugins).process(source, postCSSOptions);
  13945. if (options.isAsync) {
  13946. return result.then((result2) => ({
  13947. code: result2.css || "",
  13948. map: result2.map && result2.map.toJSON(),
  13949. errors,
  13950. modules: cssModules,
  13951. rawResult: result2,
  13952. dependencies: recordPlainCssDependencies(result2.messages)
  13953. })).catch((error) => ({
  13954. code: "",
  13955. map: void 0,
  13956. errors: [...errors, error],
  13957. rawResult: void 0,
  13958. dependencies
  13959. }));
  13960. }
  13961. recordPlainCssDependencies(result.messages);
  13962. code = result.css;
  13963. outMap = result.map;
  13964. } catch (e) {
  13965. errors.push(e);
  13966. }
  13967. return {
  13968. code: code || ``,
  13969. map: outMap && outMap.toJSON(),
  13970. errors,
  13971. rawResult: result,
  13972. dependencies
  13973. };
  13974. }
  13975. function preprocess(options, preprocessor) {
  13976. return preprocessor(
  13977. options.source,
  13978. options.inMap || options.map,
  13979. {
  13980. filename: options.filename,
  13981. ...options.preprocessOptions
  13982. },
  13983. options.preprocessCustomRequire
  13984. );
  13985. }
  13986. function analyzeScriptBindings(ast) {
  13987. for (const node of ast) {
  13988. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  13989. return analyzeBindingsFromOptions(node.declaration);
  13990. }
  13991. }
  13992. return {};
  13993. }
  13994. function analyzeBindingsFromOptions(node) {
  13995. const bindings = {};
  13996. Object.defineProperty(bindings, "__isScriptSetup", {
  13997. enumerable: false,
  13998. value: false
  13999. });
  14000. for (const property of node.properties) {
  14001. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  14002. if (property.key.name === "props") {
  14003. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  14004. bindings[key] = "props";
  14005. }
  14006. } else if (property.key.name === "inject") {
  14007. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  14008. bindings[key] = "options";
  14009. }
  14010. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  14011. for (const key of getObjectExpressionKeys(property.value)) {
  14012. bindings[key] = "options";
  14013. }
  14014. }
  14015. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  14016. for (const bodyItem of property.body.body) {
  14017. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  14018. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  14019. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  14020. }
  14021. }
  14022. }
  14023. }
  14024. }
  14025. return bindings;
  14026. }
  14027. function getObjectExpressionKeys(node) {
  14028. const keys = [];
  14029. for (const prop of node.properties) {
  14030. if (prop.type === "SpreadElement") continue;
  14031. const key = resolveObjectKey(prop.key, prop.computed);
  14032. if (key) keys.push(String(key));
  14033. }
  14034. return keys;
  14035. }
  14036. function getArrayExpressionKeys(node) {
  14037. const keys = [];
  14038. for (const element of node.elements) {
  14039. if (element && element.type === "StringLiteral") {
  14040. keys.push(element.value);
  14041. }
  14042. }
  14043. return keys;
  14044. }
  14045. function getObjectOrArrayExpressionKeys(value) {
  14046. if (value.type === "ArrayExpression") {
  14047. return getArrayExpressionKeys(value);
  14048. }
  14049. if (value.type === "ObjectExpression") {
  14050. return getObjectExpressionKeys(value);
  14051. }
  14052. return [];
  14053. }
  14054. var _a, _b;
  14055. class ScriptCompileContext {
  14056. constructor(descriptor, options) {
  14057. this.descriptor = descriptor;
  14058. this.options = options;
  14059. this.isCE = false;
  14060. this.source = this.descriptor.source;
  14061. this.filename = this.descriptor.filename;
  14062. this.s = new MagicString(this.source);
  14063. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  14064. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  14065. this.userImports = /* @__PURE__ */ Object.create(null);
  14066. // macros presence check
  14067. this.hasDefinePropsCall = false;
  14068. this.hasDefineEmitCall = false;
  14069. this.hasDefineExposeCall = false;
  14070. this.hasDefaultExportName = false;
  14071. this.hasDefaultExportRender = false;
  14072. this.hasDefineOptionsCall = false;
  14073. this.hasDefineSlotsCall = false;
  14074. this.hasDefineModelCall = false;
  14075. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  14076. // defineModel
  14077. this.modelDecls = /* @__PURE__ */ Object.create(null);
  14078. // codegen
  14079. this.bindingMetadata = {};
  14080. this.helperImports = /* @__PURE__ */ new Set();
  14081. const { script, scriptSetup } = descriptor;
  14082. const scriptLang = script && script.lang;
  14083. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  14084. this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx";
  14085. this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx";
  14086. const customElement = options.customElement;
  14087. const filename = this.descriptor.filename;
  14088. if (customElement) {
  14089. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  14090. }
  14091. const plugins = resolveParserPlugins(
  14092. scriptLang || scriptSetupLang,
  14093. options.babelParserPlugins
  14094. );
  14095. function parse(input, offset) {
  14096. try {
  14097. return parser$1.parse(input, {
  14098. plugins,
  14099. sourceType: "module"
  14100. }).program;
  14101. } catch (e) {
  14102. e.message = `[vue/compiler-sfc] ${e.message}
  14103. ${descriptor.filename}
  14104. ${shared.generateCodeFrame(
  14105. descriptor.source,
  14106. e.pos + offset,
  14107. e.pos + offset + 1
  14108. )}`;
  14109. throw e;
  14110. }
  14111. }
  14112. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  14113. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  14114. }
  14115. helper(key) {
  14116. this.helperImports.add(key);
  14117. return `_${key}`;
  14118. }
  14119. getString(node, scriptSetup = true) {
  14120. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  14121. return block.content.slice(node.start, node.end);
  14122. }
  14123. error(msg, node, scope) {
  14124. const offset = scope ? scope.offset : this.startOffset;
  14125. throw new Error(
  14126. `[@vue/compiler-sfc] ${msg}
  14127. ${(scope || this.descriptor).filename}
  14128. ${shared.generateCodeFrame(
  14129. (scope || this.descriptor).source,
  14130. node.start + offset,
  14131. node.end + offset
  14132. )}`
  14133. );
  14134. }
  14135. }
  14136. function resolveParserPlugins(lang, userPlugins, dts = false) {
  14137. const plugins = [];
  14138. if (!userPlugins || !userPlugins.some(
  14139. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  14140. )) {
  14141. plugins.push("importAttributes");
  14142. }
  14143. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  14144. plugins.push("jsx");
  14145. } else if (userPlugins) {
  14146. userPlugins = userPlugins.filter((p) => p !== "jsx");
  14147. }
  14148. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "mtsx") {
  14149. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  14150. if (!userPlugins || !userPlugins.includes("decorators")) {
  14151. plugins.push("decorators-legacy");
  14152. }
  14153. }
  14154. if (userPlugins) {
  14155. plugins.push(...userPlugins);
  14156. }
  14157. return plugins;
  14158. }
  14159. function rewriteDefault(input, as, parserPlugins) {
  14160. const ast = parser$1.parse(input, {
  14161. sourceType: "module",
  14162. plugins: resolveParserPlugins("js", parserPlugins)
  14163. }).program.body;
  14164. const s = new MagicString(input);
  14165. rewriteDefaultAST(ast, s, as);
  14166. return s.toString();
  14167. }
  14168. function rewriteDefaultAST(ast, s, as) {
  14169. if (!hasDefaultExport(ast)) {
  14170. s.append(`
  14171. const ${as} = {}`);
  14172. return;
  14173. }
  14174. ast.forEach((node) => {
  14175. if (node.type === "ExportDefaultDeclaration") {
  14176. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  14177. let start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  14178. s.overwrite(start, node.declaration.id.start, ` class `);
  14179. s.append(`
  14180. const ${as} = ${node.declaration.id.name}`);
  14181. } else {
  14182. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  14183. }
  14184. } else if (node.type === "ExportNamedDeclaration") {
  14185. for (const specifier of node.specifiers) {
  14186. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  14187. if (node.source) {
  14188. if (specifier.local.name === "default") {
  14189. s.prepend(
  14190. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  14191. `
  14192. );
  14193. const end2 = specifierEnd(s, specifier.local.end, node.end);
  14194. s.remove(specifier.start, end2);
  14195. s.append(`
  14196. const ${as} = __VUE_DEFAULT__`);
  14197. continue;
  14198. } else {
  14199. s.prepend(
  14200. `import { ${s.slice(
  14201. specifier.local.start,
  14202. specifier.local.end
  14203. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  14204. `
  14205. );
  14206. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  14207. s.remove(specifier.start, end2);
  14208. s.append(`
  14209. const ${as} = __VUE_DEFAULT__`);
  14210. continue;
  14211. }
  14212. }
  14213. const end = specifierEnd(s, specifier.end, node.end);
  14214. s.remove(specifier.start, end);
  14215. s.append(`
  14216. const ${as} = ${specifier.local.name}`);
  14217. }
  14218. }
  14219. }
  14220. });
  14221. }
  14222. function hasDefaultExport(ast) {
  14223. for (const stmt of ast) {
  14224. if (stmt.type === "ExportDefaultDeclaration") {
  14225. return true;
  14226. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  14227. (spec) => spec.exported.name === "default"
  14228. )) {
  14229. return true;
  14230. }
  14231. }
  14232. return false;
  14233. }
  14234. function specifierEnd(s, end, nodeEnd) {
  14235. let hasCommas = false;
  14236. let oldEnd = end;
  14237. while (end < nodeEnd) {
  14238. if (/\s/.test(s.slice(end, end + 1))) {
  14239. end++;
  14240. } else if (s.slice(end, end + 1) === ",") {
  14241. end++;
  14242. hasCommas = true;
  14243. break;
  14244. } else if (s.slice(end, end + 1) === "}") {
  14245. break;
  14246. }
  14247. }
  14248. return hasCommas ? end : oldEnd;
  14249. }
  14250. const normalScriptDefaultVar = `__default__`;
  14251. function processNormalScript(ctx, scopeId) {
  14252. var _a;
  14253. const script = ctx.descriptor.script;
  14254. if (script.lang && !ctx.isJS && !ctx.isTS) {
  14255. return script;
  14256. }
  14257. try {
  14258. let content = script.content;
  14259. let map = script.map;
  14260. const scriptAst = ctx.scriptAst;
  14261. const bindings = analyzeScriptBindings(scriptAst.body);
  14262. const { cssVars } = ctx.descriptor;
  14263. const { genDefaultAs, isProd } = ctx.options;
  14264. if (cssVars.length || genDefaultAs) {
  14265. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  14266. const s = new MagicString(content);
  14267. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  14268. content = s.toString();
  14269. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  14270. content += genNormalScriptCssVarsCode(
  14271. cssVars,
  14272. bindings,
  14273. scopeId,
  14274. !!isProd,
  14275. defaultVar
  14276. );
  14277. }
  14278. if (!genDefaultAs) {
  14279. content += `
  14280. export default ${defaultVar}`;
  14281. }
  14282. }
  14283. return {
  14284. ...script,
  14285. content,
  14286. map,
  14287. bindings,
  14288. scriptAst: scriptAst.body
  14289. };
  14290. } catch (e) {
  14291. return script;
  14292. }
  14293. }
  14294. var balancedMatch = balanced$1;
  14295. function balanced$1(a, b, str) {
  14296. if (a instanceof RegExp) a = maybeMatch(a, str);
  14297. if (b instanceof RegExp) b = maybeMatch(b, str);
  14298. var r = range(a, b, str);
  14299. return r && {
  14300. start: r[0],
  14301. end: r[1],
  14302. pre: str.slice(0, r[0]),
  14303. body: str.slice(r[0] + a.length, r[1]),
  14304. post: str.slice(r[1] + b.length)
  14305. };
  14306. }
  14307. function maybeMatch(reg, str) {
  14308. var m = str.match(reg);
  14309. return m ? m[0] : null;
  14310. }
  14311. balanced$1.range = range;
  14312. function range(a, b, str) {
  14313. var begs, beg, left, right, result;
  14314. var ai = str.indexOf(a);
  14315. var bi = str.indexOf(b, ai + 1);
  14316. var i = ai;
  14317. if (ai >= 0 && bi > 0) {
  14318. if(a===b) {
  14319. return [ai, bi];
  14320. }
  14321. begs = [];
  14322. left = str.length;
  14323. while (i >= 0 && !result) {
  14324. if (i == ai) {
  14325. begs.push(i);
  14326. ai = str.indexOf(a, i + 1);
  14327. } else if (begs.length == 1) {
  14328. result = [ begs.pop(), bi ];
  14329. } else {
  14330. beg = begs.pop();
  14331. if (beg < left) {
  14332. left = beg;
  14333. right = bi;
  14334. }
  14335. bi = str.indexOf(b, i + 1);
  14336. }
  14337. i = ai < bi && ai >= 0 ? ai : bi;
  14338. }
  14339. if (begs.length) {
  14340. result = [ left, right ];
  14341. }
  14342. }
  14343. return result;
  14344. }
  14345. var balanced = balancedMatch;
  14346. var braceExpansion = expandTop;
  14347. var escSlash = '\0SLASH'+Math.random()+'\0';
  14348. var escOpen = '\0OPEN'+Math.random()+'\0';
  14349. var escClose = '\0CLOSE'+Math.random()+'\0';
  14350. var escComma = '\0COMMA'+Math.random()+'\0';
  14351. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  14352. function numeric(str) {
  14353. return parseInt(str, 10) == str
  14354. ? parseInt(str, 10)
  14355. : str.charCodeAt(0);
  14356. }
  14357. function escapeBraces(str) {
  14358. return str.split('\\\\').join(escSlash)
  14359. .split('\\{').join(escOpen)
  14360. .split('\\}').join(escClose)
  14361. .split('\\,').join(escComma)
  14362. .split('\\.').join(escPeriod);
  14363. }
  14364. function unescapeBraces(str) {
  14365. return str.split(escSlash).join('\\')
  14366. .split(escOpen).join('{')
  14367. .split(escClose).join('}')
  14368. .split(escComma).join(',')
  14369. .split(escPeriod).join('.');
  14370. }
  14371. // Basically just str.split(","), but handling cases
  14372. // where we have nested braced sections, which should be
  14373. // treated as individual members, like {a,{b,c},d}
  14374. function parseCommaParts(str) {
  14375. if (!str)
  14376. return [''];
  14377. var parts = [];
  14378. var m = balanced('{', '}', str);
  14379. if (!m)
  14380. return str.split(',');
  14381. var pre = m.pre;
  14382. var body = m.body;
  14383. var post = m.post;
  14384. var p = pre.split(',');
  14385. p[p.length-1] += '{' + body + '}';
  14386. var postParts = parseCommaParts(post);
  14387. if (post.length) {
  14388. p[p.length-1] += postParts.shift();
  14389. p.push.apply(p, postParts);
  14390. }
  14391. parts.push.apply(parts, p);
  14392. return parts;
  14393. }
  14394. function expandTop(str) {
  14395. if (!str)
  14396. return [];
  14397. // I don't know why Bash 4.3 does this, but it does.
  14398. // Anything starting with {} will have the first two bytes preserved
  14399. // but *only* at the top level, so {},a}b will not expand to anything,
  14400. // but a{},b}c will be expanded to [a}c,abc].
  14401. // One could argue that this is a bug in Bash, but since the goal of
  14402. // this module is to match Bash's rules, we escape a leading {}
  14403. if (str.substr(0, 2) === '{}') {
  14404. str = '\\{\\}' + str.substr(2);
  14405. }
  14406. return expand(escapeBraces(str), true).map(unescapeBraces);
  14407. }
  14408. function embrace(str) {
  14409. return '{' + str + '}';
  14410. }
  14411. function isPadded(el) {
  14412. return /^-?0\d/.test(el);
  14413. }
  14414. function lte(i, y) {
  14415. return i <= y;
  14416. }
  14417. function gte(i, y) {
  14418. return i >= y;
  14419. }
  14420. function expand(str, isTop) {
  14421. var expansions = [];
  14422. var m = balanced('{', '}', str);
  14423. if (!m) return [str];
  14424. // no need to expand pre, since it is guaranteed to be free of brace-sets
  14425. var pre = m.pre;
  14426. var post = m.post.length
  14427. ? expand(m.post, false)
  14428. : [''];
  14429. if (/\$$/.test(m.pre)) {
  14430. for (var k = 0; k < post.length; k++) {
  14431. var expansion = pre+ '{' + m.body + '}' + post[k];
  14432. expansions.push(expansion);
  14433. }
  14434. } else {
  14435. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  14436. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  14437. var isSequence = isNumericSequence || isAlphaSequence;
  14438. var isOptions = m.body.indexOf(',') >= 0;
  14439. if (!isSequence && !isOptions) {
  14440. // {a},b}
  14441. if (m.post.match(/,.*\}/)) {
  14442. str = m.pre + '{' + m.body + escClose + m.post;
  14443. return expand(str);
  14444. }
  14445. return [str];
  14446. }
  14447. var n;
  14448. if (isSequence) {
  14449. n = m.body.split(/\.\./);
  14450. } else {
  14451. n = parseCommaParts(m.body);
  14452. if (n.length === 1) {
  14453. // x{{a,b}}y ==> x{a}y x{b}y
  14454. n = expand(n[0], false).map(embrace);
  14455. if (n.length === 1) {
  14456. return post.map(function(p) {
  14457. return m.pre + n[0] + p;
  14458. });
  14459. }
  14460. }
  14461. }
  14462. // at this point, n is the parts, and we know it's not a comma set
  14463. // with a single entry.
  14464. var N;
  14465. if (isSequence) {
  14466. var x = numeric(n[0]);
  14467. var y = numeric(n[1]);
  14468. var width = Math.max(n[0].length, n[1].length);
  14469. var incr = n.length == 3
  14470. ? Math.abs(numeric(n[2]))
  14471. : 1;
  14472. var test = lte;
  14473. var reverse = y < x;
  14474. if (reverse) {
  14475. incr *= -1;
  14476. test = gte;
  14477. }
  14478. var pad = n.some(isPadded);
  14479. N = [];
  14480. for (var i = x; test(i, y); i += incr) {
  14481. var c;
  14482. if (isAlphaSequence) {
  14483. c = String.fromCharCode(i);
  14484. if (c === '\\')
  14485. c = '';
  14486. } else {
  14487. c = String(i);
  14488. if (pad) {
  14489. var need = width - c.length;
  14490. if (need > 0) {
  14491. var z = new Array(need + 1).join('0');
  14492. if (i < 0)
  14493. c = '-' + z + c.slice(1);
  14494. else
  14495. c = z + c;
  14496. }
  14497. }
  14498. }
  14499. N.push(c);
  14500. }
  14501. } else {
  14502. N = [];
  14503. for (var j = 0; j < n.length; j++) {
  14504. N.push.apply(N, expand(n[j], false));
  14505. }
  14506. }
  14507. for (var j = 0; j < N.length; j++) {
  14508. for (var k = 0; k < post.length; k++) {
  14509. var expansion = pre + N[j] + post[k];
  14510. if (!isTop || isSequence || expansion)
  14511. expansions.push(expansion);
  14512. }
  14513. }
  14514. }
  14515. return expansions;
  14516. }
  14517. var expand$1 = /*@__PURE__*/getDefaultExportFromCjs(braceExpansion);
  14518. const MAX_PATTERN_LENGTH = 1024 * 64;
  14519. const assertValidPattern = (pattern) => {
  14520. if (typeof pattern !== 'string') {
  14521. throw new TypeError('invalid pattern');
  14522. }
  14523. if (pattern.length > MAX_PATTERN_LENGTH) {
  14524. throw new TypeError('pattern is too long');
  14525. }
  14526. };
  14527. // translate the various posix character classes into unicode properties
  14528. // this works across all unicode locales
  14529. // { <posix class>: [<translation>, /u flag required, negated]
  14530. const posixClasses = {
  14531. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  14532. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  14533. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  14534. '[:blank:]': ['\\p{Zs}\\t', true],
  14535. '[:cntrl:]': ['\\p{Cc}', true],
  14536. '[:digit:]': ['\\p{Nd}', true],
  14537. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  14538. '[:lower:]': ['\\p{Ll}', true],
  14539. '[:print:]': ['\\p{C}', true],
  14540. '[:punct:]': ['\\p{P}', true],
  14541. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  14542. '[:upper:]': ['\\p{Lu}', true],
  14543. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  14544. '[:xdigit:]': ['A-Fa-f0-9', false],
  14545. };
  14546. // only need to escape a few things inside of brace expressions
  14547. // escapes: [ \ ] -
  14548. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  14549. // escape all regexp magic characters
  14550. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  14551. // everything has already been escaped, we just have to join
  14552. const rangesToString = (ranges) => ranges.join('');
  14553. // takes a glob string at a posix brace expression, and returns
  14554. // an equivalent regular expression source, and boolean indicating
  14555. // whether the /u flag needs to be applied, and the number of chars
  14556. // consumed to parse the character class.
  14557. // This also removes out of order ranges, and returns ($.) if the
  14558. // entire class just no good.
  14559. const parseClass = (glob, position) => {
  14560. const pos = position;
  14561. /* c8 ignore start */
  14562. if (glob.charAt(pos) !== '[') {
  14563. throw new Error('not in a brace expression');
  14564. }
  14565. /* c8 ignore stop */
  14566. const ranges = [];
  14567. const negs = [];
  14568. let i = pos + 1;
  14569. let sawStart = false;
  14570. let uflag = false;
  14571. let escaping = false;
  14572. let negate = false;
  14573. let endPos = pos;
  14574. let rangeStart = '';
  14575. WHILE: while (i < glob.length) {
  14576. const c = glob.charAt(i);
  14577. if ((c === '!' || c === '^') && i === pos + 1) {
  14578. negate = true;
  14579. i++;
  14580. continue;
  14581. }
  14582. if (c === ']' && sawStart && !escaping) {
  14583. endPos = i + 1;
  14584. break;
  14585. }
  14586. sawStart = true;
  14587. if (c === '\\') {
  14588. if (!escaping) {
  14589. escaping = true;
  14590. i++;
  14591. continue;
  14592. }
  14593. // escaped \ char, fall through and treat like normal char
  14594. }
  14595. if (c === '[' && !escaping) {
  14596. // either a posix class, a collation equivalent, or just a [
  14597. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  14598. if (glob.startsWith(cls, i)) {
  14599. // invalid, [a-[] is fine, but not [a-[:alpha]]
  14600. if (rangeStart) {
  14601. return ['$.', false, glob.length - pos, true];
  14602. }
  14603. i += cls.length;
  14604. if (neg)
  14605. negs.push(unip);
  14606. else
  14607. ranges.push(unip);
  14608. uflag = uflag || u;
  14609. continue WHILE;
  14610. }
  14611. }
  14612. }
  14613. // now it's just a normal character, effectively
  14614. escaping = false;
  14615. if (rangeStart) {
  14616. // throw this range away if it's not valid, but others
  14617. // can still match.
  14618. if (c > rangeStart) {
  14619. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  14620. }
  14621. else if (c === rangeStart) {
  14622. ranges.push(braceEscape(c));
  14623. }
  14624. rangeStart = '';
  14625. i++;
  14626. continue;
  14627. }
  14628. // now might be the start of a range.
  14629. // can be either c-d or c-] or c<more...>] or c] at this point
  14630. if (glob.startsWith('-]', i + 1)) {
  14631. ranges.push(braceEscape(c + '-'));
  14632. i += 2;
  14633. continue;
  14634. }
  14635. if (glob.startsWith('-', i + 1)) {
  14636. rangeStart = c;
  14637. i += 2;
  14638. continue;
  14639. }
  14640. // not the start of a range, just a single character
  14641. ranges.push(braceEscape(c));
  14642. i++;
  14643. }
  14644. if (endPos < i) {
  14645. // didn't see the end of the class, not a valid class,
  14646. // but might still be valid as a literal match.
  14647. return ['', false, 0, false];
  14648. }
  14649. // if we got no ranges and no negates, then we have a range that
  14650. // cannot possibly match anything, and that poisons the whole glob
  14651. if (!ranges.length && !negs.length) {
  14652. return ['$.', false, glob.length - pos, true];
  14653. }
  14654. // if we got one positive range, and it's a single character, then that's
  14655. // not actually a magic pattern, it's just that one literal character.
  14656. // we should not treat that as "magic", we should just return the literal
  14657. // character. [_] is a perfectly valid way to escape glob magic chars.
  14658. if (negs.length === 0 &&
  14659. ranges.length === 1 &&
  14660. /^\\?.$/.test(ranges[0]) &&
  14661. !negate) {
  14662. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  14663. return [regexpEscape(r), false, endPos - pos, false];
  14664. }
  14665. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  14666. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  14667. const comb = ranges.length && negs.length
  14668. ? '(' + sranges + '|' + snegs + ')'
  14669. : ranges.length
  14670. ? sranges
  14671. : snegs;
  14672. return [comb, uflag, endPos - pos, true];
  14673. };
  14674. /**
  14675. * Un-escape a string that has been escaped with {@link escape}.
  14676. *
  14677. * If the {@link windowsPathsNoEscape} option is used, then square-brace
  14678. * escapes are removed, but not backslash escapes. For example, it will turn
  14679. * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
  14680. * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
  14681. *
  14682. * When `windowsPathsNoEscape` is not set, then both brace escapes and
  14683. * backslash escapes are removed.
  14684. *
  14685. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  14686. * or unescaped.
  14687. */
  14688. const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
  14689. return windowsPathsNoEscape
  14690. ? s.replace(/\[([^\/\\])\]/g, '$1')
  14691. : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
  14692. };
  14693. // parse a single path portion
  14694. const types = new Set(['!', '?', '+', '*', '@']);
  14695. const isExtglobType = (c) => types.has(c);
  14696. // Patterns that get prepended to bind to the start of either the
  14697. // entire string, or just a single path portion, to prevent dots
  14698. // and/or traversal patterns, when needed.
  14699. // Exts don't need the ^ or / bit, because the root binds that already.
  14700. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  14701. const startNoDot = '(?!\\.)';
  14702. // characters that indicate a start of pattern needs the "no dots" bit,
  14703. // because a dot *might* be matched. ( is not in the list, because in
  14704. // the case of a child extglob, it will handle the prevention itself.
  14705. const addPatternStart = new Set(['[', '.']);
  14706. // cases where traversal is A-OK, no dot prevention needed
  14707. const justDots = new Set(['..', '.']);
  14708. const reSpecials = new Set('().*{}+?[]^$\\!');
  14709. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  14710. // any single thing other than /
  14711. const qmark$1 = '[^/]';
  14712. // * => any number of characters
  14713. const star$1 = qmark$1 + '*?';
  14714. // use + when we need to ensure that *something* matches, because the * is
  14715. // the only thing in the path portion.
  14716. const starNoEmpty = qmark$1 + '+?';
  14717. // remove the \ chars that we added if we end up doing a nonmagic compare
  14718. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  14719. class AST {
  14720. type;
  14721. #root;
  14722. #hasMagic;
  14723. #uflag = false;
  14724. #parts = [];
  14725. #parent;
  14726. #parentIndex;
  14727. #negs;
  14728. #filledNegs = false;
  14729. #options;
  14730. #toString;
  14731. // set to true if it's an extglob with no children
  14732. // (which really means one child of '')
  14733. #emptyExt = false;
  14734. constructor(type, parent, options = {}) {
  14735. this.type = type;
  14736. // extglobs are inherently magical
  14737. if (type)
  14738. this.#hasMagic = true;
  14739. this.#parent = parent;
  14740. this.#root = this.#parent ? this.#parent.#root : this;
  14741. this.#options = this.#root === this ? options : this.#root.#options;
  14742. this.#negs = this.#root === this ? [] : this.#root.#negs;
  14743. if (type === '!' && !this.#root.#filledNegs)
  14744. this.#negs.push(this);
  14745. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  14746. }
  14747. get hasMagic() {
  14748. /* c8 ignore start */
  14749. if (this.#hasMagic !== undefined)
  14750. return this.#hasMagic;
  14751. /* c8 ignore stop */
  14752. for (const p of this.#parts) {
  14753. if (typeof p === 'string')
  14754. continue;
  14755. if (p.type || p.hasMagic)
  14756. return (this.#hasMagic = true);
  14757. }
  14758. // note: will be undefined until we generate the regexp src and find out
  14759. return this.#hasMagic;
  14760. }
  14761. // reconstructs the pattern
  14762. toString() {
  14763. if (this.#toString !== undefined)
  14764. return this.#toString;
  14765. if (!this.type) {
  14766. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  14767. }
  14768. else {
  14769. return (this.#toString =
  14770. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  14771. }
  14772. }
  14773. #fillNegs() {
  14774. /* c8 ignore start */
  14775. if (this !== this.#root)
  14776. throw new Error('should only call on root');
  14777. if (this.#filledNegs)
  14778. return this;
  14779. /* c8 ignore stop */
  14780. // call toString() once to fill this out
  14781. this.toString();
  14782. this.#filledNegs = true;
  14783. let n;
  14784. while ((n = this.#negs.pop())) {
  14785. if (n.type !== '!')
  14786. continue;
  14787. // walk up the tree, appending everthing that comes AFTER parentIndex
  14788. let p = n;
  14789. let pp = p.#parent;
  14790. while (pp) {
  14791. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  14792. for (const part of n.#parts) {
  14793. /* c8 ignore start */
  14794. if (typeof part === 'string') {
  14795. throw new Error('string part in extglob AST??');
  14796. }
  14797. /* c8 ignore stop */
  14798. part.copyIn(pp.#parts[i]);
  14799. }
  14800. }
  14801. p = pp;
  14802. pp = p.#parent;
  14803. }
  14804. }
  14805. return this;
  14806. }
  14807. push(...parts) {
  14808. for (const p of parts) {
  14809. if (p === '')
  14810. continue;
  14811. /* c8 ignore start */
  14812. if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
  14813. throw new Error('invalid part: ' + p);
  14814. }
  14815. /* c8 ignore stop */
  14816. this.#parts.push(p);
  14817. }
  14818. }
  14819. toJSON() {
  14820. const ret = this.type === null
  14821. ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
  14822. : [this.type, ...this.#parts.map(p => p.toJSON())];
  14823. if (this.isStart() && !this.type)
  14824. ret.unshift([]);
  14825. if (this.isEnd() &&
  14826. (this === this.#root ||
  14827. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  14828. ret.push({});
  14829. }
  14830. return ret;
  14831. }
  14832. isStart() {
  14833. if (this.#root === this)
  14834. return true;
  14835. // if (this.type) return !!this.#parent?.isStart()
  14836. if (!this.#parent?.isStart())
  14837. return false;
  14838. if (this.#parentIndex === 0)
  14839. return true;
  14840. // if everything AHEAD of this is a negation, then it's still the "start"
  14841. const p = this.#parent;
  14842. for (let i = 0; i < this.#parentIndex; i++) {
  14843. const pp = p.#parts[i];
  14844. if (!(pp instanceof AST && pp.type === '!')) {
  14845. return false;
  14846. }
  14847. }
  14848. return true;
  14849. }
  14850. isEnd() {
  14851. if (this.#root === this)
  14852. return true;
  14853. if (this.#parent?.type === '!')
  14854. return true;
  14855. if (!this.#parent?.isEnd())
  14856. return false;
  14857. if (!this.type)
  14858. return this.#parent?.isEnd();
  14859. // if not root, it'll always have a parent
  14860. /* c8 ignore start */
  14861. const pl = this.#parent ? this.#parent.#parts.length : 0;
  14862. /* c8 ignore stop */
  14863. return this.#parentIndex === pl - 1;
  14864. }
  14865. copyIn(part) {
  14866. if (typeof part === 'string')
  14867. this.push(part);
  14868. else
  14869. this.push(part.clone(this));
  14870. }
  14871. clone(parent) {
  14872. const c = new AST(this.type, parent);
  14873. for (const p of this.#parts) {
  14874. c.copyIn(p);
  14875. }
  14876. return c;
  14877. }
  14878. static #parseAST(str, ast, pos, opt) {
  14879. let escaping = false;
  14880. let inBrace = false;
  14881. let braceStart = -1;
  14882. let braceNeg = false;
  14883. if (ast.type === null) {
  14884. // outside of a extglob, append until we find a start
  14885. let i = pos;
  14886. let acc = '';
  14887. while (i < str.length) {
  14888. const c = str.charAt(i++);
  14889. // still accumulate escapes at this point, but we do ignore
  14890. // starts that are escaped
  14891. if (escaping || c === '\\') {
  14892. escaping = !escaping;
  14893. acc += c;
  14894. continue;
  14895. }
  14896. if (inBrace) {
  14897. if (i === braceStart + 1) {
  14898. if (c === '^' || c === '!') {
  14899. braceNeg = true;
  14900. }
  14901. }
  14902. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  14903. inBrace = false;
  14904. }
  14905. acc += c;
  14906. continue;
  14907. }
  14908. else if (c === '[') {
  14909. inBrace = true;
  14910. braceStart = i;
  14911. braceNeg = false;
  14912. acc += c;
  14913. continue;
  14914. }
  14915. if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
  14916. ast.push(acc);
  14917. acc = '';
  14918. const ext = new AST(c, ast);
  14919. i = AST.#parseAST(str, ext, i, opt);
  14920. ast.push(ext);
  14921. continue;
  14922. }
  14923. acc += c;
  14924. }
  14925. ast.push(acc);
  14926. return i;
  14927. }
  14928. // some kind of extglob, pos is at the (
  14929. // find the next | or )
  14930. let i = pos + 1;
  14931. let part = new AST(null, ast);
  14932. const parts = [];
  14933. let acc = '';
  14934. while (i < str.length) {
  14935. const c = str.charAt(i++);
  14936. // still accumulate escapes at this point, but we do ignore
  14937. // starts that are escaped
  14938. if (escaping || c === '\\') {
  14939. escaping = !escaping;
  14940. acc += c;
  14941. continue;
  14942. }
  14943. if (inBrace) {
  14944. if (i === braceStart + 1) {
  14945. if (c === '^' || c === '!') {
  14946. braceNeg = true;
  14947. }
  14948. }
  14949. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  14950. inBrace = false;
  14951. }
  14952. acc += c;
  14953. continue;
  14954. }
  14955. else if (c === '[') {
  14956. inBrace = true;
  14957. braceStart = i;
  14958. braceNeg = false;
  14959. acc += c;
  14960. continue;
  14961. }
  14962. if (isExtglobType(c) && str.charAt(i) === '(') {
  14963. part.push(acc);
  14964. acc = '';
  14965. const ext = new AST(c, part);
  14966. part.push(ext);
  14967. i = AST.#parseAST(str, ext, i, opt);
  14968. continue;
  14969. }
  14970. if (c === '|') {
  14971. part.push(acc);
  14972. acc = '';
  14973. parts.push(part);
  14974. part = new AST(null, ast);
  14975. continue;
  14976. }
  14977. if (c === ')') {
  14978. if (acc === '' && ast.#parts.length === 0) {
  14979. ast.#emptyExt = true;
  14980. }
  14981. part.push(acc);
  14982. acc = '';
  14983. ast.push(...parts, part);
  14984. return i;
  14985. }
  14986. acc += c;
  14987. }
  14988. // unfinished extglob
  14989. // if we got here, it was a malformed extglob! not an extglob, but
  14990. // maybe something else in there.
  14991. ast.type = null;
  14992. ast.#hasMagic = undefined;
  14993. ast.#parts = [str.substring(pos - 1)];
  14994. return i;
  14995. }
  14996. static fromGlob(pattern, options = {}) {
  14997. const ast = new AST(null, undefined, options);
  14998. AST.#parseAST(pattern, ast, 0, options);
  14999. return ast;
  15000. }
  15001. // returns the regular expression if there's magic, or the unescaped
  15002. // string if not.
  15003. toMMPattern() {
  15004. // should only be called on root
  15005. /* c8 ignore start */
  15006. if (this !== this.#root)
  15007. return this.#root.toMMPattern();
  15008. /* c8 ignore stop */
  15009. const glob = this.toString();
  15010. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  15011. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  15012. // still need a regular expression if we have to case-insensitively
  15013. // match capital/lowercase characters.
  15014. const anyMagic = hasMagic ||
  15015. this.#hasMagic ||
  15016. (this.#options.nocase &&
  15017. !this.#options.nocaseMagicOnly &&
  15018. glob.toUpperCase() !== glob.toLowerCase());
  15019. if (!anyMagic) {
  15020. return body;
  15021. }
  15022. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  15023. return Object.assign(new RegExp(`^${re}$`, flags), {
  15024. _src: re,
  15025. _glob: glob,
  15026. });
  15027. }
  15028. get options() {
  15029. return this.#options;
  15030. }
  15031. // returns the string match, the regexp source, whether there's magic
  15032. // in the regexp (so a regular expression is required) and whether or
  15033. // not the uflag is needed for the regular expression (for posix classes)
  15034. // TODO: instead of injecting the start/end at this point, just return
  15035. // the BODY of the regexp, along with the start/end portions suitable
  15036. // for binding the start/end in either a joined full-path makeRe context
  15037. // (where we bind to (^|/), or a standalone matchPart context (where
  15038. // we bind to ^, and not /). Otherwise slashes get duped!
  15039. //
  15040. // In part-matching mode, the start is:
  15041. // - if not isStart: nothing
  15042. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  15043. // - if dots allowed or not possible: ^
  15044. // - if dots possible and not allowed: ^(?!\.)
  15045. // end is:
  15046. // - if not isEnd(): nothing
  15047. // - else: $
  15048. //
  15049. // In full-path matching mode, we put the slash at the START of the
  15050. // pattern, so start is:
  15051. // - if first pattern: same as part-matching mode
  15052. // - if not isStart(): nothing
  15053. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  15054. // - if dots allowed or not possible: /
  15055. // - if dots possible and not allowed: /(?!\.)
  15056. // end is:
  15057. // - if last pattern, same as part-matching mode
  15058. // - else nothing
  15059. //
  15060. // Always put the (?:$|/) on negated tails, though, because that has to be
  15061. // there to bind the end of the negated pattern portion, and it's easier to
  15062. // just stick it in now rather than try to inject it later in the middle of
  15063. // the pattern.
  15064. //
  15065. // We can just always return the same end, and leave it up to the caller
  15066. // to know whether it's going to be used joined or in parts.
  15067. // And, if the start is adjusted slightly, can do the same there:
  15068. // - if not isStart: nothing
  15069. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  15070. // - if dots allowed or not possible: (?:/|^)
  15071. // - if dots possible and not allowed: (?:/|^)(?!\.)
  15072. //
  15073. // But it's better to have a simpler binding without a conditional, for
  15074. // performance, so probably better to return both start options.
  15075. //
  15076. // Then the caller just ignores the end if it's not the first pattern,
  15077. // and the start always gets applied.
  15078. //
  15079. // But that's always going to be $ if it's the ending pattern, or nothing,
  15080. // so the caller can just attach $ at the end of the pattern when building.
  15081. //
  15082. // So the todo is:
  15083. // - better detect what kind of start is needed
  15084. // - return both flavors of starting pattern
  15085. // - attach $ at the end of the pattern when creating the actual RegExp
  15086. //
  15087. // Ah, but wait, no, that all only applies to the root when the first pattern
  15088. // is not an extglob. If the first pattern IS an extglob, then we need all
  15089. // that dot prevention biz to live in the extglob portions, because eg
  15090. // +(*|.x*) can match .xy but not .yx.
  15091. //
  15092. // So, return the two flavors if it's #root and the first child is not an
  15093. // AST, otherwise leave it to the child AST to handle it, and there,
  15094. // use the (?:^|/) style of start binding.
  15095. //
  15096. // Even simplified further:
  15097. // - Since the start for a join is eg /(?!\.) and the start for a part
  15098. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  15099. // or start or whatever) and prepend ^ or / at the Regexp construction.
  15100. toRegExpSource(allowDot) {
  15101. const dot = allowDot ?? !!this.#options.dot;
  15102. if (this.#root === this)
  15103. this.#fillNegs();
  15104. if (!this.type) {
  15105. const noEmpty = this.isStart() && this.isEnd();
  15106. const src = this.#parts
  15107. .map(p => {
  15108. const [re, _, hasMagic, uflag] = typeof p === 'string'
  15109. ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
  15110. : p.toRegExpSource(allowDot);
  15111. this.#hasMagic = this.#hasMagic || hasMagic;
  15112. this.#uflag = this.#uflag || uflag;
  15113. return re;
  15114. })
  15115. .join('');
  15116. let start = '';
  15117. if (this.isStart()) {
  15118. if (typeof this.#parts[0] === 'string') {
  15119. // this is the string that will match the start of the pattern,
  15120. // so we need to protect against dots and such.
  15121. // '.' and '..' cannot match unless the pattern is that exactly,
  15122. // even if it starts with . or dot:true is set.
  15123. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  15124. if (!dotTravAllowed) {
  15125. const aps = addPatternStart;
  15126. // check if we have a possibility of matching . or ..,
  15127. // and prevent that.
  15128. const needNoTrav =
  15129. // dots are allowed, and the pattern starts with [ or .
  15130. (dot && aps.has(src.charAt(0))) ||
  15131. // the pattern starts with \., and then [ or .
  15132. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  15133. // the pattern starts with \.\., and then [ or .
  15134. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  15135. // no need to prevent dots if it can't match a dot, or if a
  15136. // sub-pattern will be preventing it anyway.
  15137. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  15138. start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
  15139. }
  15140. }
  15141. }
  15142. // append the "end of path portion" pattern to negation tails
  15143. let end = '';
  15144. if (this.isEnd() &&
  15145. this.#root.#filledNegs &&
  15146. this.#parent?.type === '!') {
  15147. end = '(?:$|\\/)';
  15148. }
  15149. const final = start + src + end;
  15150. return [
  15151. final,
  15152. unescape(src),
  15153. (this.#hasMagic = !!this.#hasMagic),
  15154. this.#uflag,
  15155. ];
  15156. }
  15157. // We need to calculate the body *twice* if it's a repeat pattern
  15158. // at the start, once in nodot mode, then again in dot mode, so a
  15159. // pattern like *(?) can match 'x.y'
  15160. const repeated = this.type === '*' || this.type === '+';
  15161. // some kind of extglob
  15162. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  15163. let body = this.#partsToRegExp(dot);
  15164. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  15165. // invalid extglob, has to at least be *something* present, if it's
  15166. // the entire path portion.
  15167. const s = this.toString();
  15168. this.#parts = [s];
  15169. this.type = null;
  15170. this.#hasMagic = undefined;
  15171. return [s, unescape(this.toString()), false, false];
  15172. }
  15173. // XXX abstract out this map method
  15174. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
  15175. ? ''
  15176. : this.#partsToRegExp(true);
  15177. if (bodyDotAllowed === body) {
  15178. bodyDotAllowed = '';
  15179. }
  15180. if (bodyDotAllowed) {
  15181. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  15182. }
  15183. // an empty !() is exactly equivalent to a starNoEmpty
  15184. let final = '';
  15185. if (this.type === '!' && this.#emptyExt) {
  15186. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  15187. }
  15188. else {
  15189. const close = this.type === '!'
  15190. ? // !() must match something,but !(x) can match ''
  15191. '))' +
  15192. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  15193. star$1 +
  15194. ')'
  15195. : this.type === '@'
  15196. ? ')'
  15197. : this.type === '?'
  15198. ? ')?'
  15199. : this.type === '+' && bodyDotAllowed
  15200. ? ')'
  15201. : this.type === '*' && bodyDotAllowed
  15202. ? `)?`
  15203. : `)${this.type}`;
  15204. final = start + body + close;
  15205. }
  15206. return [
  15207. final,
  15208. unescape(body),
  15209. (this.#hasMagic = !!this.#hasMagic),
  15210. this.#uflag,
  15211. ];
  15212. }
  15213. #partsToRegExp(dot) {
  15214. return this.#parts
  15215. .map(p => {
  15216. // extglob ASTs should only contain parent ASTs
  15217. /* c8 ignore start */
  15218. if (typeof p === 'string') {
  15219. throw new Error('string type in extglob ast??');
  15220. }
  15221. /* c8 ignore stop */
  15222. // can ignore hasMagic, because extglobs are already always magic
  15223. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  15224. this.#uflag = this.#uflag || uflag;
  15225. return re;
  15226. })
  15227. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  15228. .join('|');
  15229. }
  15230. static #parseGlob(glob, hasMagic, noEmpty = false) {
  15231. let escaping = false;
  15232. let re = '';
  15233. let uflag = false;
  15234. for (let i = 0; i < glob.length; i++) {
  15235. const c = glob.charAt(i);
  15236. if (escaping) {
  15237. escaping = false;
  15238. re += (reSpecials.has(c) ? '\\' : '') + c;
  15239. continue;
  15240. }
  15241. if (c === '\\') {
  15242. if (i === glob.length - 1) {
  15243. re += '\\\\';
  15244. }
  15245. else {
  15246. escaping = true;
  15247. }
  15248. continue;
  15249. }
  15250. if (c === '[') {
  15251. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  15252. if (consumed) {
  15253. re += src;
  15254. uflag = uflag || needUflag;
  15255. i += consumed - 1;
  15256. hasMagic = hasMagic || magic;
  15257. continue;
  15258. }
  15259. }
  15260. if (c === '*') {
  15261. if (noEmpty && glob === '*')
  15262. re += starNoEmpty;
  15263. else
  15264. re += star$1;
  15265. hasMagic = true;
  15266. continue;
  15267. }
  15268. if (c === '?') {
  15269. re += qmark$1;
  15270. hasMagic = true;
  15271. continue;
  15272. }
  15273. re += regExpEscape$1(c);
  15274. }
  15275. return [re, unescape(glob), !!hasMagic, uflag];
  15276. }
  15277. }
  15278. /**
  15279. * Escape all magic characters in a glob pattern.
  15280. *
  15281. * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
  15282. * option is used, then characters are escaped by wrapping in `[]`, because
  15283. * a magic character wrapped in a character class can only be satisfied by
  15284. * that exact character. In this mode, `\` is _not_ escaped, because it is
  15285. * not interpreted as a magic character, but instead as a path separator.
  15286. */
  15287. const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
  15288. // don't need to escape +@! because we escape the parens
  15289. // that make those magic, and escaping ! as [!] isn't valid,
  15290. // because [!]] is a valid glob class meaning not ']'.
  15291. return windowsPathsNoEscape
  15292. ? s.replace(/[?*()[\]]/g, '[$&]')
  15293. : s.replace(/[?*()[\]\\]/g, '\\$&');
  15294. };
  15295. const minimatch = (p, pattern, options = {}) => {
  15296. assertValidPattern(pattern);
  15297. // shortcut: comments match nothing.
  15298. if (!options.nocomment && pattern.charAt(0) === '#') {
  15299. return false;
  15300. }
  15301. return new Minimatch(pattern, options).match(p);
  15302. };
  15303. // Optimized checking for the most common glob patterns.
  15304. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  15305. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  15306. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  15307. const starDotExtTestNocase = (ext) => {
  15308. ext = ext.toLowerCase();
  15309. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  15310. };
  15311. const starDotExtTestNocaseDot = (ext) => {
  15312. ext = ext.toLowerCase();
  15313. return (f) => f.toLowerCase().endsWith(ext);
  15314. };
  15315. const starDotStarRE = /^\*+\.\*+$/;
  15316. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  15317. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  15318. const dotStarRE = /^\.\*+$/;
  15319. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  15320. const starRE = /^\*+$/;
  15321. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  15322. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  15323. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  15324. const qmarksTestNocase = ([$0, ext = '']) => {
  15325. const noext = qmarksTestNoExt([$0]);
  15326. if (!ext)
  15327. return noext;
  15328. ext = ext.toLowerCase();
  15329. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  15330. };
  15331. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  15332. const noext = qmarksTestNoExtDot([$0]);
  15333. if (!ext)
  15334. return noext;
  15335. ext = ext.toLowerCase();
  15336. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  15337. };
  15338. const qmarksTestDot = ([$0, ext = '']) => {
  15339. const noext = qmarksTestNoExtDot([$0]);
  15340. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  15341. };
  15342. const qmarksTest = ([$0, ext = '']) => {
  15343. const noext = qmarksTestNoExt([$0]);
  15344. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  15345. };
  15346. const qmarksTestNoExt = ([$0]) => {
  15347. const len = $0.length;
  15348. return (f) => f.length === len && !f.startsWith('.');
  15349. };
  15350. const qmarksTestNoExtDot = ([$0]) => {
  15351. const len = $0.length;
  15352. return (f) => f.length === len && f !== '.' && f !== '..';
  15353. };
  15354. /* c8 ignore start */
  15355. const defaultPlatform = (typeof process === 'object' && process
  15356. ? (typeof process.env === 'object' &&
  15357. process.env &&
  15358. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  15359. process.platform
  15360. : 'posix');
  15361. const path = {
  15362. win32: { sep: '\\' },
  15363. posix: { sep: '/' },
  15364. };
  15365. /* c8 ignore stop */
  15366. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  15367. minimatch.sep = sep;
  15368. const GLOBSTAR = Symbol('globstar **');
  15369. minimatch.GLOBSTAR = GLOBSTAR;
  15370. // any single thing other than /
  15371. // don't need to escape / when using new RegExp()
  15372. const qmark = '[^/]';
  15373. // * => any number of characters
  15374. const star = qmark + '*?';
  15375. // ** when dots are allowed. Anything goes, except .. and .
  15376. // not (^ or / followed by one or two dots followed by $ or /),
  15377. // followed by anything, any number of times.
  15378. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  15379. // not a ^ or / followed by a dot,
  15380. // followed by anything, any number of times.
  15381. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  15382. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  15383. minimatch.filter = filter;
  15384. const ext = (a, b = {}) => Object.assign({}, a, b);
  15385. const defaults = (def) => {
  15386. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  15387. return minimatch;
  15388. }
  15389. const orig = minimatch;
  15390. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  15391. return Object.assign(m, {
  15392. Minimatch: class Minimatch extends orig.Minimatch {
  15393. constructor(pattern, options = {}) {
  15394. super(pattern, ext(def, options));
  15395. }
  15396. static defaults(options) {
  15397. return orig.defaults(ext(def, options)).Minimatch;
  15398. }
  15399. },
  15400. AST: class AST extends orig.AST {
  15401. /* c8 ignore start */
  15402. constructor(type, parent, options = {}) {
  15403. super(type, parent, ext(def, options));
  15404. }
  15405. /* c8 ignore stop */
  15406. static fromGlob(pattern, options = {}) {
  15407. return orig.AST.fromGlob(pattern, ext(def, options));
  15408. }
  15409. },
  15410. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  15411. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  15412. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  15413. defaults: (options) => orig.defaults(ext(def, options)),
  15414. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  15415. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  15416. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  15417. sep: orig.sep,
  15418. GLOBSTAR: GLOBSTAR,
  15419. });
  15420. };
  15421. minimatch.defaults = defaults;
  15422. // Brace expansion:
  15423. // a{b,c}d -> abd acd
  15424. // a{b,}c -> abc ac
  15425. // a{0..3}d -> a0d a1d a2d a3d
  15426. // a{b,c{d,e}f}g -> abg acdfg acefg
  15427. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  15428. //
  15429. // Invalid sets are not expanded.
  15430. // a{2..}b -> a{2..}b
  15431. // a{b}c -> a{b}c
  15432. const braceExpand = (pattern, options = {}) => {
  15433. assertValidPattern(pattern);
  15434. // Thanks to Yeting Li <https://github.com/yetingli> for
  15435. // improving this regexp to avoid a ReDOS vulnerability.
  15436. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  15437. // shortcut. no need to expand.
  15438. return [pattern];
  15439. }
  15440. return expand$1(pattern);
  15441. };
  15442. minimatch.braceExpand = braceExpand;
  15443. // parse a component of the expanded set.
  15444. // At this point, no pattern may contain "/" in it
  15445. // so we're going to return a 2d array, where each entry is the full
  15446. // pattern, split on '/', and then turned into a regular expression.
  15447. // A regexp is made at the end which joins each array with an
  15448. // escaped /, and another full one which joins each regexp with |.
  15449. //
  15450. // Following the lead of Bash 4.1, note that "**" only has special meaning
  15451. // when it is the *only* thing in a path portion. Otherwise, any series
  15452. // of * is equivalent to a single *. Globstar behavior is enabled by
  15453. // default, and can be disabled by setting options.noglobstar.
  15454. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  15455. minimatch.makeRe = makeRe;
  15456. const match = (list, pattern, options = {}) => {
  15457. const mm = new Minimatch(pattern, options);
  15458. list = list.filter(f => mm.match(f));
  15459. if (mm.options.nonull && !list.length) {
  15460. list.push(pattern);
  15461. }
  15462. return list;
  15463. };
  15464. minimatch.match = match;
  15465. // replace stuff like \* with *
  15466. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  15467. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  15468. class Minimatch {
  15469. options;
  15470. set;
  15471. pattern;
  15472. windowsPathsNoEscape;
  15473. nonegate;
  15474. negate;
  15475. comment;
  15476. empty;
  15477. preserveMultipleSlashes;
  15478. partial;
  15479. globSet;
  15480. globParts;
  15481. nocase;
  15482. isWindows;
  15483. platform;
  15484. windowsNoMagicRoot;
  15485. regexp;
  15486. constructor(pattern, options = {}) {
  15487. assertValidPattern(pattern);
  15488. options = options || {};
  15489. this.options = options;
  15490. this.pattern = pattern;
  15491. this.platform = options.platform || defaultPlatform;
  15492. this.isWindows = this.platform === 'win32';
  15493. this.windowsPathsNoEscape =
  15494. !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  15495. if (this.windowsPathsNoEscape) {
  15496. this.pattern = this.pattern.replace(/\\/g, '/');
  15497. }
  15498. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  15499. this.regexp = null;
  15500. this.negate = false;
  15501. this.nonegate = !!options.nonegate;
  15502. this.comment = false;
  15503. this.empty = false;
  15504. this.partial = !!options.partial;
  15505. this.nocase = !!this.options.nocase;
  15506. this.windowsNoMagicRoot =
  15507. options.windowsNoMagicRoot !== undefined
  15508. ? options.windowsNoMagicRoot
  15509. : !!(this.isWindows && this.nocase);
  15510. this.globSet = [];
  15511. this.globParts = [];
  15512. this.set = [];
  15513. // make the set of regexps etc.
  15514. this.make();
  15515. }
  15516. hasMagic() {
  15517. if (this.options.magicalBraces && this.set.length > 1) {
  15518. return true;
  15519. }
  15520. for (const pattern of this.set) {
  15521. for (const part of pattern) {
  15522. if (typeof part !== 'string')
  15523. return true;
  15524. }
  15525. }
  15526. return false;
  15527. }
  15528. debug(..._) { }
  15529. make() {
  15530. const pattern = this.pattern;
  15531. const options = this.options;
  15532. // empty patterns and comments match nothing.
  15533. if (!options.nocomment && pattern.charAt(0) === '#') {
  15534. this.comment = true;
  15535. return;
  15536. }
  15537. if (!pattern) {
  15538. this.empty = true;
  15539. return;
  15540. }
  15541. // step 1: figure out negation, etc.
  15542. this.parseNegate();
  15543. // step 2: expand braces
  15544. this.globSet = [...new Set(this.braceExpand())];
  15545. if (options.debug) {
  15546. this.debug = (...args) => console.error(...args);
  15547. }
  15548. this.debug(this.pattern, this.globSet);
  15549. // step 3: now we have a set, so turn each one into a series of
  15550. // path-portion matching patterns.
  15551. // These will be regexps, except in the case of "**", which is
  15552. // set to the GLOBSTAR object for globstar behavior,
  15553. // and will not contain any / characters
  15554. //
  15555. // First, we preprocess to make the glob pattern sets a bit simpler
  15556. // and deduped. There are some perf-killing patterns that can cause
  15557. // problems with a glob walk, but we can simplify them down a bit.
  15558. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  15559. this.globParts = this.preprocess(rawGlobParts);
  15560. this.debug(this.pattern, this.globParts);
  15561. // glob --> regexps
  15562. let set = this.globParts.map((s, _, __) => {
  15563. if (this.isWindows && this.windowsNoMagicRoot) {
  15564. // check if it's a drive or unc path.
  15565. const isUNC = s[0] === '' &&
  15566. s[1] === '' &&
  15567. (s[2] === '?' || !globMagic.test(s[2])) &&
  15568. !globMagic.test(s[3]);
  15569. const isDrive = /^[a-z]:/i.test(s[0]);
  15570. if (isUNC) {
  15571. return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
  15572. }
  15573. else if (isDrive) {
  15574. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  15575. }
  15576. }
  15577. return s.map(ss => this.parse(ss));
  15578. });
  15579. this.debug(this.pattern, set);
  15580. // filter out everything that didn't compile properly.
  15581. this.set = set.filter(s => s.indexOf(false) === -1);
  15582. // do not treat the ? in UNC paths as magic
  15583. if (this.isWindows) {
  15584. for (let i = 0; i < this.set.length; i++) {
  15585. const p = this.set[i];
  15586. if (p[0] === '' &&
  15587. p[1] === '' &&
  15588. this.globParts[i][2] === '?' &&
  15589. typeof p[3] === 'string' &&
  15590. /^[a-z]:$/i.test(p[3])) {
  15591. p[2] = '?';
  15592. }
  15593. }
  15594. }
  15595. this.debug(this.pattern, this.set);
  15596. }
  15597. // various transforms to equivalent pattern sets that are
  15598. // faster to process in a filesystem walk. The goal is to
  15599. // eliminate what we can, and push all ** patterns as far
  15600. // to the right as possible, even if it increases the number
  15601. // of patterns that we have to process.
  15602. preprocess(globParts) {
  15603. // if we're not in globstar mode, then turn all ** into *
  15604. if (this.options.noglobstar) {
  15605. for (let i = 0; i < globParts.length; i++) {
  15606. for (let j = 0; j < globParts[i].length; j++) {
  15607. if (globParts[i][j] === '**') {
  15608. globParts[i][j] = '*';
  15609. }
  15610. }
  15611. }
  15612. }
  15613. const { optimizationLevel = 1 } = this.options;
  15614. if (optimizationLevel >= 2) {
  15615. // aggressive optimization for the purpose of fs walking
  15616. globParts = this.firstPhasePreProcess(globParts);
  15617. globParts = this.secondPhasePreProcess(globParts);
  15618. }
  15619. else if (optimizationLevel >= 1) {
  15620. // just basic optimizations to remove some .. parts
  15621. globParts = this.levelOneOptimize(globParts);
  15622. }
  15623. else {
  15624. // just collapse multiple ** portions into one
  15625. globParts = this.adjascentGlobstarOptimize(globParts);
  15626. }
  15627. return globParts;
  15628. }
  15629. // just get rid of adjascent ** portions
  15630. adjascentGlobstarOptimize(globParts) {
  15631. return globParts.map(parts => {
  15632. let gs = -1;
  15633. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  15634. let i = gs;
  15635. while (parts[i + 1] === '**') {
  15636. i++;
  15637. }
  15638. if (i !== gs) {
  15639. parts.splice(gs, i - gs);
  15640. }
  15641. }
  15642. return parts;
  15643. });
  15644. }
  15645. // get rid of adjascent ** and resolve .. portions
  15646. levelOneOptimize(globParts) {
  15647. return globParts.map(parts => {
  15648. parts = parts.reduce((set, part) => {
  15649. const prev = set[set.length - 1];
  15650. if (part === '**' && prev === '**') {
  15651. return set;
  15652. }
  15653. if (part === '..') {
  15654. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  15655. set.pop();
  15656. return set;
  15657. }
  15658. }
  15659. set.push(part);
  15660. return set;
  15661. }, []);
  15662. return parts.length === 0 ? [''] : parts;
  15663. });
  15664. }
  15665. levelTwoFileOptimize(parts) {
  15666. if (!Array.isArray(parts)) {
  15667. parts = this.slashSplit(parts);
  15668. }
  15669. let didSomething = false;
  15670. do {
  15671. didSomething = false;
  15672. // <pre>/<e>/<rest> -> <pre>/<rest>
  15673. if (!this.preserveMultipleSlashes) {
  15674. for (let i = 1; i < parts.length - 1; i++) {
  15675. const p = parts[i];
  15676. // don't squeeze out UNC patterns
  15677. if (i === 1 && p === '' && parts[0] === '')
  15678. continue;
  15679. if (p === '.' || p === '') {
  15680. didSomething = true;
  15681. parts.splice(i, 1);
  15682. i--;
  15683. }
  15684. }
  15685. if (parts[0] === '.' &&
  15686. parts.length === 2 &&
  15687. (parts[1] === '.' || parts[1] === '')) {
  15688. didSomething = true;
  15689. parts.pop();
  15690. }
  15691. }
  15692. // <pre>/<p>/../<rest> -> <pre>/<rest>
  15693. let dd = 0;
  15694. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  15695. const p = parts[dd - 1];
  15696. if (p && p !== '.' && p !== '..' && p !== '**') {
  15697. didSomething = true;
  15698. parts.splice(dd - 1, 2);
  15699. dd -= 2;
  15700. }
  15701. }
  15702. } while (didSomething);
  15703. return parts.length === 0 ? [''] : parts;
  15704. }
  15705. // First phase: single-pattern processing
  15706. // <pre> is 1 or more portions
  15707. // <rest> is 1 or more portions
  15708. // <p> is any portion other than ., .., '', or **
  15709. // <e> is . or ''
  15710. //
  15711. // **/.. is *brutal* for filesystem walking performance, because
  15712. // it effectively resets the recursive walk each time it occurs,
  15713. // and ** cannot be reduced out by a .. pattern part like a regexp
  15714. // or most strings (other than .., ., and '') can be.
  15715. //
  15716. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  15717. // <pre>/<e>/<rest> -> <pre>/<rest>
  15718. // <pre>/<p>/../<rest> -> <pre>/<rest>
  15719. // **/**/<rest> -> **/<rest>
  15720. //
  15721. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  15722. // this WOULD be allowed if ** did follow symlinks, or * didn't
  15723. firstPhasePreProcess(globParts) {
  15724. let didSomething = false;
  15725. do {
  15726. didSomething = false;
  15727. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  15728. for (let parts of globParts) {
  15729. let gs = -1;
  15730. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  15731. let gss = gs;
  15732. while (parts[gss + 1] === '**') {
  15733. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  15734. gss++;
  15735. }
  15736. // eg, if gs is 2 and gss is 4, that means we have 3 **
  15737. // parts, and can remove 2 of them.
  15738. if (gss > gs) {
  15739. parts.splice(gs + 1, gss - gs);
  15740. }
  15741. let next = parts[gs + 1];
  15742. const p = parts[gs + 2];
  15743. const p2 = parts[gs + 3];
  15744. if (next !== '..')
  15745. continue;
  15746. if (!p ||
  15747. p === '.' ||
  15748. p === '..' ||
  15749. !p2 ||
  15750. p2 === '.' ||
  15751. p2 === '..') {
  15752. continue;
  15753. }
  15754. didSomething = true;
  15755. // edit parts in place, and push the new one
  15756. parts.splice(gs, 1);
  15757. const other = parts.slice(0);
  15758. other[gs] = '**';
  15759. globParts.push(other);
  15760. gs--;
  15761. }
  15762. // <pre>/<e>/<rest> -> <pre>/<rest>
  15763. if (!this.preserveMultipleSlashes) {
  15764. for (let i = 1; i < parts.length - 1; i++) {
  15765. const p = parts[i];
  15766. // don't squeeze out UNC patterns
  15767. if (i === 1 && p === '' && parts[0] === '')
  15768. continue;
  15769. if (p === '.' || p === '') {
  15770. didSomething = true;
  15771. parts.splice(i, 1);
  15772. i--;
  15773. }
  15774. }
  15775. if (parts[0] === '.' &&
  15776. parts.length === 2 &&
  15777. (parts[1] === '.' || parts[1] === '')) {
  15778. didSomething = true;
  15779. parts.pop();
  15780. }
  15781. }
  15782. // <pre>/<p>/../<rest> -> <pre>/<rest>
  15783. let dd = 0;
  15784. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  15785. const p = parts[dd - 1];
  15786. if (p && p !== '.' && p !== '..' && p !== '**') {
  15787. didSomething = true;
  15788. const needDot = dd === 1 && parts[dd + 1] === '**';
  15789. const splin = needDot ? ['.'] : [];
  15790. parts.splice(dd - 1, 2, ...splin);
  15791. if (parts.length === 0)
  15792. parts.push('');
  15793. dd -= 2;
  15794. }
  15795. }
  15796. }
  15797. } while (didSomething);
  15798. return globParts;
  15799. }
  15800. // second phase: multi-pattern dedupes
  15801. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  15802. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  15803. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  15804. //
  15805. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  15806. // ^-- not valid because ** doens't follow symlinks
  15807. secondPhasePreProcess(globParts) {
  15808. for (let i = 0; i < globParts.length - 1; i++) {
  15809. for (let j = i + 1; j < globParts.length; j++) {
  15810. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  15811. if (matched) {
  15812. globParts[i] = [];
  15813. globParts[j] = matched;
  15814. break;
  15815. }
  15816. }
  15817. }
  15818. return globParts.filter(gs => gs.length);
  15819. }
  15820. partsMatch(a, b, emptyGSMatch = false) {
  15821. let ai = 0;
  15822. let bi = 0;
  15823. let result = [];
  15824. let which = '';
  15825. while (ai < a.length && bi < b.length) {
  15826. if (a[ai] === b[bi]) {
  15827. result.push(which === 'b' ? b[bi] : a[ai]);
  15828. ai++;
  15829. bi++;
  15830. }
  15831. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  15832. result.push(a[ai]);
  15833. ai++;
  15834. }
  15835. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  15836. result.push(b[bi]);
  15837. bi++;
  15838. }
  15839. else if (a[ai] === '*' &&
  15840. b[bi] &&
  15841. (this.options.dot || !b[bi].startsWith('.')) &&
  15842. b[bi] !== '**') {
  15843. if (which === 'b')
  15844. return false;
  15845. which = 'a';
  15846. result.push(a[ai]);
  15847. ai++;
  15848. bi++;
  15849. }
  15850. else if (b[bi] === '*' &&
  15851. a[ai] &&
  15852. (this.options.dot || !a[ai].startsWith('.')) &&
  15853. a[ai] !== '**') {
  15854. if (which === 'a')
  15855. return false;
  15856. which = 'b';
  15857. result.push(b[bi]);
  15858. ai++;
  15859. bi++;
  15860. }
  15861. else {
  15862. return false;
  15863. }
  15864. }
  15865. // if we fall out of the loop, it means they two are identical
  15866. // as long as their lengths match
  15867. return a.length === b.length && result;
  15868. }
  15869. parseNegate() {
  15870. if (this.nonegate)
  15871. return;
  15872. const pattern = this.pattern;
  15873. let negate = false;
  15874. let negateOffset = 0;
  15875. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  15876. negate = !negate;
  15877. negateOffset++;
  15878. }
  15879. if (negateOffset)
  15880. this.pattern = pattern.slice(negateOffset);
  15881. this.negate = negate;
  15882. }
  15883. // set partial to true to test if, for example,
  15884. // "/a/b" matches the start of "/*/b/*/d"
  15885. // Partial means, if you run out of file before you run
  15886. // out of pattern, then that's fine, as long as all
  15887. // the parts match.
  15888. matchOne(file, pattern, partial = false) {
  15889. const options = this.options;
  15890. // UNC paths like //?/X:/... can match X:/... and vice versa
  15891. // Drive letters in absolute drive or unc paths are always compared
  15892. // case-insensitively.
  15893. if (this.isWindows) {
  15894. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  15895. const fileUNC = !fileDrive &&
  15896. file[0] === '' &&
  15897. file[1] === '' &&
  15898. file[2] === '?' &&
  15899. /^[a-z]:$/i.test(file[3]);
  15900. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  15901. const patternUNC = !patternDrive &&
  15902. pattern[0] === '' &&
  15903. pattern[1] === '' &&
  15904. pattern[2] === '?' &&
  15905. typeof pattern[3] === 'string' &&
  15906. /^[a-z]:$/i.test(pattern[3]);
  15907. const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
  15908. const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
  15909. if (typeof fdi === 'number' && typeof pdi === 'number') {
  15910. const [fd, pd] = [file[fdi], pattern[pdi]];
  15911. if (fd.toLowerCase() === pd.toLowerCase()) {
  15912. pattern[pdi] = fd;
  15913. if (pdi > fdi) {
  15914. pattern = pattern.slice(pdi);
  15915. }
  15916. else if (fdi > pdi) {
  15917. file = file.slice(fdi);
  15918. }
  15919. }
  15920. }
  15921. }
  15922. // resolve and reduce . and .. portions in the file as well.
  15923. // dont' need to do the second phase, because it's only one string[]
  15924. const { optimizationLevel = 1 } = this.options;
  15925. if (optimizationLevel >= 2) {
  15926. file = this.levelTwoFileOptimize(file);
  15927. }
  15928. this.debug('matchOne', this, { file, pattern });
  15929. this.debug('matchOne', file.length, pattern.length);
  15930. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  15931. this.debug('matchOne loop');
  15932. var p = pattern[pi];
  15933. var f = file[fi];
  15934. this.debug(pattern, p, f);
  15935. // should be impossible.
  15936. // some invalid regexp stuff in the set.
  15937. /* c8 ignore start */
  15938. if (p === false) {
  15939. return false;
  15940. }
  15941. /* c8 ignore stop */
  15942. if (p === GLOBSTAR) {
  15943. this.debug('GLOBSTAR', [pattern, p, f]);
  15944. // "**"
  15945. // a/**/b/**/c would match the following:
  15946. // a/b/x/y/z/c
  15947. // a/x/y/z/b/c
  15948. // a/b/x/b/x/c
  15949. // a/b/c
  15950. // To do this, take the rest of the pattern after
  15951. // the **, and see if it would match the file remainder.
  15952. // If so, return success.
  15953. // If not, the ** "swallows" a segment, and try again.
  15954. // This is recursively awful.
  15955. //
  15956. // a/**/b/**/c matching a/b/x/y/z/c
  15957. // - a matches a
  15958. // - doublestar
  15959. // - matchOne(b/x/y/z/c, b/**/c)
  15960. // - b matches b
  15961. // - doublestar
  15962. // - matchOne(x/y/z/c, c) -> no
  15963. // - matchOne(y/z/c, c) -> no
  15964. // - matchOne(z/c, c) -> no
  15965. // - matchOne(c, c) yes, hit
  15966. var fr = fi;
  15967. var pr = pi + 1;
  15968. if (pr === pl) {
  15969. this.debug('** at the end');
  15970. // a ** at the end will just swallow the rest.
  15971. // We have found a match.
  15972. // however, it will not swallow /.x, unless
  15973. // options.dot is set.
  15974. // . and .. are *never* matched by **, for explosively
  15975. // exponential reasons.
  15976. for (; fi < fl; fi++) {
  15977. if (file[fi] === '.' ||
  15978. file[fi] === '..' ||
  15979. (!options.dot && file[fi].charAt(0) === '.'))
  15980. return false;
  15981. }
  15982. return true;
  15983. }
  15984. // ok, let's see if we can swallow whatever we can.
  15985. while (fr < fl) {
  15986. var swallowee = file[fr];
  15987. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  15988. // XXX remove this slice. Just pass the start index.
  15989. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  15990. this.debug('globstar found match!', fr, fl, swallowee);
  15991. // found a match.
  15992. return true;
  15993. }
  15994. else {
  15995. // can't swallow "." or ".." ever.
  15996. // can only swallow ".foo" when explicitly asked.
  15997. if (swallowee === '.' ||
  15998. swallowee === '..' ||
  15999. (!options.dot && swallowee.charAt(0) === '.')) {
  16000. this.debug('dot detected!', file, fr, pattern, pr);
  16001. break;
  16002. }
  16003. // ** swallows a segment, and continue.
  16004. this.debug('globstar swallow a segment, and continue');
  16005. fr++;
  16006. }
  16007. }
  16008. // no match was found.
  16009. // However, in partial mode, we can't say this is necessarily over.
  16010. /* c8 ignore start */
  16011. if (partial) {
  16012. // ran out of file
  16013. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  16014. if (fr === fl) {
  16015. return true;
  16016. }
  16017. }
  16018. /* c8 ignore stop */
  16019. return false;
  16020. }
  16021. // something other than **
  16022. // non-magic patterns just have to match exactly
  16023. // patterns with magic have been turned into regexps.
  16024. let hit;
  16025. if (typeof p === 'string') {
  16026. hit = f === p;
  16027. this.debug('string match', p, f, hit);
  16028. }
  16029. else {
  16030. hit = p.test(f);
  16031. this.debug('pattern match', p, f, hit);
  16032. }
  16033. if (!hit)
  16034. return false;
  16035. }
  16036. // Note: ending in / means that we'll get a final ""
  16037. // at the end of the pattern. This can only match a
  16038. // corresponding "" at the end of the file.
  16039. // If the file ends in /, then it can only match a
  16040. // a pattern that ends in /, unless the pattern just
  16041. // doesn't have any more for it. But, a/b/ should *not*
  16042. // match "a/b/*", even though "" matches against the
  16043. // [^/]*? pattern, except in partial mode, where it might
  16044. // simply not be reached yet.
  16045. // However, a/b/ should still satisfy a/*
  16046. // now either we fell off the end of the pattern, or we're done.
  16047. if (fi === fl && pi === pl) {
  16048. // ran out of pattern and filename at the same time.
  16049. // an exact hit!
  16050. return true;
  16051. }
  16052. else if (fi === fl) {
  16053. // ran out of file, but still had pattern left.
  16054. // this is ok if we're doing the match as part of
  16055. // a glob fs traversal.
  16056. return partial;
  16057. }
  16058. else if (pi === pl) {
  16059. // ran out of pattern, still have file left.
  16060. // this is only acceptable if we're on the very last
  16061. // empty segment of a file with a trailing slash.
  16062. // a/* should match a/b/
  16063. return fi === fl - 1 && file[fi] === '';
  16064. /* c8 ignore start */
  16065. }
  16066. else {
  16067. // should be unreachable.
  16068. throw new Error('wtf?');
  16069. }
  16070. /* c8 ignore stop */
  16071. }
  16072. braceExpand() {
  16073. return braceExpand(this.pattern, this.options);
  16074. }
  16075. parse(pattern) {
  16076. assertValidPattern(pattern);
  16077. const options = this.options;
  16078. // shortcuts
  16079. if (pattern === '**')
  16080. return GLOBSTAR;
  16081. if (pattern === '')
  16082. return '';
  16083. // far and away, the most common glob pattern parts are
  16084. // *, *.*, and *.<ext> Add a fast check method for those.
  16085. let m;
  16086. let fastTest = null;
  16087. if ((m = pattern.match(starRE))) {
  16088. fastTest = options.dot ? starTestDot : starTest;
  16089. }
  16090. else if ((m = pattern.match(starDotExtRE))) {
  16091. fastTest = (options.nocase
  16092. ? options.dot
  16093. ? starDotExtTestNocaseDot
  16094. : starDotExtTestNocase
  16095. : options.dot
  16096. ? starDotExtTestDot
  16097. : starDotExtTest)(m[1]);
  16098. }
  16099. else if ((m = pattern.match(qmarksRE))) {
  16100. fastTest = (options.nocase
  16101. ? options.dot
  16102. ? qmarksTestNocaseDot
  16103. : qmarksTestNocase
  16104. : options.dot
  16105. ? qmarksTestDot
  16106. : qmarksTest)(m);
  16107. }
  16108. else if ((m = pattern.match(starDotStarRE))) {
  16109. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  16110. }
  16111. else if ((m = pattern.match(dotStarRE))) {
  16112. fastTest = dotStarTest;
  16113. }
  16114. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  16115. if (fastTest && typeof re === 'object') {
  16116. // Avoids overriding in frozen environments
  16117. Reflect.defineProperty(re, 'test', { value: fastTest });
  16118. }
  16119. return re;
  16120. }
  16121. makeRe() {
  16122. if (this.regexp || this.regexp === false)
  16123. return this.regexp;
  16124. // at this point, this.set is a 2d array of partial
  16125. // pattern strings, or "**".
  16126. //
  16127. // It's better to use .match(). This function shouldn't
  16128. // be used, really, but it's pretty convenient sometimes,
  16129. // when you just want to work with a regex.
  16130. const set = this.set;
  16131. if (!set.length) {
  16132. this.regexp = false;
  16133. return this.regexp;
  16134. }
  16135. const options = this.options;
  16136. const twoStar = options.noglobstar
  16137. ? star
  16138. : options.dot
  16139. ? twoStarDot
  16140. : twoStarNoDot;
  16141. const flags = new Set(options.nocase ? ['i'] : []);
  16142. // regexpify non-globstar patterns
  16143. // if ** is only item, then we just do one twoStar
  16144. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  16145. // if ** is last, append (\/twoStar|) to previous
  16146. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  16147. // then filter out GLOBSTAR symbols
  16148. let re = set
  16149. .map(pattern => {
  16150. const pp = pattern.map(p => {
  16151. if (p instanceof RegExp) {
  16152. for (const f of p.flags.split(''))
  16153. flags.add(f);
  16154. }
  16155. return typeof p === 'string'
  16156. ? regExpEscape(p)
  16157. : p === GLOBSTAR
  16158. ? GLOBSTAR
  16159. : p._src;
  16160. });
  16161. pp.forEach((p, i) => {
  16162. const next = pp[i + 1];
  16163. const prev = pp[i - 1];
  16164. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  16165. return;
  16166. }
  16167. if (prev === undefined) {
  16168. if (next !== undefined && next !== GLOBSTAR) {
  16169. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  16170. }
  16171. else {
  16172. pp[i] = twoStar;
  16173. }
  16174. }
  16175. else if (next === undefined) {
  16176. pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
  16177. }
  16178. else if (next !== GLOBSTAR) {
  16179. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  16180. pp[i + 1] = GLOBSTAR;
  16181. }
  16182. });
  16183. return pp.filter(p => p !== GLOBSTAR).join('/');
  16184. })
  16185. .join('|');
  16186. // need to wrap in parens if we had more than one thing with |,
  16187. // otherwise only the first will be anchored to ^ and the last to $
  16188. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  16189. // must match entire pattern
  16190. // ending in a * or ** will make it less strict.
  16191. re = '^' + open + re + close + '$';
  16192. // can match anything, as long as it's not this.
  16193. if (this.negate)
  16194. re = '^(?!' + re + ').+$';
  16195. try {
  16196. this.regexp = new RegExp(re, [...flags].join(''));
  16197. /* c8 ignore start */
  16198. }
  16199. catch (ex) {
  16200. // should be impossible
  16201. this.regexp = false;
  16202. }
  16203. /* c8 ignore stop */
  16204. return this.regexp;
  16205. }
  16206. slashSplit(p) {
  16207. // if p starts with // on windows, we preserve that
  16208. // so that UNC paths aren't broken. Otherwise, any number of
  16209. // / characters are coalesced into one, unless
  16210. // preserveMultipleSlashes is set to true.
  16211. if (this.preserveMultipleSlashes) {
  16212. return p.split('/');
  16213. }
  16214. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  16215. // add an extra '' for the one we lose
  16216. return ['', ...p.split(/\/+/)];
  16217. }
  16218. else {
  16219. return p.split(/\/+/);
  16220. }
  16221. }
  16222. match(f, partial = this.partial) {
  16223. this.debug('match', f, this.pattern);
  16224. // short-circuit in the case of busted things.
  16225. // comments, etc.
  16226. if (this.comment) {
  16227. return false;
  16228. }
  16229. if (this.empty) {
  16230. return f === '';
  16231. }
  16232. if (f === '/' && partial) {
  16233. return true;
  16234. }
  16235. const options = this.options;
  16236. // windows: need to use /, not \
  16237. if (this.isWindows) {
  16238. f = f.split('\\').join('/');
  16239. }
  16240. // treat the test path as a set of pathparts.
  16241. const ff = this.slashSplit(f);
  16242. this.debug(this.pattern, 'split', ff);
  16243. // just ONE of the pattern sets in this.set needs to match
  16244. // in order for it to be valid. If negating, then just one
  16245. // match means that we have failed.
  16246. // Either way, return on the first hit.
  16247. const set = this.set;
  16248. this.debug(this.pattern, 'set', set);
  16249. // Find the basename of the path by looking for the last non-empty segment
  16250. let filename = ff[ff.length - 1];
  16251. if (!filename) {
  16252. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  16253. filename = ff[i];
  16254. }
  16255. }
  16256. for (let i = 0; i < set.length; i++) {
  16257. const pattern = set[i];
  16258. let file = ff;
  16259. if (options.matchBase && pattern.length === 1) {
  16260. file = [filename];
  16261. }
  16262. const hit = this.matchOne(file, pattern, partial);
  16263. if (hit) {
  16264. if (options.flipNegate) {
  16265. return true;
  16266. }
  16267. return !this.negate;
  16268. }
  16269. }
  16270. // didn't get any hits. this is success if it's a negative
  16271. // pattern, failure otherwise.
  16272. if (options.flipNegate) {
  16273. return false;
  16274. }
  16275. return this.negate;
  16276. }
  16277. static defaults(def) {
  16278. return minimatch.defaults(def).Minimatch;
  16279. }
  16280. }
  16281. /* c8 ignore stop */
  16282. minimatch.AST = AST;
  16283. minimatch.Minimatch = Minimatch;
  16284. minimatch.escape = escape;
  16285. minimatch.unescape = unescape;
  16286. class TypeScope {
  16287. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  16288. this.filename = filename;
  16289. this.source = source;
  16290. this.offset = offset;
  16291. this.imports = imports;
  16292. this.types = types;
  16293. this.declares = declares;
  16294. this.isGenericScope = false;
  16295. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  16296. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  16297. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  16298. }
  16299. }
  16300. function resolveTypeElements(ctx, node, scope, typeParameters) {
  16301. const canCache = !typeParameters;
  16302. if (canCache && node._resolvedElements) {
  16303. return node._resolvedElements;
  16304. }
  16305. const resolved = innerResolveTypeElements(
  16306. ctx,
  16307. node,
  16308. node._ownerScope || scope || ctxToScope(ctx),
  16309. typeParameters
  16310. );
  16311. return canCache ? node._resolvedElements = resolved : resolved;
  16312. }
  16313. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  16314. var _a, _b;
  16315. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  16316. return { props: {} };
  16317. }
  16318. switch (node.type) {
  16319. case "TSTypeLiteral":
  16320. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  16321. case "TSInterfaceDeclaration":
  16322. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  16323. case "TSTypeAliasDeclaration":
  16324. case "TSTypeAnnotation":
  16325. case "TSParenthesizedType":
  16326. return resolveTypeElements(
  16327. ctx,
  16328. node.typeAnnotation,
  16329. scope,
  16330. typeParameters
  16331. );
  16332. case "TSFunctionType": {
  16333. return { props: {}, calls: [node] };
  16334. }
  16335. case "TSUnionType":
  16336. case "TSIntersectionType":
  16337. return mergeElements(
  16338. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  16339. node.type
  16340. );
  16341. case "TSMappedType":
  16342. return resolveMappedType(ctx, node, scope, typeParameters);
  16343. case "TSIndexedAccessType": {
  16344. const types = resolveIndexType(ctx, node, scope);
  16345. return mergeElements(
  16346. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  16347. "TSUnionType"
  16348. );
  16349. }
  16350. case "TSExpressionWithTypeArguments":
  16351. case "TSTypeReference": {
  16352. const typeName = getReferenceName(node);
  16353. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  16354. return resolveExtractPropTypes(
  16355. resolveTypeElements(
  16356. ctx,
  16357. node.typeParameters.params[0],
  16358. scope,
  16359. typeParameters
  16360. ),
  16361. scope
  16362. );
  16363. }
  16364. const resolved = resolveTypeReference(ctx, node, scope);
  16365. if (resolved) {
  16366. let typeParams;
  16367. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  16368. typeParams = /* @__PURE__ */ Object.create(null);
  16369. resolved.typeParameters.params.forEach((p, i) => {
  16370. let param = typeParameters && typeParameters[p.name];
  16371. if (!param) param = node.typeParameters.params[i];
  16372. typeParams[p.name] = param;
  16373. });
  16374. }
  16375. return resolveTypeElements(
  16376. ctx,
  16377. resolved,
  16378. resolved._ownerScope,
  16379. typeParams
  16380. );
  16381. } else {
  16382. if (typeof typeName === "string") {
  16383. if (typeParameters && typeParameters[typeName]) {
  16384. return resolveTypeElements(
  16385. ctx,
  16386. typeParameters[typeName],
  16387. scope,
  16388. typeParameters
  16389. );
  16390. }
  16391. if (
  16392. // @ts-expect-error
  16393. SupportedBuiltinsSet.has(typeName)
  16394. ) {
  16395. return resolveBuiltin(
  16396. ctx,
  16397. node,
  16398. typeName,
  16399. scope,
  16400. typeParameters
  16401. );
  16402. } else if (typeName === "ReturnType" && node.typeParameters) {
  16403. const ret = resolveReturnType(
  16404. ctx,
  16405. node.typeParameters.params[0],
  16406. scope
  16407. );
  16408. if (ret) {
  16409. return resolveTypeElements(ctx, ret, scope);
  16410. }
  16411. }
  16412. }
  16413. return ctx.error(
  16414. `Unresolvable type reference or unsupported built-in utility type`,
  16415. node,
  16416. scope
  16417. );
  16418. }
  16419. }
  16420. case "TSImportType": {
  16421. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  16422. return resolveExtractPropTypes(
  16423. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  16424. scope
  16425. );
  16426. }
  16427. const sourceScope = importSourceToScope(
  16428. ctx,
  16429. node.argument,
  16430. scope,
  16431. node.argument.value
  16432. );
  16433. const resolved = resolveTypeReference(ctx, node, sourceScope);
  16434. if (resolved) {
  16435. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  16436. }
  16437. break;
  16438. }
  16439. case "TSTypeQuery":
  16440. {
  16441. const resolved = resolveTypeReference(ctx, node, scope);
  16442. if (resolved) {
  16443. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  16444. }
  16445. }
  16446. break;
  16447. }
  16448. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  16449. }
  16450. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  16451. const res = { props: {} };
  16452. for (const e of elements) {
  16453. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  16454. if (typeParameters) {
  16455. scope = createChildScope(scope);
  16456. scope.isGenericScope = true;
  16457. Object.assign(scope.types, typeParameters);
  16458. }
  16459. e._ownerScope = scope;
  16460. const name = getId(e.key);
  16461. if (name && !e.computed) {
  16462. res.props[name] = e;
  16463. } else if (e.key.type === "TemplateLiteral") {
  16464. for (const key of resolveTemplateKeys(ctx, e.key, scope)) {
  16465. res.props[key] = e;
  16466. }
  16467. } else {
  16468. ctx.error(
  16469. `Unsupported computed key in type referenced by a macro`,
  16470. e.key,
  16471. scope
  16472. );
  16473. }
  16474. } else if (e.type === "TSCallSignatureDeclaration") {
  16475. (res.calls || (res.calls = [])).push(e);
  16476. }
  16477. }
  16478. return res;
  16479. }
  16480. function mergeElements(maps, type) {
  16481. if (maps.length === 1) return maps[0];
  16482. const res = { props: {} };
  16483. const { props: baseProps } = res;
  16484. for (const { props, calls } of maps) {
  16485. for (const key in props) {
  16486. if (!shared.hasOwn(baseProps, key)) {
  16487. baseProps[key] = props[key];
  16488. } else {
  16489. baseProps[key] = createProperty(
  16490. baseProps[key].key,
  16491. {
  16492. type,
  16493. // @ts-expect-error
  16494. types: [baseProps[key], props[key]]
  16495. },
  16496. baseProps[key]._ownerScope,
  16497. baseProps[key].optional || props[key].optional
  16498. );
  16499. }
  16500. }
  16501. if (calls) {
  16502. (res.calls || (res.calls = [])).push(...calls);
  16503. }
  16504. }
  16505. return res;
  16506. }
  16507. function createProperty(key, typeAnnotation, scope, optional) {
  16508. return {
  16509. type: "TSPropertySignature",
  16510. key,
  16511. kind: "get",
  16512. optional,
  16513. typeAnnotation: {
  16514. type: "TSTypeAnnotation",
  16515. typeAnnotation
  16516. },
  16517. _ownerScope: scope
  16518. };
  16519. }
  16520. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  16521. const base = typeElementsToMap(
  16522. ctx,
  16523. node.body.body,
  16524. node._ownerScope,
  16525. typeParameters
  16526. );
  16527. if (node.extends) {
  16528. for (const ext of node.extends) {
  16529. try {
  16530. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  16531. for (const key in props) {
  16532. if (!shared.hasOwn(base.props, key)) {
  16533. base.props[key] = props[key];
  16534. }
  16535. }
  16536. if (calls) {
  16537. ;
  16538. (base.calls || (base.calls = [])).push(...calls);
  16539. }
  16540. } catch (e) {
  16541. ctx.error(
  16542. `Failed to resolve extends base type.
  16543. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  16544. interface Props extends /* @vue-ignore */ Base {}
  16545. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  16546. ext,
  16547. scope
  16548. );
  16549. }
  16550. }
  16551. }
  16552. return base;
  16553. }
  16554. function resolveMappedType(ctx, node, scope, typeParameters) {
  16555. const res = { props: {} };
  16556. let keys;
  16557. if (node.nameType) {
  16558. const { name, constraint } = node.typeParameter;
  16559. scope = createChildScope(scope);
  16560. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  16561. keys = resolveStringType(ctx, node.nameType, scope);
  16562. } else {
  16563. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  16564. }
  16565. for (const key of keys) {
  16566. res.props[key] = createProperty(
  16567. {
  16568. type: "Identifier",
  16569. name: key
  16570. },
  16571. node.typeAnnotation,
  16572. scope,
  16573. !!node.optional
  16574. );
  16575. }
  16576. return res;
  16577. }
  16578. function resolveIndexType(ctx, node, scope) {
  16579. var _a, _b;
  16580. if (node.indexType.type === "TSNumberKeyword") {
  16581. return resolveArrayElementType(ctx, node.objectType, scope);
  16582. }
  16583. const { indexType, objectType } = node;
  16584. const types = [];
  16585. let keys;
  16586. let resolved;
  16587. if (indexType.type === "TSStringKeyword") {
  16588. resolved = resolveTypeElements(ctx, objectType, scope);
  16589. keys = Object.keys(resolved.props);
  16590. } else {
  16591. keys = resolveStringType(ctx, indexType, scope);
  16592. resolved = resolveTypeElements(ctx, objectType, scope);
  16593. }
  16594. for (const key of keys) {
  16595. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  16596. if (targetType) {
  16597. targetType._ownerScope = resolved.props[key]._ownerScope;
  16598. types.push(targetType);
  16599. }
  16600. }
  16601. return types;
  16602. }
  16603. function resolveArrayElementType(ctx, node, scope) {
  16604. if (node.type === "TSArrayType") {
  16605. return [node.elementType];
  16606. }
  16607. if (node.type === "TSTupleType") {
  16608. return node.elementTypes.map(
  16609. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  16610. );
  16611. }
  16612. if (node.type === "TSTypeReference") {
  16613. if (getReferenceName(node) === "Array" && node.typeParameters) {
  16614. return node.typeParameters.params;
  16615. } else {
  16616. const resolved = resolveTypeReference(ctx, node, scope);
  16617. if (resolved) {
  16618. return resolveArrayElementType(ctx, resolved, scope);
  16619. }
  16620. }
  16621. }
  16622. return ctx.error(
  16623. "Failed to resolve element type from target type",
  16624. node,
  16625. scope
  16626. );
  16627. }
  16628. function resolveStringType(ctx, node, scope) {
  16629. switch (node.type) {
  16630. case "StringLiteral":
  16631. return [node.value];
  16632. case "TSLiteralType":
  16633. return resolveStringType(ctx, node.literal, scope);
  16634. case "TSUnionType":
  16635. return node.types.map((t) => resolveStringType(ctx, t, scope)).flat();
  16636. case "TemplateLiteral": {
  16637. return resolveTemplateKeys(ctx, node, scope);
  16638. }
  16639. case "TSTypeReference": {
  16640. const resolved = resolveTypeReference(ctx, node, scope);
  16641. if (resolved) {
  16642. return resolveStringType(ctx, resolved, scope);
  16643. }
  16644. if (node.typeName.type === "Identifier") {
  16645. const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters.params[index], scope);
  16646. switch (node.typeName.name) {
  16647. case "Extract":
  16648. return getParam(1);
  16649. case "Exclude": {
  16650. const excluded = getParam(1);
  16651. return getParam().filter((s) => !excluded.includes(s));
  16652. }
  16653. case "Uppercase":
  16654. return getParam().map((s) => s.toUpperCase());
  16655. case "Lowercase":
  16656. return getParam().map((s) => s.toLowerCase());
  16657. case "Capitalize":
  16658. return getParam().map(shared.capitalize);
  16659. case "Uncapitalize":
  16660. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  16661. default:
  16662. ctx.error(
  16663. "Unsupported type when resolving index type",
  16664. node.typeName,
  16665. scope
  16666. );
  16667. }
  16668. }
  16669. }
  16670. }
  16671. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  16672. }
  16673. function resolveTemplateKeys(ctx, node, scope) {
  16674. if (!node.expressions.length) {
  16675. return [node.quasis[0].value.raw];
  16676. }
  16677. const res = [];
  16678. const e = node.expressions[0];
  16679. const q = node.quasis[0];
  16680. const leading = q ? q.value.raw : ``;
  16681. const resolved = resolveStringType(ctx, e, scope);
  16682. const restResolved = resolveTemplateKeys(
  16683. ctx,
  16684. {
  16685. ...node,
  16686. expressions: node.expressions.slice(1),
  16687. quasis: q ? node.quasis.slice(1) : node.quasis
  16688. },
  16689. scope
  16690. );
  16691. for (const r of resolved) {
  16692. for (const rr of restResolved) {
  16693. res.push(leading + r + rr);
  16694. }
  16695. }
  16696. return res;
  16697. }
  16698. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  16699. "Partial",
  16700. "Required",
  16701. "Readonly",
  16702. "Pick",
  16703. "Omit"
  16704. ]);
  16705. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  16706. const t = resolveTypeElements(
  16707. ctx,
  16708. node.typeParameters.params[0],
  16709. scope,
  16710. typeParameters
  16711. );
  16712. switch (name) {
  16713. case "Partial": {
  16714. const res2 = { props: {}, calls: t.calls };
  16715. Object.keys(t.props).forEach((key) => {
  16716. res2.props[key] = { ...t.props[key], optional: true };
  16717. });
  16718. return res2;
  16719. }
  16720. case "Required": {
  16721. const res2 = { props: {}, calls: t.calls };
  16722. Object.keys(t.props).forEach((key) => {
  16723. res2.props[key] = { ...t.props[key], optional: false };
  16724. });
  16725. return res2;
  16726. }
  16727. case "Readonly":
  16728. return t;
  16729. case "Pick": {
  16730. const picked = resolveStringType(
  16731. ctx,
  16732. node.typeParameters.params[1],
  16733. scope
  16734. );
  16735. const res2 = { props: {}, calls: t.calls };
  16736. for (const key of picked) {
  16737. res2.props[key] = t.props[key];
  16738. }
  16739. return res2;
  16740. }
  16741. case "Omit":
  16742. const omitted = resolveStringType(
  16743. ctx,
  16744. node.typeParameters.params[1],
  16745. scope
  16746. );
  16747. const res = { props: {}, calls: t.calls };
  16748. for (const key in t.props) {
  16749. if (!omitted.includes(key)) {
  16750. res.props[key] = t.props[key];
  16751. }
  16752. }
  16753. return res;
  16754. }
  16755. }
  16756. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  16757. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  16758. if (canCache && node._resolvedReference) {
  16759. return node._resolvedReference;
  16760. }
  16761. const resolved = innerResolveTypeReference(
  16762. ctx,
  16763. scope || ctxToScope(ctx),
  16764. name || getReferenceName(node),
  16765. node,
  16766. onlyExported
  16767. );
  16768. return canCache ? node._resolvedReference = resolved : resolved;
  16769. }
  16770. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  16771. if (typeof name === "string") {
  16772. if (scope.imports[name]) {
  16773. return resolveTypeFromImport(ctx, node, name, scope);
  16774. } else {
  16775. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  16776. if (lookupSource[name]) {
  16777. return lookupSource[name];
  16778. } else {
  16779. const globalScopes = resolveGlobalScope(ctx);
  16780. if (globalScopes) {
  16781. for (const s of globalScopes) {
  16782. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  16783. if (src[name]) {
  16784. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  16785. return src[name];
  16786. }
  16787. }
  16788. }
  16789. }
  16790. }
  16791. } else {
  16792. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  16793. if (ns) {
  16794. if (ns.type !== "TSModuleDeclaration") {
  16795. ns = ns._ns;
  16796. }
  16797. if (ns) {
  16798. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  16799. return innerResolveTypeReference(
  16800. ctx,
  16801. childScope,
  16802. name.length > 2 ? name.slice(1) : name[name.length - 1],
  16803. node,
  16804. !ns.declare
  16805. );
  16806. }
  16807. }
  16808. }
  16809. }
  16810. function getReferenceName(node) {
  16811. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  16812. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  16813. return ref.name;
  16814. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  16815. return qualifiedNameToPath(ref);
  16816. } else {
  16817. return "default";
  16818. }
  16819. }
  16820. function qualifiedNameToPath(node) {
  16821. if (node.type === "Identifier") {
  16822. return [node.name];
  16823. } else {
  16824. return [...qualifiedNameToPath(node.left), node.right.name];
  16825. }
  16826. }
  16827. function resolveGlobalScope(ctx) {
  16828. if (ctx.options.globalTypeFiles) {
  16829. const fs = resolveFS(ctx);
  16830. if (!fs) {
  16831. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  16832. }
  16833. return ctx.options.globalTypeFiles.map(
  16834. (file) => fileToScope(ctx, normalizePath(file), true)
  16835. );
  16836. }
  16837. }
  16838. let ts;
  16839. let loadTS;
  16840. function registerTS(_loadTS) {
  16841. loadTS = () => {
  16842. try {
  16843. return _loadTS();
  16844. } catch (err) {
  16845. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  16846. throw new Error(
  16847. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "typescript" is installed as a project dependency.'
  16848. );
  16849. } else {
  16850. throw new Error(
  16851. "Failed to load TypeScript for resolving imported types."
  16852. );
  16853. }
  16854. }
  16855. };
  16856. }
  16857. function resolveFS(ctx) {
  16858. if (ctx.fs) {
  16859. return ctx.fs;
  16860. }
  16861. if (!ts && loadTS) {
  16862. ts = loadTS();
  16863. }
  16864. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  16865. if (!fs) {
  16866. return;
  16867. }
  16868. return ctx.fs = {
  16869. fileExists(file) {
  16870. if (file.endsWith(".vue.ts")) {
  16871. file = file.replace(/\.ts$/, "");
  16872. }
  16873. return fs.fileExists(file);
  16874. },
  16875. readFile(file) {
  16876. if (file.endsWith(".vue.ts")) {
  16877. file = file.replace(/\.ts$/, "");
  16878. }
  16879. return fs.readFile(file);
  16880. },
  16881. realpath: fs.realpath
  16882. };
  16883. }
  16884. function resolveTypeFromImport(ctx, node, name, scope) {
  16885. const { source, imported } = scope.imports[name];
  16886. const sourceScope = importSourceToScope(ctx, node, scope, source);
  16887. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  16888. }
  16889. function importSourceToScope(ctx, node, scope, source) {
  16890. let fs;
  16891. try {
  16892. fs = resolveFS(ctx);
  16893. } catch (err) {
  16894. return ctx.error(err.message, node, scope);
  16895. }
  16896. if (!fs) {
  16897. return ctx.error(
  16898. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  16899. node,
  16900. scope
  16901. );
  16902. }
  16903. let resolved = scope.resolvedImportSources[source];
  16904. if (!resolved) {
  16905. if (source.startsWith("..")) {
  16906. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$3.join : joinPaths;
  16907. const filename = osSpecificJoinFn(path$3.dirname(scope.filename), source);
  16908. resolved = resolveExt(filename, fs);
  16909. } else if (source[0] === ".") {
  16910. const filename = joinPaths(path$3.dirname(scope.filename), source);
  16911. resolved = resolveExt(filename, fs);
  16912. } else {
  16913. if (!ts) {
  16914. if (loadTS) ts = loadTS();
  16915. if (!ts) {
  16916. return ctx.error(
  16917. `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.`,
  16918. node,
  16919. scope
  16920. );
  16921. }
  16922. }
  16923. resolved = resolveWithTS(scope.filename, source, ts, fs);
  16924. }
  16925. if (resolved) {
  16926. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  16927. }
  16928. }
  16929. if (resolved) {
  16930. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  16931. return fileToScope(ctx, resolved);
  16932. } else {
  16933. return ctx.error(
  16934. `Failed to resolve import source ${JSON.stringify(source)}.`,
  16935. node,
  16936. scope
  16937. );
  16938. }
  16939. }
  16940. function resolveExt(filename, fs) {
  16941. filename = filename.replace(/\.js$/, "");
  16942. const tryResolve = (filename2) => {
  16943. if (fs.fileExists(filename2)) return filename2;
  16944. };
  16945. return tryResolve(filename) || tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.tsx`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  16946. }
  16947. const tsConfigCache = createCache();
  16948. const tsConfigRefMap = /* @__PURE__ */ new Map();
  16949. function resolveWithTS(containingFile, source, ts2, fs) {
  16950. var _a, _b;
  16951. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  16952. let tsCompilerOptions;
  16953. let tsResolveCache;
  16954. if (configPath) {
  16955. let configs;
  16956. const normalizedConfigPath = normalizePath(configPath);
  16957. const cached = tsConfigCache.get(normalizedConfigPath);
  16958. if (!cached) {
  16959. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  16960. tsConfigCache.set(normalizedConfigPath, configs);
  16961. } else {
  16962. configs = cached;
  16963. }
  16964. let matchedConfig;
  16965. if (configs.length === 1) {
  16966. matchedConfig = configs[0];
  16967. } else {
  16968. for (const c of configs) {
  16969. const base = normalizePath(
  16970. c.config.options.pathsBasePath || path$3.dirname(c.config.options.configFilePath)
  16971. );
  16972. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  16973. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  16974. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, joinPaths(base, p))))) {
  16975. if (excluded && excluded.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  16976. continue;
  16977. }
  16978. matchedConfig = c;
  16979. break;
  16980. }
  16981. }
  16982. if (!matchedConfig) {
  16983. matchedConfig = configs[configs.length - 1];
  16984. }
  16985. }
  16986. tsCompilerOptions = matchedConfig.config.options;
  16987. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  16988. process__namespace.cwd(),
  16989. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  16990. tsCompilerOptions
  16991. ));
  16992. } else {
  16993. tsCompilerOptions = {};
  16994. }
  16995. const res = ts2.resolveModuleName(
  16996. source,
  16997. containingFile,
  16998. tsCompilerOptions,
  16999. fs,
  17000. tsResolveCache
  17001. );
  17002. if (res.resolvedModule) {
  17003. let filename = res.resolvedModule.resolvedFileName;
  17004. if (filename.endsWith(".vue.ts")) {
  17005. filename = filename.replace(/\.ts$/, "");
  17006. }
  17007. return fs.realpath ? fs.realpath(filename) : filename;
  17008. }
  17009. }
  17010. function loadTSConfig(configPath, ts2, fs) {
  17011. const parseConfigHost = ts2.sys;
  17012. const config = ts2.parseJsonConfigFileContent(
  17013. ts2.readConfigFile(configPath, fs.readFile).config,
  17014. parseConfigHost,
  17015. path$3.dirname(configPath),
  17016. void 0,
  17017. configPath
  17018. );
  17019. const res = [config];
  17020. if (config.projectReferences) {
  17021. for (const ref of config.projectReferences) {
  17022. const refPath = ts2.resolveProjectReferencePath(ref);
  17023. if (!fs.fileExists(refPath)) {
  17024. continue;
  17025. }
  17026. tsConfigRefMap.set(refPath, configPath);
  17027. res.unshift(...loadTSConfig(refPath, ts2, fs));
  17028. }
  17029. }
  17030. return res;
  17031. }
  17032. const fileToScopeCache = createCache();
  17033. function invalidateTypeCache(filename) {
  17034. filename = normalizePath(filename);
  17035. fileToScopeCache.delete(filename);
  17036. tsConfigCache.delete(filename);
  17037. const affectedConfig = tsConfigRefMap.get(filename);
  17038. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  17039. }
  17040. function fileToScope(ctx, filename, asGlobal = false) {
  17041. const cached = fileToScopeCache.get(filename);
  17042. if (cached) {
  17043. return cached;
  17044. }
  17045. const fs = resolveFS(ctx);
  17046. const source = fs.readFile(filename) || "";
  17047. const body = parseFile(filename, source, ctx.options.babelParserPlugins);
  17048. const scope = new TypeScope(filename, source, 0, recordImports(body));
  17049. recordTypes(ctx, body, scope, asGlobal);
  17050. fileToScopeCache.set(filename, scope);
  17051. return scope;
  17052. }
  17053. function parseFile(filename, content, parserPlugins) {
  17054. const ext = path$3.extname(filename);
  17055. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".mtsx") {
  17056. return parser$1.parse(content, {
  17057. plugins: resolveParserPlugins(
  17058. ext.slice(1),
  17059. parserPlugins,
  17060. /\.d\.m?ts$/.test(filename)
  17061. ),
  17062. sourceType: "module"
  17063. }).program.body;
  17064. } else if (ext === ".vue") {
  17065. const {
  17066. descriptor: { script, scriptSetup }
  17067. } = parse$2(content);
  17068. if (!script && !scriptSetup) {
  17069. return [];
  17070. }
  17071. const scriptOffset = script ? script.loc.start.offset : Infinity;
  17072. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  17073. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  17074. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  17075. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  17076. if (secondBlock) {
  17077. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  17078. }
  17079. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  17080. return parser$1.parse(scriptContent, {
  17081. plugins: resolveParserPlugins(lang, parserPlugins),
  17082. sourceType: "module"
  17083. }).program.body;
  17084. }
  17085. return [];
  17086. }
  17087. function ctxToScope(ctx) {
  17088. if (ctx.scope) {
  17089. return ctx.scope;
  17090. }
  17091. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  17092. const scope = new TypeScope(
  17093. ctx.filename,
  17094. ctx.source,
  17095. "startOffset" in ctx ? ctx.startOffset : 0,
  17096. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  17097. );
  17098. recordTypes(ctx, body, scope);
  17099. return ctx.scope = scope;
  17100. }
  17101. function moduleDeclToScope(ctx, node, parentScope) {
  17102. if (node._resolvedChildScope) {
  17103. return node._resolvedChildScope;
  17104. }
  17105. const scope = createChildScope(parentScope);
  17106. if (node.body.type === "TSModuleDeclaration") {
  17107. const decl = node.body;
  17108. decl._ownerScope = scope;
  17109. const id = getId(decl.id);
  17110. scope.types[id] = scope.exportedTypes[id] = decl;
  17111. } else {
  17112. recordTypes(ctx, node.body.body, scope);
  17113. }
  17114. return node._resolvedChildScope = scope;
  17115. }
  17116. function createChildScope(parentScope) {
  17117. return new TypeScope(
  17118. parentScope.filename,
  17119. parentScope.source,
  17120. parentScope.offset,
  17121. Object.create(parentScope.imports),
  17122. Object.create(parentScope.types),
  17123. Object.create(parentScope.declares)
  17124. );
  17125. }
  17126. const importExportRE = /^Import|^Export/;
  17127. function recordTypes(ctx, body, scope, asGlobal = false) {
  17128. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  17129. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  17130. for (const stmt of body) {
  17131. if (asGlobal) {
  17132. if (isAmbient) {
  17133. if (stmt.declare) {
  17134. recordType(stmt, types, declares);
  17135. }
  17136. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  17137. for (const s of stmt.body.body) {
  17138. recordType(s, types, declares);
  17139. }
  17140. }
  17141. } else {
  17142. recordType(stmt, types, declares);
  17143. }
  17144. }
  17145. if (!asGlobal) {
  17146. for (const stmt of body) {
  17147. if (stmt.type === "ExportNamedDeclaration") {
  17148. if (stmt.declaration) {
  17149. recordType(stmt.declaration, types, declares);
  17150. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  17151. } else {
  17152. for (const spec of stmt.specifiers) {
  17153. if (spec.type === "ExportSpecifier") {
  17154. const local = spec.local.name;
  17155. const exported = getId(spec.exported);
  17156. if (stmt.source) {
  17157. imports[exported] = {
  17158. source: stmt.source.value,
  17159. imported: local
  17160. };
  17161. exportedTypes[exported] = {
  17162. type: "TSTypeReference",
  17163. typeName: {
  17164. type: "Identifier",
  17165. name: local
  17166. },
  17167. _ownerScope: scope
  17168. };
  17169. } else if (types[local]) {
  17170. exportedTypes[exported] = types[local];
  17171. }
  17172. }
  17173. }
  17174. }
  17175. } else if (stmt.type === "ExportAllDeclaration") {
  17176. const sourceScope = importSourceToScope(
  17177. ctx,
  17178. stmt.source,
  17179. scope,
  17180. stmt.source.value
  17181. );
  17182. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  17183. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  17184. if (stmt.declaration.type !== "Identifier") {
  17185. recordType(stmt.declaration, types, declares, "default");
  17186. recordType(
  17187. stmt.declaration,
  17188. exportedTypes,
  17189. exportedDeclares,
  17190. "default"
  17191. );
  17192. } else if (types[stmt.declaration.name]) {
  17193. exportedTypes["default"] = types[stmt.declaration.name];
  17194. }
  17195. }
  17196. }
  17197. }
  17198. for (const key of Object.keys(types)) {
  17199. const node = types[key];
  17200. node._ownerScope = scope;
  17201. if (node._ns) node._ns._ownerScope = scope;
  17202. }
  17203. for (const key of Object.keys(declares)) {
  17204. declares[key]._ownerScope = scope;
  17205. }
  17206. }
  17207. function recordType(node, types, declares, overwriteId) {
  17208. switch (node.type) {
  17209. case "TSInterfaceDeclaration":
  17210. case "TSEnumDeclaration":
  17211. case "TSModuleDeclaration": {
  17212. const id = overwriteId || getId(node.id);
  17213. let existing = types[id];
  17214. if (existing) {
  17215. if (node.type === "TSModuleDeclaration") {
  17216. if (existing.type === "TSModuleDeclaration") {
  17217. mergeNamespaces(existing, node);
  17218. } else {
  17219. attachNamespace(existing, node);
  17220. }
  17221. break;
  17222. }
  17223. if (existing.type === "TSModuleDeclaration") {
  17224. types[id] = node;
  17225. attachNamespace(node, existing);
  17226. break;
  17227. }
  17228. if (existing.type !== node.type) {
  17229. break;
  17230. }
  17231. if (node.type === "TSInterfaceDeclaration") {
  17232. existing.body.body.push(...node.body.body);
  17233. } else {
  17234. existing.members.push(...node.members);
  17235. }
  17236. } else {
  17237. types[id] = node;
  17238. }
  17239. break;
  17240. }
  17241. case "ClassDeclaration":
  17242. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  17243. break;
  17244. case "TSTypeAliasDeclaration":
  17245. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  17246. break;
  17247. case "TSDeclareFunction":
  17248. if (node.id) declares[node.id.name] = node;
  17249. break;
  17250. case "VariableDeclaration": {
  17251. if (node.declare) {
  17252. for (const decl of node.declarations) {
  17253. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  17254. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  17255. }
  17256. }
  17257. }
  17258. break;
  17259. }
  17260. }
  17261. }
  17262. function mergeNamespaces(to, from) {
  17263. const toBody = to.body;
  17264. const fromBody = from.body;
  17265. if (toBody.type === "TSModuleDeclaration") {
  17266. if (fromBody.type === "TSModuleDeclaration") {
  17267. mergeNamespaces(toBody, fromBody);
  17268. } else {
  17269. fromBody.body.push({
  17270. type: "ExportNamedDeclaration",
  17271. declaration: toBody,
  17272. exportKind: "type",
  17273. specifiers: []
  17274. });
  17275. }
  17276. } else if (fromBody.type === "TSModuleDeclaration") {
  17277. toBody.body.push({
  17278. type: "ExportNamedDeclaration",
  17279. declaration: fromBody,
  17280. exportKind: "type",
  17281. specifiers: []
  17282. });
  17283. } else {
  17284. toBody.body.push(...fromBody.body);
  17285. }
  17286. }
  17287. function attachNamespace(to, ns) {
  17288. if (!to._ns) {
  17289. to._ns = ns;
  17290. } else {
  17291. mergeNamespaces(to._ns, ns);
  17292. }
  17293. }
  17294. function recordImports(body) {
  17295. const imports = /* @__PURE__ */ Object.create(null);
  17296. for (const s of body) {
  17297. recordImport(s, imports);
  17298. }
  17299. return imports;
  17300. }
  17301. function recordImport(node, imports) {
  17302. if (node.type !== "ImportDeclaration") {
  17303. return;
  17304. }
  17305. for (const s of node.specifiers) {
  17306. imports[s.local.name] = {
  17307. imported: getImportedName(s),
  17308. source: node.source.value
  17309. };
  17310. }
  17311. }
  17312. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false) {
  17313. try {
  17314. switch (node.type) {
  17315. case "TSStringKeyword":
  17316. return ["String"];
  17317. case "TSNumberKeyword":
  17318. return ["Number"];
  17319. case "TSBooleanKeyword":
  17320. return ["Boolean"];
  17321. case "TSObjectKeyword":
  17322. return ["Object"];
  17323. case "TSNullKeyword":
  17324. return ["null"];
  17325. case "TSTypeLiteral":
  17326. case "TSInterfaceDeclaration": {
  17327. const types = /* @__PURE__ */ new Set();
  17328. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  17329. for (const m of members) {
  17330. if (isKeyOf) {
  17331. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  17332. types.add("Number");
  17333. } else if (m.type === "TSIndexSignature") {
  17334. const annotation = m.parameters[0].typeAnnotation;
  17335. if (annotation && annotation.type !== "Noop") {
  17336. const type = inferRuntimeType(
  17337. ctx,
  17338. annotation.typeAnnotation,
  17339. scope
  17340. )[0];
  17341. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  17342. types.add(type);
  17343. }
  17344. } else {
  17345. types.add("String");
  17346. }
  17347. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  17348. types.add("Function");
  17349. } else {
  17350. types.add("Object");
  17351. }
  17352. }
  17353. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  17354. }
  17355. case "TSPropertySignature":
  17356. if (node.typeAnnotation) {
  17357. return inferRuntimeType(
  17358. ctx,
  17359. node.typeAnnotation.typeAnnotation,
  17360. scope
  17361. );
  17362. }
  17363. break;
  17364. case "TSMethodSignature":
  17365. case "TSFunctionType":
  17366. return ["Function"];
  17367. case "TSArrayType":
  17368. case "TSTupleType":
  17369. return ["Array"];
  17370. case "TSLiteralType":
  17371. switch (node.literal.type) {
  17372. case "StringLiteral":
  17373. return ["String"];
  17374. case "BooleanLiteral":
  17375. return ["Boolean"];
  17376. case "NumericLiteral":
  17377. case "BigIntLiteral":
  17378. return ["Number"];
  17379. default:
  17380. return [UNKNOWN_TYPE];
  17381. }
  17382. case "TSTypeReference": {
  17383. const resolved = resolveTypeReference(ctx, node, scope);
  17384. if (resolved) {
  17385. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  17386. }
  17387. if (node.typeName.type === "Identifier") {
  17388. if (isKeyOf) {
  17389. switch (node.typeName.name) {
  17390. case "String":
  17391. case "Array":
  17392. case "ArrayLike":
  17393. case "Parameters":
  17394. case "ConstructorParameters":
  17395. case "ReadonlyArray":
  17396. return ["String", "Number"];
  17397. case "Record":
  17398. case "Partial":
  17399. case "Required":
  17400. case "Readonly":
  17401. if (node.typeParameters && node.typeParameters.params[0]) {
  17402. return inferRuntimeType(
  17403. ctx,
  17404. node.typeParameters.params[0],
  17405. scope,
  17406. true
  17407. );
  17408. }
  17409. break;
  17410. case "Pick":
  17411. case "Extract":
  17412. if (node.typeParameters && node.typeParameters.params[1]) {
  17413. return inferRuntimeType(
  17414. ctx,
  17415. node.typeParameters.params[1],
  17416. scope
  17417. );
  17418. }
  17419. break;
  17420. case "Function":
  17421. case "Object":
  17422. case "Set":
  17423. case "Map":
  17424. case "WeakSet":
  17425. case "WeakMap":
  17426. case "Date":
  17427. case "Promise":
  17428. case "Error":
  17429. case "Uppercase":
  17430. case "Lowercase":
  17431. case "Capitalize":
  17432. case "Uncapitalize":
  17433. case "ReadonlyMap":
  17434. case "ReadonlySet":
  17435. return ["String"];
  17436. }
  17437. } else {
  17438. switch (node.typeName.name) {
  17439. case "Array":
  17440. case "Function":
  17441. case "Object":
  17442. case "Set":
  17443. case "Map":
  17444. case "WeakSet":
  17445. case "WeakMap":
  17446. case "Date":
  17447. case "Promise":
  17448. case "Error":
  17449. return [node.typeName.name];
  17450. case "Partial":
  17451. case "Required":
  17452. case "Readonly":
  17453. case "Record":
  17454. case "Pick":
  17455. case "Omit":
  17456. case "InstanceType":
  17457. return ["Object"];
  17458. case "Uppercase":
  17459. case "Lowercase":
  17460. case "Capitalize":
  17461. case "Uncapitalize":
  17462. return ["String"];
  17463. case "Parameters":
  17464. case "ConstructorParameters":
  17465. case "ReadonlyArray":
  17466. return ["Array"];
  17467. case "ReadonlyMap":
  17468. return ["Map"];
  17469. case "ReadonlySet":
  17470. return ["Set"];
  17471. case "NonNullable":
  17472. if (node.typeParameters && node.typeParameters.params[0]) {
  17473. return inferRuntimeType(
  17474. ctx,
  17475. node.typeParameters.params[0],
  17476. scope
  17477. ).filter((t) => t !== "null");
  17478. }
  17479. break;
  17480. case "Extract":
  17481. if (node.typeParameters && node.typeParameters.params[1]) {
  17482. return inferRuntimeType(
  17483. ctx,
  17484. node.typeParameters.params[1],
  17485. scope
  17486. );
  17487. }
  17488. break;
  17489. case "Exclude":
  17490. case "OmitThisParameter":
  17491. if (node.typeParameters && node.typeParameters.params[0]) {
  17492. return inferRuntimeType(
  17493. ctx,
  17494. node.typeParameters.params[0],
  17495. scope
  17496. );
  17497. }
  17498. break;
  17499. }
  17500. }
  17501. }
  17502. break;
  17503. }
  17504. case "TSParenthesizedType":
  17505. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  17506. case "TSUnionType":
  17507. return flattenTypes(ctx, node.types, scope, isKeyOf);
  17508. case "TSIntersectionType": {
  17509. return flattenTypes(ctx, node.types, scope, isKeyOf).filter(
  17510. (t) => t !== UNKNOWN_TYPE
  17511. );
  17512. }
  17513. case "TSEnumDeclaration":
  17514. return inferEnumType(node);
  17515. case "TSSymbolKeyword":
  17516. return ["Symbol"];
  17517. case "TSIndexedAccessType": {
  17518. const types = resolveIndexType(ctx, node, scope);
  17519. return flattenTypes(ctx, types, scope, isKeyOf);
  17520. }
  17521. case "ClassDeclaration":
  17522. return ["Object"];
  17523. case "TSImportType": {
  17524. const sourceScope = importSourceToScope(
  17525. ctx,
  17526. node.argument,
  17527. scope,
  17528. node.argument.value
  17529. );
  17530. const resolved = resolveTypeReference(ctx, node, sourceScope);
  17531. if (resolved) {
  17532. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  17533. }
  17534. break;
  17535. }
  17536. case "TSTypeQuery": {
  17537. const id = node.exprName;
  17538. if (id.type === "Identifier") {
  17539. const matched = scope.declares[id.name];
  17540. if (matched) {
  17541. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  17542. }
  17543. }
  17544. break;
  17545. }
  17546. case "TSTypeOperator": {
  17547. return inferRuntimeType(
  17548. ctx,
  17549. node.typeAnnotation,
  17550. scope,
  17551. node.operator === "keyof"
  17552. );
  17553. }
  17554. case "TSAnyKeyword": {
  17555. if (isKeyOf) {
  17556. return ["String", "Number", "Symbol"];
  17557. }
  17558. break;
  17559. }
  17560. }
  17561. } catch (e) {
  17562. }
  17563. return [UNKNOWN_TYPE];
  17564. }
  17565. function flattenTypes(ctx, types, scope, isKeyOf = false) {
  17566. if (types.length === 1) {
  17567. return inferRuntimeType(ctx, types[0], scope, isKeyOf);
  17568. }
  17569. return [
  17570. ...new Set(
  17571. [].concat(
  17572. ...types.map((t) => inferRuntimeType(ctx, t, scope, isKeyOf))
  17573. )
  17574. )
  17575. ];
  17576. }
  17577. function inferEnumType(node) {
  17578. const types = /* @__PURE__ */ new Set();
  17579. for (const m of node.members) {
  17580. if (m.initializer) {
  17581. switch (m.initializer.type) {
  17582. case "StringLiteral":
  17583. types.add("String");
  17584. break;
  17585. case "NumericLiteral":
  17586. types.add("Number");
  17587. break;
  17588. }
  17589. }
  17590. }
  17591. return types.size ? [...types] : ["Number"];
  17592. }
  17593. function resolveExtractPropTypes({ props }, scope) {
  17594. const res = { props: {} };
  17595. for (const key in props) {
  17596. const raw = props[key];
  17597. res.props[key] = reverseInferType(
  17598. raw.key,
  17599. raw.typeAnnotation.typeAnnotation,
  17600. scope
  17601. );
  17602. }
  17603. return res;
  17604. }
  17605. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  17606. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  17607. const typeType = findStaticPropertyType(node, "type");
  17608. if (typeType) {
  17609. const requiredType = findStaticPropertyType(node, "required");
  17610. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  17611. return reverseInferType(key, typeType, scope, optional2, false);
  17612. }
  17613. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  17614. if (node.typeName.name.endsWith("Constructor")) {
  17615. return createProperty(
  17616. key,
  17617. ctorToType(node.typeName.name),
  17618. scope,
  17619. optional
  17620. );
  17621. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  17622. return createProperty(key, node.typeParameters.params[0], scope, optional);
  17623. }
  17624. }
  17625. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  17626. for (const t of node.typeParameters.params) {
  17627. const inferred = reverseInferType(key, t, scope, optional);
  17628. if (inferred) return inferred;
  17629. }
  17630. }
  17631. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  17632. }
  17633. function ctorToType(ctorType) {
  17634. const ctor = ctorType.slice(0, -11);
  17635. switch (ctor) {
  17636. case "String":
  17637. case "Number":
  17638. case "Boolean":
  17639. return { type: `TS${ctor}Keyword` };
  17640. case "Array":
  17641. case "Function":
  17642. case "Object":
  17643. case "Set":
  17644. case "Map":
  17645. case "WeakSet":
  17646. case "WeakMap":
  17647. case "Date":
  17648. case "Promise":
  17649. return {
  17650. type: "TSTypeReference",
  17651. typeName: { type: "Identifier", name: ctor }
  17652. };
  17653. }
  17654. return { type: `TSNullKeyword` };
  17655. }
  17656. function findStaticPropertyType(node, key) {
  17657. const prop = node.members.find(
  17658. (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation
  17659. );
  17660. return prop && prop.typeAnnotation.typeAnnotation;
  17661. }
  17662. function resolveReturnType(ctx, arg, scope) {
  17663. var _a;
  17664. let resolved = arg;
  17665. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  17666. resolved = resolveTypeReference(ctx, arg, scope);
  17667. }
  17668. if (!resolved) return;
  17669. if (resolved.type === "TSFunctionType") {
  17670. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  17671. }
  17672. if (resolved.type === "TSDeclareFunction") {
  17673. return resolved.returnType;
  17674. }
  17675. }
  17676. function resolveUnionType(ctx, node, scope) {
  17677. if (node.type === "TSTypeReference") {
  17678. const resolved = resolveTypeReference(ctx, node, scope);
  17679. if (resolved) node = resolved;
  17680. }
  17681. let types;
  17682. if (node.type === "TSUnionType") {
  17683. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  17684. } else {
  17685. types = [node];
  17686. }
  17687. return types;
  17688. }
  17689. const DEFINE_MODEL = "defineModel";
  17690. function processDefineModel(ctx, node, declId) {
  17691. if (!isCallOf(node, DEFINE_MODEL)) {
  17692. return false;
  17693. }
  17694. ctx.hasDefineModelCall = true;
  17695. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  17696. let modelName;
  17697. let options;
  17698. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  17699. const hasName = arg0 && arg0.type === "StringLiteral";
  17700. if (hasName) {
  17701. modelName = arg0.value;
  17702. options = node.arguments[1];
  17703. } else {
  17704. modelName = "modelValue";
  17705. options = arg0;
  17706. }
  17707. if (ctx.modelDecls[modelName]) {
  17708. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  17709. }
  17710. let optionsString = options && ctx.getString(options);
  17711. let optionsRemoved = !options;
  17712. const runtimeOptionNodes = [];
  17713. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  17714. let removed = 0;
  17715. for (let i = options.properties.length - 1; i >= 0; i--) {
  17716. const p = options.properties[i];
  17717. const next = options.properties[i + 1];
  17718. const start = p.start;
  17719. const end = next ? next.start : options.end - 1;
  17720. 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"))) {
  17721. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  17722. } else {
  17723. removed++;
  17724. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  17725. runtimeOptionNodes.push(p);
  17726. }
  17727. }
  17728. if (removed === options.properties.length) {
  17729. optionsRemoved = true;
  17730. ctx.s.remove(
  17731. ctx.startOffset + (hasName ? arg0.end : options.start),
  17732. ctx.startOffset + options.end
  17733. );
  17734. }
  17735. }
  17736. ctx.modelDecls[modelName] = {
  17737. type,
  17738. options: optionsString,
  17739. runtimeOptionNodes,
  17740. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  17741. };
  17742. ctx.bindingMetadata[modelName] = "props";
  17743. ctx.s.overwrite(
  17744. ctx.startOffset + node.callee.start,
  17745. ctx.startOffset + node.callee.end,
  17746. ctx.helper("useModel")
  17747. );
  17748. ctx.s.appendLeft(
  17749. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  17750. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  17751. );
  17752. return true;
  17753. }
  17754. function genModelProps(ctx) {
  17755. if (!ctx.hasDefineModelCall) return;
  17756. const isProd = !!ctx.options.isProd;
  17757. let modelPropsDecl = "";
  17758. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  17759. ctx.modelDecls
  17760. )) {
  17761. let skipCheck = false;
  17762. let codegenOptions = ``;
  17763. let runtimeTypes = type && inferRuntimeType(ctx, type);
  17764. if (runtimeTypes) {
  17765. const hasBoolean = runtimeTypes.includes("Boolean");
  17766. const hasFunction = runtimeTypes.includes("Function");
  17767. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  17768. if (hasUnknownType) {
  17769. if (hasBoolean || hasFunction) {
  17770. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  17771. skipCheck = true;
  17772. } else {
  17773. runtimeTypes = ["null"];
  17774. }
  17775. }
  17776. if (!isProd) {
  17777. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  17778. } else if (hasBoolean || runtimeOptions && hasFunction) {
  17779. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  17780. } else ;
  17781. }
  17782. let decl;
  17783. if (codegenOptions && runtimeOptions) {
  17784. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  17785. } else if (codegenOptions) {
  17786. decl = `{ ${codegenOptions} }`;
  17787. } else if (runtimeOptions) {
  17788. decl = runtimeOptions;
  17789. } else {
  17790. decl = `{}`;
  17791. }
  17792. modelPropsDecl += `
  17793. ${JSON.stringify(name)}: ${decl},`;
  17794. const modifierPropName = JSON.stringify(
  17795. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  17796. );
  17797. modelPropsDecl += `
  17798. ${modifierPropName}: {},`;
  17799. }
  17800. return `{${modelPropsDecl}
  17801. }`;
  17802. }
  17803. const DEFINE_PROPS = "defineProps";
  17804. const WITH_DEFAULTS = "withDefaults";
  17805. function processDefineProps(ctx, node, declId) {
  17806. if (!isCallOf(node, DEFINE_PROPS)) {
  17807. return processWithDefaults(ctx, node, declId);
  17808. }
  17809. if (ctx.hasDefinePropsCall) {
  17810. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  17811. }
  17812. ctx.hasDefinePropsCall = true;
  17813. ctx.propsRuntimeDecl = node.arguments[0];
  17814. if (ctx.propsRuntimeDecl) {
  17815. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  17816. if (!(key in ctx.bindingMetadata)) {
  17817. ctx.bindingMetadata[key] = "props";
  17818. }
  17819. }
  17820. }
  17821. if (node.typeParameters) {
  17822. if (ctx.propsRuntimeDecl) {
  17823. ctx.error(
  17824. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  17825. node
  17826. );
  17827. }
  17828. ctx.propsTypeDecl = node.typeParameters.params[0];
  17829. }
  17830. if (declId && declId.type === "ObjectPattern") {
  17831. processPropsDestructure(ctx, declId);
  17832. }
  17833. ctx.propsCall = node;
  17834. ctx.propsDecl = declId;
  17835. return true;
  17836. }
  17837. function processWithDefaults(ctx, node, declId) {
  17838. if (!isCallOf(node, WITH_DEFAULTS)) {
  17839. return false;
  17840. }
  17841. if (!processDefineProps(ctx, node.arguments[0], declId)) {
  17842. ctx.error(
  17843. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  17844. node.arguments[0] || node
  17845. );
  17846. }
  17847. if (ctx.propsRuntimeDecl) {
  17848. ctx.error(
  17849. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  17850. node
  17851. );
  17852. }
  17853. if (ctx.propsDestructureDecl) {
  17854. ctx.error(
  17855. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  17856. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`,
  17857. node.callee
  17858. );
  17859. }
  17860. ctx.propsRuntimeDefaults = node.arguments[1];
  17861. if (!ctx.propsRuntimeDefaults) {
  17862. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  17863. }
  17864. ctx.propsCall = node;
  17865. return true;
  17866. }
  17867. function genRuntimeProps(ctx) {
  17868. let propsDecls;
  17869. if (ctx.propsRuntimeDecl) {
  17870. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  17871. if (ctx.propsDestructureDecl) {
  17872. const defaults = [];
  17873. for (const key in ctx.propsDestructuredBindings) {
  17874. const d = genDestructuredDefaultValue(ctx, key);
  17875. const finalKey = getEscapedPropName(key);
  17876. if (d)
  17877. defaults.push(
  17878. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  17879. );
  17880. }
  17881. if (defaults.length) {
  17882. propsDecls = `/*#__PURE__*/${ctx.helper(
  17883. `mergeDefaults`
  17884. )}(${propsDecls}, {
  17885. ${defaults.join(",\n ")}
  17886. })`;
  17887. }
  17888. }
  17889. } else if (ctx.propsTypeDecl) {
  17890. propsDecls = extractRuntimeProps(ctx);
  17891. }
  17892. const modelsDecls = genModelProps(ctx);
  17893. if (propsDecls && modelsDecls) {
  17894. return `/*#__PURE__*/${ctx.helper(
  17895. "mergeModels"
  17896. )}(${propsDecls}, ${modelsDecls})`;
  17897. } else {
  17898. return modelsDecls || propsDecls;
  17899. }
  17900. }
  17901. function extractRuntimeProps(ctx) {
  17902. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  17903. if (!props.length) {
  17904. return;
  17905. }
  17906. const propStrings = [];
  17907. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  17908. for (const prop of props) {
  17909. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  17910. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  17911. ctx.bindingMetadata[prop.key] = "props";
  17912. }
  17913. }
  17914. let propsDecls = `{
  17915. ${propStrings.join(",\n ")}
  17916. }`;
  17917. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  17918. propsDecls = `/*#__PURE__*/${ctx.helper(
  17919. "mergeDefaults"
  17920. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  17921. }
  17922. return propsDecls;
  17923. }
  17924. function resolveRuntimePropsFromType(ctx, node) {
  17925. const props = [];
  17926. const elements = resolveTypeElements(ctx, node);
  17927. for (const key in elements.props) {
  17928. const e = elements.props[key];
  17929. let type = inferRuntimeType(ctx, e);
  17930. let skipCheck = false;
  17931. if (type.includes(UNKNOWN_TYPE)) {
  17932. if (type.includes("Boolean") || type.includes("Function")) {
  17933. type = type.filter((t) => t !== UNKNOWN_TYPE);
  17934. skipCheck = true;
  17935. } else {
  17936. type = ["null"];
  17937. }
  17938. }
  17939. props.push({
  17940. key,
  17941. required: !e.optional,
  17942. type: type || [`null`],
  17943. skipCheck
  17944. });
  17945. }
  17946. return props;
  17947. }
  17948. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  17949. let defaultString;
  17950. const destructured = genDestructuredDefaultValue(ctx, key, type);
  17951. if (destructured) {
  17952. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  17953. } else if (hasStaticDefaults) {
  17954. const prop = ctx.propsRuntimeDefaults.properties.find(
  17955. (node) => {
  17956. if (node.type === "SpreadElement") return false;
  17957. return resolveObjectKey(node.key, node.computed) === key;
  17958. }
  17959. );
  17960. if (prop) {
  17961. if (prop.type === "ObjectProperty") {
  17962. defaultString = `default: ${ctx.getString(prop.value)}`;
  17963. } else {
  17964. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`;
  17965. }
  17966. }
  17967. }
  17968. const finalKey = getEscapedPropName(key);
  17969. if (!ctx.options.isProd) {
  17970. return `${finalKey}: { ${concatStrings([
  17971. `type: ${toRuntimeTypeString(type)}`,
  17972. `required: ${required}`,
  17973. skipCheck && "skipCheck: true",
  17974. defaultString
  17975. ])} }`;
  17976. } else if (type.some(
  17977. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  17978. )) {
  17979. return `${finalKey}: { ${concatStrings([
  17980. `type: ${toRuntimeTypeString(type)}`,
  17981. defaultString
  17982. ])} }`;
  17983. } else {
  17984. if (ctx.isCE) {
  17985. if (defaultString) {
  17986. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  17987. type
  17988. )} }`}`;
  17989. } else {
  17990. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  17991. }
  17992. }
  17993. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  17994. }
  17995. }
  17996. function hasStaticWithDefaults(ctx) {
  17997. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  17998. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  17999. ));
  18000. }
  18001. function genDestructuredDefaultValue(ctx, key, inferredType) {
  18002. const destructured = ctx.propsDestructuredBindings[key];
  18003. const defaultVal = destructured && destructured.default;
  18004. if (defaultVal) {
  18005. const value = ctx.getString(defaultVal);
  18006. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  18007. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  18008. const valueType = inferValueType(unwrapped);
  18009. if (valueType && !inferredType.includes(valueType)) {
  18010. ctx.error(
  18011. `Default value of prop "${key}" does not match declared type.`,
  18012. unwrapped
  18013. );
  18014. }
  18015. }
  18016. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  18017. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  18018. return {
  18019. valueString: needFactoryWrap ? `() => (${value})` : value,
  18020. needSkipFactory
  18021. };
  18022. }
  18023. }
  18024. function inferValueType(node) {
  18025. switch (node.type) {
  18026. case "StringLiteral":
  18027. return "String";
  18028. case "NumericLiteral":
  18029. return "Number";
  18030. case "BooleanLiteral":
  18031. return "Boolean";
  18032. case "ObjectExpression":
  18033. return "Object";
  18034. case "ArrayExpression":
  18035. return "Array";
  18036. case "FunctionExpression":
  18037. case "ArrowFunctionExpression":
  18038. return "Function";
  18039. }
  18040. }
  18041. function processPropsDestructure(ctx, declId) {
  18042. if (!ctx.options.propsDestructure) {
  18043. return;
  18044. }
  18045. warnOnce(
  18046. `This project is using reactive props destructure, which is an experimental feature. It may receive breaking changes or be removed in the future, so use at your own risk.
  18047. To stay updated, follow the RFC at https://github.com/vuejs/rfcs/discussions/502.`
  18048. );
  18049. ctx.propsDestructureDecl = declId;
  18050. const registerBinding = (key, local, defaultValue) => {
  18051. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  18052. if (local !== key) {
  18053. ctx.bindingMetadata[local] = "props-aliased";
  18054. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  18055. }
  18056. };
  18057. for (const prop of declId.properties) {
  18058. if (prop.type === "ObjectProperty") {
  18059. const propKey = resolveObjectKey(prop.key, prop.computed);
  18060. if (!propKey) {
  18061. ctx.error(
  18062. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  18063. prop.key
  18064. );
  18065. }
  18066. if (prop.value.type === "AssignmentPattern") {
  18067. const { left, right } = prop.value;
  18068. if (left.type !== "Identifier") {
  18069. ctx.error(
  18070. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  18071. left
  18072. );
  18073. }
  18074. registerBinding(propKey, left.name, right);
  18075. } else if (prop.value.type === "Identifier") {
  18076. registerBinding(propKey, prop.value.name);
  18077. } else {
  18078. ctx.error(
  18079. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  18080. prop.value
  18081. );
  18082. }
  18083. } else {
  18084. ctx.propsDestructureRestId = prop.argument.name;
  18085. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  18086. }
  18087. }
  18088. }
  18089. function transformDestructuredProps(ctx, vueImportAliases) {
  18090. if (!ctx.options.propsDestructure) {
  18091. return;
  18092. }
  18093. const rootScope = {};
  18094. const scopeStack = [rootScope];
  18095. let currentScope = rootScope;
  18096. const excludedIds = /* @__PURE__ */ new WeakSet();
  18097. const parentStack = [];
  18098. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  18099. for (const key in ctx.propsDestructuredBindings) {
  18100. const { local } = ctx.propsDestructuredBindings[key];
  18101. rootScope[local] = true;
  18102. propsLocalToPublicMap[local] = key;
  18103. }
  18104. function pushScope() {
  18105. scopeStack.push(currentScope = Object.create(currentScope));
  18106. }
  18107. function popScope() {
  18108. scopeStack.pop();
  18109. currentScope = scopeStack[scopeStack.length - 1] || null;
  18110. }
  18111. function registerLocalBinding(id) {
  18112. excludedIds.add(id);
  18113. if (currentScope) {
  18114. currentScope[id.name] = false;
  18115. } else {
  18116. ctx.error(
  18117. "registerBinding called without active scope, something is wrong.",
  18118. id
  18119. );
  18120. }
  18121. }
  18122. function walkScope(node, isRoot = false) {
  18123. for (const stmt of node.body) {
  18124. if (stmt.type === "VariableDeclaration") {
  18125. walkVariableDeclaration(stmt, isRoot);
  18126. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  18127. if (stmt.declare || !stmt.id) continue;
  18128. registerLocalBinding(stmt.id);
  18129. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  18130. walkVariableDeclaration(stmt.left);
  18131. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  18132. walkVariableDeclaration(stmt.declaration, isRoot);
  18133. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  18134. walkVariableDeclaration(stmt.body, isRoot);
  18135. }
  18136. }
  18137. }
  18138. function walkVariableDeclaration(stmt, isRoot = false) {
  18139. if (stmt.declare) {
  18140. return;
  18141. }
  18142. for (const decl of stmt.declarations) {
  18143. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  18144. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  18145. if (isDefineProps) {
  18146. excludedIds.add(id);
  18147. } else {
  18148. registerLocalBinding(id);
  18149. }
  18150. }
  18151. }
  18152. }
  18153. function rewriteId(id, parent, parentStack2) {
  18154. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  18155. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  18156. }
  18157. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  18158. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  18159. ctx.s.appendLeft(
  18160. id.end + ctx.startOffset,
  18161. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  18162. );
  18163. }
  18164. } else {
  18165. ctx.s.overwrite(
  18166. id.start + ctx.startOffset,
  18167. id.end + ctx.startOffset,
  18168. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  18169. );
  18170. }
  18171. }
  18172. function checkUsage(node, method, alias = method) {
  18173. if (isCallOf(node, alias)) {
  18174. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  18175. if (arg.type === "Identifier" && currentScope[arg.name]) {
  18176. ctx.error(
  18177. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  18178. arg
  18179. );
  18180. }
  18181. }
  18182. }
  18183. const ast = ctx.scriptSetupAst;
  18184. walkScope(ast, true);
  18185. estreeWalker.walk(ast, {
  18186. enter(node, parent) {
  18187. parent && parentStack.push(parent);
  18188. if (parent && parent.type.startsWith("TS") && parent.type !== "TSAsExpression" && parent.type !== "TSNonNullExpression" && parent.type !== "TSTypeAssertion") {
  18189. return this.skip();
  18190. }
  18191. checkUsage(node, "watch", vueImportAliases.watch);
  18192. checkUsage(node, "toRef", vueImportAliases.toRef);
  18193. if (CompilerDOM.isFunctionType(node)) {
  18194. pushScope();
  18195. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  18196. if (node.body.type === "BlockStatement") {
  18197. walkScope(node.body);
  18198. }
  18199. return;
  18200. }
  18201. if (node.type === "CatchClause") {
  18202. pushScope();
  18203. if (node.param && node.param.type === "Identifier") {
  18204. registerLocalBinding(node.param);
  18205. }
  18206. walkScope(node.body);
  18207. return;
  18208. }
  18209. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  18210. pushScope();
  18211. walkScope(node);
  18212. return;
  18213. }
  18214. if (node.type === "Identifier") {
  18215. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  18216. if (currentScope[node.name]) {
  18217. rewriteId(node, parent, parentStack);
  18218. }
  18219. }
  18220. }
  18221. },
  18222. leave(node, parent) {
  18223. parent && parentStack.pop();
  18224. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node)) {
  18225. popScope();
  18226. }
  18227. }
  18228. });
  18229. }
  18230. const DEFINE_EMITS = "defineEmits";
  18231. function processDefineEmits(ctx, node, declId) {
  18232. if (!isCallOf(node, DEFINE_EMITS)) {
  18233. return false;
  18234. }
  18235. if (ctx.hasDefineEmitCall) {
  18236. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  18237. }
  18238. ctx.hasDefineEmitCall = true;
  18239. ctx.emitsRuntimeDecl = node.arguments[0];
  18240. if (node.typeParameters) {
  18241. if (ctx.emitsRuntimeDecl) {
  18242. ctx.error(
  18243. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  18244. node
  18245. );
  18246. }
  18247. ctx.emitsTypeDecl = node.typeParameters.params[0];
  18248. }
  18249. ctx.emitDecl = declId;
  18250. return true;
  18251. }
  18252. function genRuntimeEmits(ctx) {
  18253. let emitsDecl = "";
  18254. if (ctx.emitsRuntimeDecl) {
  18255. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  18256. } else if (ctx.emitsTypeDecl) {
  18257. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  18258. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  18259. }
  18260. if (ctx.hasDefineModelCall) {
  18261. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  18262. emitsDecl = emitsDecl ? `/*#__PURE__*/${ctx.helper(
  18263. "mergeModels"
  18264. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  18265. }
  18266. return emitsDecl;
  18267. }
  18268. function extractRuntimeEmits(ctx) {
  18269. const emits = /* @__PURE__ */ new Set();
  18270. const node = ctx.emitsTypeDecl;
  18271. if (node.type === "TSFunctionType") {
  18272. extractEventNames(ctx, node.parameters[0], emits);
  18273. return emits;
  18274. }
  18275. const { props, calls } = resolveTypeElements(ctx, node);
  18276. let hasProperty = false;
  18277. for (const key in props) {
  18278. emits.add(key);
  18279. hasProperty = true;
  18280. }
  18281. if (calls) {
  18282. if (hasProperty) {
  18283. ctx.error(
  18284. `defineEmits() type cannot mixed call signature and property syntax.`,
  18285. node
  18286. );
  18287. }
  18288. for (const call of calls) {
  18289. extractEventNames(ctx, call.parameters[0], emits);
  18290. }
  18291. }
  18292. return emits;
  18293. }
  18294. function extractEventNames(ctx, eventName, emits) {
  18295. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  18296. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  18297. for (const type of types) {
  18298. if (type.type === "TSLiteralType") {
  18299. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  18300. emits.add(String(type.literal.value));
  18301. }
  18302. }
  18303. }
  18304. }
  18305. }
  18306. const DEFINE_EXPOSE = "defineExpose";
  18307. function processDefineExpose(ctx, node) {
  18308. if (isCallOf(node, DEFINE_EXPOSE)) {
  18309. if (ctx.hasDefineExposeCall) {
  18310. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  18311. }
  18312. ctx.hasDefineExposeCall = true;
  18313. return true;
  18314. }
  18315. return false;
  18316. }
  18317. const DEFINE_SLOTS = "defineSlots";
  18318. function processDefineSlots(ctx, node, declId) {
  18319. if (!isCallOf(node, DEFINE_SLOTS)) {
  18320. return false;
  18321. }
  18322. if (ctx.hasDefineSlotsCall) {
  18323. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  18324. }
  18325. ctx.hasDefineSlotsCall = true;
  18326. if (node.arguments.length > 0) {
  18327. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  18328. }
  18329. if (declId) {
  18330. ctx.s.overwrite(
  18331. ctx.startOffset + node.start,
  18332. ctx.startOffset + node.end,
  18333. `${ctx.helper("useSlots")}()`
  18334. );
  18335. }
  18336. return true;
  18337. }
  18338. const DEFINE_OPTIONS = "defineOptions";
  18339. function processDefineOptions(ctx, node) {
  18340. if (!isCallOf(node, DEFINE_OPTIONS)) {
  18341. return false;
  18342. }
  18343. if (ctx.hasDefineOptionsCall) {
  18344. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  18345. }
  18346. if (node.typeParameters) {
  18347. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  18348. }
  18349. if (!node.arguments[0]) return true;
  18350. ctx.hasDefineOptionsCall = true;
  18351. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  18352. let propsOption = void 0;
  18353. let emitsOption = void 0;
  18354. let exposeOption = void 0;
  18355. let slotsOption = void 0;
  18356. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  18357. for (const prop of ctx.optionsRuntimeDecl.properties) {
  18358. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  18359. switch (prop.key.name) {
  18360. case "props":
  18361. propsOption = prop;
  18362. break;
  18363. case "emits":
  18364. emitsOption = prop;
  18365. break;
  18366. case "expose":
  18367. exposeOption = prop;
  18368. break;
  18369. case "slots":
  18370. slotsOption = prop;
  18371. break;
  18372. }
  18373. }
  18374. }
  18375. }
  18376. if (propsOption) {
  18377. ctx.error(
  18378. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  18379. propsOption
  18380. );
  18381. }
  18382. if (emitsOption) {
  18383. ctx.error(
  18384. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  18385. emitsOption
  18386. );
  18387. }
  18388. if (exposeOption) {
  18389. ctx.error(
  18390. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  18391. exposeOption
  18392. );
  18393. }
  18394. if (slotsOption) {
  18395. ctx.error(
  18396. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  18397. slotsOption
  18398. );
  18399. }
  18400. return true;
  18401. }
  18402. function processAwait(ctx, node, needSemi, isStatement) {
  18403. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  18404. const startOffset = ctx.startOffset;
  18405. const argumentStr = ctx.descriptor.source.slice(
  18406. argumentStart + startOffset,
  18407. node.argument.end + startOffset
  18408. );
  18409. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  18410. ctx.s.overwrite(
  18411. node.start + startOffset,
  18412. argumentStart + startOffset,
  18413. `${needSemi ? `;` : ``}(
  18414. ([__temp,__restore] = ${ctx.helper(
  18415. `withAsyncContext`
  18416. )}(${containsNestedAwait ? `async ` : ``}() => `
  18417. );
  18418. ctx.s.appendLeft(
  18419. node.end + startOffset,
  18420. `)),
  18421. ${isStatement ? `` : `__temp = `}await __temp,
  18422. __restore()${isStatement ? `` : `,
  18423. __temp`}
  18424. )`
  18425. );
  18426. }
  18427. const MACROS = [
  18428. DEFINE_PROPS,
  18429. DEFINE_EMITS,
  18430. DEFINE_EXPOSE,
  18431. DEFINE_OPTIONS,
  18432. DEFINE_SLOTS,
  18433. DEFINE_MODEL,
  18434. WITH_DEFAULTS
  18435. ];
  18436. function compileScript(sfc, options) {
  18437. var _a, _b, _c;
  18438. if (!options.id) {
  18439. warnOnce(
  18440. `compileScript now requires passing the \`id\` option.
  18441. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  18442. );
  18443. }
  18444. const ctx = new ScriptCompileContext(sfc, options);
  18445. const { script, scriptSetup, source, filename } = sfc;
  18446. const hoistStatic = options.hoistStatic !== false && !script;
  18447. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  18448. const scriptLang = script && script.lang;
  18449. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  18450. if (!scriptSetup) {
  18451. if (!script) {
  18452. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  18453. }
  18454. return processNormalScript(ctx, scopeId);
  18455. }
  18456. if (script && scriptLang !== scriptSetupLang) {
  18457. throw new Error(
  18458. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  18459. );
  18460. }
  18461. if (scriptSetupLang && !ctx.isJS && !ctx.isTS) {
  18462. return scriptSetup;
  18463. }
  18464. const scriptBindings = /* @__PURE__ */ Object.create(null);
  18465. const setupBindings = /* @__PURE__ */ Object.create(null);
  18466. let defaultExport;
  18467. let hasAwait = false;
  18468. let hasInlinedSsrRenderFn = false;
  18469. const startOffset = ctx.startOffset;
  18470. const endOffset = ctx.endOffset;
  18471. const scriptStartOffset = script && script.loc.start.offset;
  18472. const scriptEndOffset = script && script.loc.end.offset;
  18473. function hoistNode(node) {
  18474. const start = node.start + startOffset;
  18475. let end = node.end + startOffset;
  18476. if (node.trailingComments && node.trailingComments.length > 0) {
  18477. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  18478. end = lastCommentNode.end + startOffset;
  18479. }
  18480. while (end <= source.length) {
  18481. if (!/\s/.test(source.charAt(end))) {
  18482. break;
  18483. }
  18484. end++;
  18485. }
  18486. ctx.s.move(start, end, 0);
  18487. }
  18488. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  18489. let isUsedInTemplate = needTemplateUsageCheck;
  18490. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  18491. isUsedInTemplate = isImportUsed(local, sfc);
  18492. }
  18493. ctx.userImports[local] = {
  18494. isType,
  18495. imported,
  18496. local,
  18497. source: source2,
  18498. isFromSetup,
  18499. isUsedInTemplate
  18500. };
  18501. }
  18502. function checkInvalidScopeReference(node, method) {
  18503. if (!node) return;
  18504. CompilerDOM.walkIdentifiers(node, (id) => {
  18505. const binding = setupBindings[id.name];
  18506. if (binding && binding !== "literal-const") {
  18507. ctx.error(
  18508. `\`${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.`,
  18509. id
  18510. );
  18511. }
  18512. });
  18513. }
  18514. const scriptAst = ctx.scriptAst;
  18515. const scriptSetupAst = ctx.scriptSetupAst;
  18516. if (scriptAst) {
  18517. for (const node of scriptAst.body) {
  18518. if (node.type === "ImportDeclaration") {
  18519. for (const specifier of node.specifiers) {
  18520. const imported = getImportedName(specifier);
  18521. registerUserImport(
  18522. node.source.value,
  18523. specifier.local.name,
  18524. imported,
  18525. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  18526. false,
  18527. !options.inlineTemplate
  18528. );
  18529. }
  18530. }
  18531. }
  18532. }
  18533. for (const node of scriptSetupAst.body) {
  18534. if (node.type === "ImportDeclaration") {
  18535. hoistNode(node);
  18536. let removed = 0;
  18537. const removeSpecifier = (i) => {
  18538. const removeLeft = i > removed;
  18539. removed++;
  18540. const current = node.specifiers[i];
  18541. const next = node.specifiers[i + 1];
  18542. ctx.s.remove(
  18543. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  18544. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  18545. );
  18546. };
  18547. for (let i = 0; i < node.specifiers.length; i++) {
  18548. const specifier = node.specifiers[i];
  18549. const local = specifier.local.name;
  18550. const imported = getImportedName(specifier);
  18551. const source2 = node.source.value;
  18552. const existing = ctx.userImports[local];
  18553. if (source2 === "vue" && MACROS.includes(imported)) {
  18554. if (local === imported) {
  18555. warnOnce(
  18556. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  18557. );
  18558. } else {
  18559. ctx.error(
  18560. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  18561. specifier
  18562. );
  18563. }
  18564. removeSpecifier(i);
  18565. } else if (existing) {
  18566. if (existing.source === source2 && existing.imported === imported) {
  18567. removeSpecifier(i);
  18568. } else {
  18569. ctx.error(
  18570. `different imports aliased to same local name.`,
  18571. specifier
  18572. );
  18573. }
  18574. } else {
  18575. registerUserImport(
  18576. source2,
  18577. local,
  18578. imported,
  18579. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  18580. true,
  18581. !options.inlineTemplate
  18582. );
  18583. }
  18584. }
  18585. if (node.specifiers.length && removed === node.specifiers.length) {
  18586. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  18587. }
  18588. }
  18589. }
  18590. const vueImportAliases = {};
  18591. for (const key in ctx.userImports) {
  18592. const { source: source2, imported, local } = ctx.userImports[key];
  18593. if (source2 === "vue") vueImportAliases[imported] = local;
  18594. }
  18595. if (script && scriptAst) {
  18596. for (const node of scriptAst.body) {
  18597. if (node.type === "ExportDefaultDeclaration") {
  18598. defaultExport = node;
  18599. let optionProperties;
  18600. if (defaultExport.declaration.type === "ObjectExpression") {
  18601. optionProperties = defaultExport.declaration.properties;
  18602. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  18603. optionProperties = defaultExport.declaration.arguments[0].properties;
  18604. }
  18605. if (optionProperties) {
  18606. for (const p of optionProperties) {
  18607. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  18608. ctx.hasDefaultExportName = true;
  18609. }
  18610. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  18611. ctx.hasDefaultExportRender = true;
  18612. }
  18613. }
  18614. }
  18615. const start = node.start + scriptStartOffset;
  18616. const end = node.declaration.start + scriptStartOffset;
  18617. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  18618. } else if (node.type === "ExportNamedDeclaration") {
  18619. const defaultSpecifier = node.specifiers.find(
  18620. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  18621. );
  18622. if (defaultSpecifier) {
  18623. defaultExport = node;
  18624. if (node.specifiers.length > 1) {
  18625. ctx.s.remove(
  18626. defaultSpecifier.start + scriptStartOffset,
  18627. defaultSpecifier.end + scriptStartOffset
  18628. );
  18629. } else {
  18630. ctx.s.remove(
  18631. node.start + scriptStartOffset,
  18632. node.end + scriptStartOffset
  18633. );
  18634. }
  18635. if (node.source) {
  18636. ctx.s.prepend(
  18637. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  18638. `
  18639. );
  18640. } else {
  18641. ctx.s.appendLeft(
  18642. scriptEndOffset,
  18643. `
  18644. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  18645. `
  18646. );
  18647. }
  18648. }
  18649. if (node.declaration) {
  18650. walkDeclaration(
  18651. "script",
  18652. node.declaration,
  18653. scriptBindings,
  18654. vueImportAliases,
  18655. hoistStatic
  18656. );
  18657. }
  18658. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  18659. walkDeclaration(
  18660. "script",
  18661. node,
  18662. scriptBindings,
  18663. vueImportAliases,
  18664. hoistStatic
  18665. );
  18666. }
  18667. }
  18668. if (scriptStartOffset > startOffset) {
  18669. if (!/\n$/.test(script.content.trim())) {
  18670. ctx.s.appendLeft(scriptEndOffset, `
  18671. `);
  18672. }
  18673. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  18674. }
  18675. }
  18676. for (const node of scriptSetupAst.body) {
  18677. if (node.type === "ExpressionStatement") {
  18678. const expr = CompilerDOM.unwrapTSNode(node.expression);
  18679. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  18680. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  18681. } else if (processDefineExpose(ctx, expr)) {
  18682. const callee = expr.callee;
  18683. ctx.s.overwrite(
  18684. callee.start + startOffset,
  18685. callee.end + startOffset,
  18686. "__expose"
  18687. );
  18688. } else {
  18689. processDefineModel(ctx, expr);
  18690. }
  18691. }
  18692. if (node.type === "VariableDeclaration" && !node.declare) {
  18693. const total = node.declarations.length;
  18694. let left = total;
  18695. let lastNonRemoved;
  18696. for (let i = 0; i < total; i++) {
  18697. const decl = node.declarations[i];
  18698. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  18699. if (init) {
  18700. if (processDefineOptions(ctx, init)) {
  18701. ctx.error(
  18702. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  18703. node
  18704. );
  18705. }
  18706. const isDefineProps = processDefineProps(ctx, init, decl.id);
  18707. if (ctx.propsDestructureRestId) {
  18708. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  18709. }
  18710. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  18711. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  18712. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  18713. if (left === 1) {
  18714. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  18715. } else {
  18716. let start = decl.start + startOffset;
  18717. let end = decl.end + startOffset;
  18718. if (i === total - 1) {
  18719. start = node.declarations[lastNonRemoved].end + startOffset;
  18720. } else {
  18721. end = node.declarations[i + 1].start + startOffset;
  18722. }
  18723. ctx.s.remove(start, end);
  18724. left--;
  18725. }
  18726. } else if (isDefineEmits) {
  18727. ctx.s.overwrite(
  18728. startOffset + init.start,
  18729. startOffset + init.end,
  18730. "__emit"
  18731. );
  18732. } else {
  18733. lastNonRemoved = i;
  18734. }
  18735. }
  18736. }
  18737. }
  18738. let isAllLiteral = false;
  18739. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  18740. isAllLiteral = walkDeclaration(
  18741. "scriptSetup",
  18742. node,
  18743. setupBindings,
  18744. vueImportAliases,
  18745. hoistStatic
  18746. );
  18747. }
  18748. if (hoistStatic && isAllLiteral) {
  18749. hoistNode(node);
  18750. }
  18751. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  18752. const scope = [scriptSetupAst.body];
  18753. estreeWalker.walk(node, {
  18754. enter(child, parent) {
  18755. if (CompilerDOM.isFunctionType(child)) {
  18756. this.skip();
  18757. }
  18758. if (child.type === "BlockStatement") {
  18759. scope.push(child.body);
  18760. }
  18761. if (child.type === "AwaitExpression") {
  18762. hasAwait = true;
  18763. const currentScope = scope[scope.length - 1];
  18764. const needsSemi = currentScope.some((n, i) => {
  18765. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  18766. });
  18767. processAwait(
  18768. ctx,
  18769. child,
  18770. needsSemi,
  18771. parent.type === "ExpressionStatement"
  18772. );
  18773. }
  18774. },
  18775. exit(node2) {
  18776. if (node2.type === "BlockStatement") scope.pop();
  18777. }
  18778. });
  18779. }
  18780. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  18781. ctx.error(
  18782. `<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.`,
  18783. node
  18784. );
  18785. }
  18786. if (ctx.isTS) {
  18787. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  18788. if (node.type !== "TSEnumDeclaration") {
  18789. hoistNode(node);
  18790. }
  18791. }
  18792. }
  18793. }
  18794. if (ctx.propsDestructureDecl) {
  18795. transformDestructuredProps(ctx, vueImportAliases);
  18796. }
  18797. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  18798. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  18799. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  18800. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  18801. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  18802. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  18803. for (const node of runtimeOptionNodes) {
  18804. checkInvalidScopeReference(node, DEFINE_MODEL);
  18805. }
  18806. }
  18807. if (script) {
  18808. if (startOffset < scriptStartOffset) {
  18809. ctx.s.remove(0, startOffset);
  18810. ctx.s.remove(endOffset, scriptStartOffset);
  18811. ctx.s.remove(scriptEndOffset, source.length);
  18812. } else {
  18813. ctx.s.remove(0, scriptStartOffset);
  18814. ctx.s.remove(scriptEndOffset, startOffset);
  18815. ctx.s.remove(endOffset, source.length);
  18816. }
  18817. } else {
  18818. ctx.s.remove(0, startOffset);
  18819. ctx.s.remove(endOffset, source.length);
  18820. }
  18821. if (scriptAst) {
  18822. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  18823. }
  18824. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  18825. ctx.userImports
  18826. )) {
  18827. if (isType) continue;
  18828. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  18829. }
  18830. for (const key in scriptBindings) {
  18831. ctx.bindingMetadata[key] = scriptBindings[key];
  18832. }
  18833. for (const key in setupBindings) {
  18834. ctx.bindingMetadata[key] = setupBindings[key];
  18835. }
  18836. if (sfc.cssVars.length && // no need to do this when targeting SSR
  18837. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  18838. ctx.helperImports.add(CSS_VARS_HELPER);
  18839. ctx.helperImports.add("unref");
  18840. ctx.s.prependLeft(
  18841. startOffset,
  18842. `
  18843. ${genCssVarsCode(
  18844. sfc.cssVars,
  18845. ctx.bindingMetadata,
  18846. scopeId,
  18847. !!options.isProd
  18848. )}
  18849. `
  18850. );
  18851. }
  18852. let args = `__props`;
  18853. if (ctx.propsTypeDecl) {
  18854. args += `: any`;
  18855. }
  18856. if (ctx.propsDecl) {
  18857. if (ctx.propsDestructureRestId) {
  18858. ctx.s.overwrite(
  18859. startOffset + ctx.propsCall.start,
  18860. startOffset + ctx.propsCall.end,
  18861. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  18862. Object.keys(ctx.propsDestructuredBindings)
  18863. )})`
  18864. );
  18865. ctx.s.overwrite(
  18866. startOffset + ctx.propsDestructureDecl.start,
  18867. startOffset + ctx.propsDestructureDecl.end,
  18868. ctx.propsDestructureRestId
  18869. );
  18870. } else if (!ctx.propsDestructureDecl) {
  18871. ctx.s.overwrite(
  18872. startOffset + ctx.propsCall.start,
  18873. startOffset + ctx.propsCall.end,
  18874. "__props"
  18875. );
  18876. }
  18877. }
  18878. if (hasAwait) {
  18879. const any = ctx.isTS ? `: any` : ``;
  18880. ctx.s.prependLeft(startOffset, `
  18881. let __temp${any}, __restore${any}
  18882. `);
  18883. }
  18884. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  18885. if (ctx.emitDecl) {
  18886. destructureElements.push(`emit: __emit`);
  18887. }
  18888. if (destructureElements.length) {
  18889. args += `, { ${destructureElements.join(", ")} }`;
  18890. }
  18891. let returned;
  18892. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  18893. const allBindings = {
  18894. ...scriptBindings,
  18895. ...setupBindings
  18896. };
  18897. for (const key in ctx.userImports) {
  18898. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  18899. allBindings[key] = true;
  18900. }
  18901. }
  18902. returned = `{ `;
  18903. for (const key in allBindings) {
  18904. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  18905. returned += `get ${key}() { return ${key} }, `;
  18906. } else if (ctx.bindingMetadata[key] === "setup-let") {
  18907. const setArg = key === "v" ? `_v` : `v`;
  18908. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  18909. } else {
  18910. returned += `${key}, `;
  18911. }
  18912. }
  18913. returned = returned.replace(/, $/, "") + ` }`;
  18914. } else {
  18915. if (sfc.template && !sfc.template.src) {
  18916. if (options.templateOptions && options.templateOptions.ssr) {
  18917. hasInlinedSsrRenderFn = true;
  18918. }
  18919. const { code, ast, preamble, tips, errors } = compileTemplate({
  18920. filename,
  18921. ast: sfc.template.ast,
  18922. source: sfc.template.content,
  18923. inMap: sfc.template.map,
  18924. ...options.templateOptions,
  18925. id: scopeId,
  18926. scoped: sfc.styles.some((s) => s.scoped),
  18927. isProd: options.isProd,
  18928. ssrCssVars: sfc.cssVars,
  18929. compilerOptions: {
  18930. ...options.templateOptions && options.templateOptions.compilerOptions,
  18931. inline: true,
  18932. isTS: ctx.isTS,
  18933. bindingMetadata: ctx.bindingMetadata
  18934. }
  18935. });
  18936. if (tips.length) {
  18937. tips.forEach(warnOnce);
  18938. }
  18939. const err = errors[0];
  18940. if (typeof err === "string") {
  18941. throw new Error(err);
  18942. } else if (err) {
  18943. if (err.loc) {
  18944. err.message += `
  18945. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  18946. source,
  18947. err.loc.start.offset,
  18948. err.loc.end.offset
  18949. ) + `
  18950. `;
  18951. }
  18952. throw err;
  18953. }
  18954. if (preamble) {
  18955. ctx.s.prepend(preamble);
  18956. }
  18957. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  18958. ctx.helperImports.delete("unref");
  18959. }
  18960. returned = code;
  18961. } else {
  18962. returned = `() => {}`;
  18963. }
  18964. }
  18965. if (!options.inlineTemplate && true) {
  18966. ctx.s.appendRight(
  18967. endOffset,
  18968. `
  18969. const __returned__ = ${returned}
  18970. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  18971. return __returned__
  18972. }
  18973. `
  18974. );
  18975. } else {
  18976. ctx.s.appendRight(endOffset, `
  18977. return ${returned}
  18978. }
  18979. `);
  18980. }
  18981. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  18982. let runtimeOptions = ``;
  18983. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  18984. const match = filename.match(/([^/\\]+)\.\w+$/);
  18985. if (match) {
  18986. runtimeOptions += `
  18987. __name: '${match[1]}',`;
  18988. }
  18989. }
  18990. if (hasInlinedSsrRenderFn) {
  18991. runtimeOptions += `
  18992. __ssrInlineRender: true,`;
  18993. }
  18994. const propsDecl = genRuntimeProps(ctx);
  18995. if (propsDecl) runtimeOptions += `
  18996. props: ${propsDecl},`;
  18997. const emitsDecl = genRuntimeEmits(ctx);
  18998. if (emitsDecl) runtimeOptions += `
  18999. emits: ${emitsDecl},`;
  19000. let definedOptions = "";
  19001. if (ctx.optionsRuntimeDecl) {
  19002. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  19003. }
  19004. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  19005. `;
  19006. if (ctx.isTS) {
  19007. const def = (defaultExport ? `
  19008. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  19009. ...${definedOptions},` : "");
  19010. ctx.s.prependLeft(
  19011. startOffset,
  19012. `
  19013. ${genDefaultAs} /*#__PURE__*/${ctx.helper(
  19014. `defineComponent`
  19015. )}({${def}${runtimeOptions}
  19016. ${hasAwait ? `async ` : ``}setup(${args}) {
  19017. ${exposeCall}`
  19018. );
  19019. ctx.s.appendRight(endOffset, `})`);
  19020. } else {
  19021. if (defaultExport || definedOptions) {
  19022. ctx.s.prependLeft(
  19023. startOffset,
  19024. `
  19025. ${genDefaultAs} /*#__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  19026. ${hasAwait ? `async ` : ``}setup(${args}) {
  19027. ${exposeCall}`
  19028. );
  19029. ctx.s.appendRight(endOffset, `})`);
  19030. } else {
  19031. ctx.s.prependLeft(
  19032. startOffset,
  19033. `
  19034. ${genDefaultAs} {${runtimeOptions}
  19035. ${hasAwait ? `async ` : ``}setup(${args}) {
  19036. ${exposeCall}`
  19037. );
  19038. ctx.s.appendRight(endOffset, `}`);
  19039. }
  19040. }
  19041. if (ctx.helperImports.size > 0) {
  19042. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  19043. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  19044. ctx.s.prepend(
  19045. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  19046. `
  19047. );
  19048. }
  19049. return {
  19050. ...scriptSetup,
  19051. bindings: ctx.bindingMetadata,
  19052. imports: ctx.userImports,
  19053. content: ctx.s.toString(),
  19054. map: options.sourceMap !== false ? ctx.s.generateMap({
  19055. source: filename,
  19056. hires: true,
  19057. includeContent: true
  19058. }) : void 0,
  19059. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  19060. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  19061. deps: ctx.deps ? [...ctx.deps] : void 0
  19062. };
  19063. }
  19064. function registerBinding(bindings, node, type) {
  19065. bindings[node.name] = type;
  19066. }
  19067. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic) {
  19068. let isAllLiteral = false;
  19069. if (node.type === "VariableDeclaration") {
  19070. const isConst = node.kind === "const";
  19071. isAllLiteral = isConst && node.declarations.every(
  19072. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  19073. );
  19074. for (const { id, init: _init } of node.declarations) {
  19075. const init = _init && CompilerDOM.unwrapTSNode(_init);
  19076. const isConstMacroCall = isConst && isCallOf(
  19077. init,
  19078. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  19079. );
  19080. if (id.type === "Identifier") {
  19081. let bindingType;
  19082. const userReactiveBinding = userImportAliases["reactive"];
  19083. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  19084. bindingType = "literal-const";
  19085. } else if (isCallOf(init, userReactiveBinding)) {
  19086. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  19087. } else if (
  19088. // if a declaration is a const literal, we can mark it so that
  19089. // the generated render fn code doesn't need to unref() it
  19090. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  19091. ) {
  19092. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  19093. } else if (isConst) {
  19094. if (isCallOf(
  19095. init,
  19096. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === DEFINE_MODEL
  19097. )) {
  19098. bindingType = "setup-ref";
  19099. } else {
  19100. bindingType = "setup-maybe-ref";
  19101. }
  19102. } else {
  19103. bindingType = "setup-let";
  19104. }
  19105. registerBinding(bindings, id, bindingType);
  19106. } else {
  19107. if (isCallOf(init, DEFINE_PROPS)) {
  19108. continue;
  19109. }
  19110. if (id.type === "ObjectPattern") {
  19111. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  19112. } else if (id.type === "ArrayPattern") {
  19113. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  19114. }
  19115. }
  19116. }
  19117. } else if (node.type === "TSEnumDeclaration") {
  19118. isAllLiteral = node.members.every(
  19119. (member) => !member.initializer || isStaticNode(member.initializer)
  19120. );
  19121. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  19122. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  19123. bindings[node.id.name] = "setup-const";
  19124. }
  19125. return isAllLiteral;
  19126. }
  19127. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  19128. for (const p of node.properties) {
  19129. if (p.type === "ObjectProperty") {
  19130. if (p.key.type === "Identifier" && p.key === p.value) {
  19131. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  19132. registerBinding(bindings, p.key, type);
  19133. } else {
  19134. walkPattern(p.value, bindings, isConst, isDefineCall);
  19135. }
  19136. } else {
  19137. const type = isConst ? "setup-const" : "setup-let";
  19138. registerBinding(bindings, p.argument, type);
  19139. }
  19140. }
  19141. }
  19142. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  19143. for (const e of node.elements) {
  19144. e && walkPattern(e, bindings, isConst, isDefineCall);
  19145. }
  19146. }
  19147. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  19148. if (node.type === "Identifier") {
  19149. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  19150. registerBinding(bindings, node, type);
  19151. } else if (node.type === "RestElement") {
  19152. const type = isConst ? "setup-const" : "setup-let";
  19153. registerBinding(bindings, node.argument, type);
  19154. } else if (node.type === "ObjectPattern") {
  19155. walkObjectPattern(node, bindings, isConst);
  19156. } else if (node.type === "ArrayPattern") {
  19157. walkArrayPattern(node, bindings, isConst);
  19158. } else if (node.type === "AssignmentPattern") {
  19159. if (node.left.type === "Identifier") {
  19160. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  19161. registerBinding(bindings, node.left, type);
  19162. } else {
  19163. walkPattern(node.left, bindings, isConst);
  19164. }
  19165. }
  19166. }
  19167. function canNeverBeRef(node, userReactiveImport) {
  19168. if (isCallOf(node, userReactiveImport)) {
  19169. return true;
  19170. }
  19171. switch (node.type) {
  19172. case "UnaryExpression":
  19173. case "BinaryExpression":
  19174. case "ArrayExpression":
  19175. case "ObjectExpression":
  19176. case "FunctionExpression":
  19177. case "ArrowFunctionExpression":
  19178. case "UpdateExpression":
  19179. case "ClassExpression":
  19180. case "TaggedTemplateExpression":
  19181. return true;
  19182. case "SequenceExpression":
  19183. return canNeverBeRef(
  19184. node.expressions[node.expressions.length - 1],
  19185. userReactiveImport
  19186. );
  19187. default:
  19188. if (isLiteralNode(node)) {
  19189. return true;
  19190. }
  19191. return false;
  19192. }
  19193. }
  19194. function isStaticNode(node) {
  19195. node = CompilerDOM.unwrapTSNode(node);
  19196. switch (node.type) {
  19197. case "UnaryExpression":
  19198. return isStaticNode(node.argument);
  19199. case "LogicalExpression":
  19200. case "BinaryExpression":
  19201. return isStaticNode(node.left) && isStaticNode(node.right);
  19202. case "ConditionalExpression": {
  19203. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  19204. }
  19205. case "SequenceExpression":
  19206. case "TemplateLiteral":
  19207. return node.expressions.every((expr) => isStaticNode(expr));
  19208. case "ParenthesizedExpression":
  19209. return isStaticNode(node.expression);
  19210. case "StringLiteral":
  19211. case "NumericLiteral":
  19212. case "BooleanLiteral":
  19213. case "NullLiteral":
  19214. case "BigIntLiteral":
  19215. return true;
  19216. }
  19217. return false;
  19218. }
  19219. const version = "3.4.38";
  19220. const parseCache = parseCache$1;
  19221. const errorMessages = {
  19222. ...CompilerDOM.errorMessages,
  19223. ...CompilerDOM.DOMErrorMessages
  19224. };
  19225. const walk = estreeWalker.walk;
  19226. const shouldTransformRef = () => false;
  19227. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  19228. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  19229. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  19230. exports.isStaticProperty = compilerCore.isStaticProperty;
  19231. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  19232. exports.MagicString = MagicString;
  19233. exports.babelParse = parser$1.parse;
  19234. exports.compileScript = compileScript;
  19235. exports.compileStyle = compileStyle;
  19236. exports.compileStyleAsync = compileStyleAsync;
  19237. exports.compileTemplate = compileTemplate;
  19238. exports.errorMessages = errorMessages;
  19239. exports.extractRuntimeEmits = extractRuntimeEmits;
  19240. exports.extractRuntimeProps = extractRuntimeProps;
  19241. exports.inferRuntimeType = inferRuntimeType;
  19242. exports.invalidateTypeCache = invalidateTypeCache;
  19243. exports.parse = parse$2;
  19244. exports.parseCache = parseCache;
  19245. exports.registerTS = registerTS;
  19246. exports.resolveTypeElements = resolveTypeElements;
  19247. exports.rewriteDefault = rewriteDefault;
  19248. exports.rewriteDefaultAST = rewriteDefaultAST;
  19249. exports.shouldTransformRef = shouldTransformRef;
  19250. exports.version = version;
  19251. exports.walk = walk;