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

compiler-sfc.esm-browser.js 1.6MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147
  1. /**
  2. * @vue/compiler-sfc v3.5.38
  3. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  4. * @license MIT
  5. **/
  6. // @__NO_SIDE_EFFECTS__
  7. function makeMap(str) {
  8. const map = /* @__PURE__ */ Object.create(null);
  9. for (const key of str.split(",")) map[key] = 1;
  10. return (val) => val in map;
  11. }
  12. const EMPTY_OBJ = Object.freeze({}) ;
  13. const NOOP = () => {
  14. };
  15. const NO = () => false;
  16. const isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter
  17. (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97);
  18. const extend = Object.assign;
  19. const hasOwnProperty$3 = Object.prototype.hasOwnProperty;
  20. const hasOwn = (val, key) => hasOwnProperty$3.call(val, key);
  21. const isArray$3 = Array.isArray;
  22. const isMap = (val) => toTypeString(val) === "[object Map]";
  23. const isSet = (val) => toTypeString(val) === "[object Set]";
  24. const isFunction$1 = (val) => typeof val === "function";
  25. const isString$1 = (val) => typeof val === "string";
  26. const isSymbol$1 = (val) => typeof val === "symbol";
  27. const isObject$2 = (val) => val !== null && typeof val === "object";
  28. const objectToString$1 = Object.prototype.toString;
  29. const toTypeString = (value) => objectToString$1.call(value);
  30. const isPlainObject = (val) => toTypeString(val) === "[object Object]";
  31. const isReservedProp = /* @__PURE__ */ makeMap(
  32. // the leading comma is intentional so empty string "" is also included
  33. ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"
  34. );
  35. const isBuiltInDirective = /* @__PURE__ */ makeMap(
  36. "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo"
  37. );
  38. const cacheStringFunction = (fn) => {
  39. const cache = /* @__PURE__ */ Object.create(null);
  40. return ((str) => {
  41. const hit = cache[str];
  42. return hit || (cache[str] = fn(str));
  43. });
  44. };
  45. const camelizeRE = /-\w/g;
  46. const camelize = cacheStringFunction(
  47. (str) => {
  48. return str.replace(camelizeRE, (c) => c.slice(1).toUpperCase());
  49. }
  50. );
  51. const hyphenateRE = /\B([A-Z])/g;
  52. const hyphenate = cacheStringFunction(
  53. (str) => str.replace(hyphenateRE, "-$1").toLowerCase()
  54. );
  55. const capitalize = cacheStringFunction((str) => {
  56. return str.charAt(0).toUpperCase() + str.slice(1);
  57. });
  58. const toHandlerKey = cacheStringFunction(
  59. (str) => {
  60. const s = str ? `on${capitalize(str)}` : ``;
  61. return s;
  62. }
  63. );
  64. const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
  65. function genPropsAccessExp(name) {
  66. return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`;
  67. }
  68. function genCacheKey(source, options) {
  69. return source + JSON.stringify(
  70. options,
  71. (_, val) => typeof val === "function" ? val.toString() : val
  72. );
  73. }
  74. const PatchFlagNames = {
  75. [1]: `TEXT`,
  76. [2]: `CLASS`,
  77. [4]: `STYLE`,
  78. [8]: `PROPS`,
  79. [16]: `FULL_PROPS`,
  80. [32]: `NEED_HYDRATION`,
  81. [64]: `STABLE_FRAGMENT`,
  82. [128]: `KEYED_FRAGMENT`,
  83. [256]: `UNKEYED_FRAGMENT`,
  84. [512]: `NEED_PATCH`,
  85. [1024]: `DYNAMIC_SLOTS`,
  86. [2048]: `DEV_ROOT_FRAGMENT`,
  87. [-1]: `CACHED`,
  88. [-2]: `BAIL`
  89. };
  90. const slotFlagsText = {
  91. [1]: "STABLE",
  92. [2]: "DYNAMIC",
  93. [3]: "FORWARDED"
  94. };
  95. const GLOBALS_ALLOWED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol";
  96. const isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED);
  97. const range = 2;
  98. function generateCodeFrame(source, start = 0, end = source.length) {
  99. start = Math.max(0, Math.min(start, source.length));
  100. end = Math.max(0, Math.min(end, source.length));
  101. if (start > end) return "";
  102. let lines = source.split(/(\r?\n)/);
  103. const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
  104. lines = lines.filter((_, idx) => idx % 2 === 0);
  105. let count = 0;
  106. const res = [];
  107. for (let i = 0; i < lines.length; i++) {
  108. count += lines[i].length + (newlineSequences[i] && newlineSequences[i].length || 0);
  109. if (count >= start) {
  110. for (let j = i - range; j <= i + range || end > count; j++) {
  111. if (j < 0 || j >= lines.length) continue;
  112. const line = j + 1;
  113. res.push(
  114. `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`
  115. );
  116. const lineLength = lines[j].length;
  117. const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0;
  118. if (j === i) {
  119. const pad = start - (count - (lineLength + newLineSeqLength));
  120. const length = Math.max(
  121. 1,
  122. end > count ? lineLength - pad : end - start
  123. );
  124. res.push(` | ` + " ".repeat(pad) + "^".repeat(length));
  125. } else if (j > i) {
  126. if (end > count) {
  127. const length = Math.max(Math.min(end - count, lineLength), 1);
  128. res.push(` | ` + "^".repeat(length));
  129. }
  130. count += lineLength + newLineSeqLength;
  131. }
  132. }
  133. break;
  134. }
  135. }
  136. return res.join("\n");
  137. }
  138. function normalizeStyle(value) {
  139. if (isArray$3(value)) {
  140. const res = {};
  141. for (let i = 0; i < value.length; i++) {
  142. const item = value[i];
  143. const normalized = isString$1(item) ? parseStringStyle(item) : normalizeStyle(item);
  144. if (normalized) {
  145. for (const key in normalized) {
  146. res[key] = normalized[key];
  147. }
  148. }
  149. }
  150. return res;
  151. } else if (isString$1(value) || isObject$2(value)) {
  152. return value;
  153. }
  154. }
  155. const listDelimiterRE = /;(?![^(]*\))/g;
  156. const propertyDelimiterRE = /:([^]+)/;
  157. const styleCommentRE = /\/\*[^]*?\*\//g;
  158. function parseStringStyle(cssText) {
  159. const ret = {};
  160. cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => {
  161. if (item) {
  162. const tmp = item.split(propertyDelimiterRE);
  163. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  164. }
  165. });
  166. return ret;
  167. }
  168. function stringifyStyle(styles) {
  169. if (!styles) return "";
  170. if (isString$1(styles)) return styles;
  171. let ret = "";
  172. for (const key in styles) {
  173. const value = styles[key];
  174. if (isString$1(value) || typeof value === "number") {
  175. const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
  176. ret += `${normalizedKey}:${value};`;
  177. }
  178. }
  179. return ret;
  180. }
  181. function normalizeClass(value) {
  182. let res = "";
  183. if (isString$1(value)) {
  184. res = value;
  185. } else if (isArray$3(value)) {
  186. for (let i = 0; i < value.length; i++) {
  187. const normalized = normalizeClass(value[i]);
  188. if (normalized) {
  189. res += normalized + " ";
  190. }
  191. }
  192. } else if (isObject$2(value)) {
  193. for (const name in value) {
  194. if (value[name]) {
  195. res += name + " ";
  196. }
  197. }
  198. }
  199. return res.trim();
  200. }
  201. const HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot";
  202. const SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view";
  203. const MATH_TAGS = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics";
  204. const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr";
  205. const isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS);
  206. const isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS);
  207. const isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS);
  208. const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS);
  209. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  210. const isBooleanAttr = /* @__PURE__ */ makeMap(
  211. specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`
  212. );
  213. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
  214. const attrValidationCache = {};
  215. function isSSRSafeAttrName(name) {
  216. if (attrValidationCache.hasOwnProperty(name)) {
  217. return attrValidationCache[name];
  218. }
  219. const isUnsafe = unsafeAttrCharRE.test(name);
  220. if (isUnsafe) {
  221. console.error(`unsafe attribute name: ${name}`);
  222. }
  223. return attrValidationCache[name] = !isUnsafe;
  224. }
  225. const propsToAttrMap = {
  226. acceptCharset: "accept-charset",
  227. className: "class",
  228. htmlFor: "for",
  229. httpEquiv: "http-equiv"
  230. };
  231. const isKnownHtmlAttr = /* @__PURE__ */ makeMap(
  232. `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap`
  233. );
  234. const isKnownSvgAttr = /* @__PURE__ */ makeMap(
  235. `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`
  236. );
  237. const isKnownMathMLAttr = /* @__PURE__ */ makeMap(
  238. `accent,accentunder,actiontype,align,alignmentscope,altimg,altimg-height,altimg-valign,altimg-width,alttext,bevelled,close,columnsalign,columnlines,columnspan,denomalign,depth,dir,display,displaystyle,encoding,equalcolumns,equalrows,fence,fontstyle,fontweight,form,frame,framespacing,groupalign,height,href,id,indentalign,indentalignfirst,indentalignlast,indentshift,indentshiftfirst,indentshiftlast,indextype,justify,largetop,largeop,lquote,lspace,mathbackground,mathcolor,mathsize,mathvariant,maxsize,minlabelspacing,mode,other,overflow,position,rowalign,rowlines,rowspan,rquote,rspace,scriptlevel,scriptminsize,scriptsizemultiplier,selection,separator,separators,shift,side,src,stackalign,stretchy,subscriptshift,superscriptshift,symmetric,voffset,width,widths,xlink:href,xlink:show,xlink:type,xmlns`
  239. );
  240. const escapeRE = /["'&<>]/;
  241. function escapeHtml(string) {
  242. const str = "" + string;
  243. const match = escapeRE.exec(str);
  244. if (!match) {
  245. return str;
  246. }
  247. let html = "";
  248. let escaped;
  249. let index;
  250. let lastIndex = 0;
  251. for (index = match.index; index < str.length; index++) {
  252. switch (str.charCodeAt(index)) {
  253. case 34:
  254. escaped = "&quot;";
  255. break;
  256. case 38:
  257. escaped = "&amp;";
  258. break;
  259. case 39:
  260. escaped = "&#39;";
  261. break;
  262. case 60:
  263. escaped = "&lt;";
  264. break;
  265. case 62:
  266. escaped = "&gt;";
  267. break;
  268. default:
  269. continue;
  270. }
  271. if (lastIndex !== index) {
  272. html += str.slice(lastIndex, index);
  273. }
  274. lastIndex = index + 1;
  275. html += escaped;
  276. }
  277. return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
  278. }
  279. const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g;
  280. function getEscapedCssVarName(key, doubleEscape) {
  281. return key.replace(
  282. cssVarNameEscapeSymbolsRE,
  283. (s) => doubleEscape ? s === '"' ? '\\\\\\"' : `\\\\${s}` : `\\${s}`
  284. );
  285. }
  286. const isRef = (val) => {
  287. return !!(val && val["__v_isRef"] === true);
  288. };
  289. const toDisplayString = (val) => {
  290. return isString$1(val) ? val : val == null ? "" : isArray$3(val) || isObject$2(val) && (val.toString === objectToString$1 || !isFunction$1(val.toString)) ? isRef(val) ? toDisplayString(val.value) : JSON.stringify(val, replacer, 2) : String(val);
  291. };
  292. const replacer = (_key, val) => {
  293. if (isRef(val)) {
  294. return replacer(_key, val.value);
  295. } else if (isMap(val)) {
  296. return {
  297. [`Map(${val.size})`]: [...val.entries()].reduce(
  298. (entries, [key, val2], i) => {
  299. entries[stringifySymbol(key, i) + " =>"] = val2;
  300. return entries;
  301. },
  302. {}
  303. )
  304. };
  305. } else if (isSet(val)) {
  306. return {
  307. [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v))
  308. };
  309. } else if (isSymbol$1(val)) {
  310. return stringifySymbol(val);
  311. } else if (isObject$2(val) && !isArray$3(val) && !isPlainObject(val)) {
  312. return String(val);
  313. }
  314. return val;
  315. };
  316. const stringifySymbol = (v, i = "") => {
  317. var _a;
  318. return (
  319. // Symbol.description in es2019+ so we need to cast here to pass
  320. // the lib: es2016 check
  321. isSymbol$1(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v
  322. );
  323. };
  324. const FRAGMENT = /* @__PURE__ */ Symbol(`Fragment` );
  325. const TELEPORT = /* @__PURE__ */ Symbol(`Teleport` );
  326. const SUSPENSE = /* @__PURE__ */ Symbol(`Suspense` );
  327. const KEEP_ALIVE = /* @__PURE__ */ Symbol(`KeepAlive` );
  328. const BASE_TRANSITION = /* @__PURE__ */ Symbol(
  329. `BaseTransition`
  330. );
  331. const OPEN_BLOCK = /* @__PURE__ */ Symbol(`openBlock` );
  332. const CREATE_BLOCK = /* @__PURE__ */ Symbol(`createBlock` );
  333. const CREATE_ELEMENT_BLOCK = /* @__PURE__ */ Symbol(
  334. `createElementBlock`
  335. );
  336. const CREATE_VNODE = /* @__PURE__ */ Symbol(`createVNode` );
  337. const CREATE_ELEMENT_VNODE = /* @__PURE__ */ Symbol(
  338. `createElementVNode`
  339. );
  340. const CREATE_COMMENT = /* @__PURE__ */ Symbol(
  341. `createCommentVNode`
  342. );
  343. const CREATE_TEXT = /* @__PURE__ */ Symbol(
  344. `createTextVNode`
  345. );
  346. const CREATE_STATIC = /* @__PURE__ */ Symbol(
  347. `createStaticVNode`
  348. );
  349. const RESOLVE_COMPONENT = /* @__PURE__ */ Symbol(
  350. `resolveComponent`
  351. );
  352. const RESOLVE_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol(
  353. `resolveDynamicComponent`
  354. );
  355. const RESOLVE_DIRECTIVE = /* @__PURE__ */ Symbol(
  356. `resolveDirective`
  357. );
  358. const RESOLVE_FILTER = /* @__PURE__ */ Symbol(
  359. `resolveFilter`
  360. );
  361. const WITH_DIRECTIVES = /* @__PURE__ */ Symbol(
  362. `withDirectives`
  363. );
  364. const RENDER_LIST = /* @__PURE__ */ Symbol(`renderList` );
  365. const RENDER_SLOT = /* @__PURE__ */ Symbol(`renderSlot` );
  366. const CREATE_SLOTS = /* @__PURE__ */ Symbol(`createSlots` );
  367. const TO_DISPLAY_STRING = /* @__PURE__ */ Symbol(
  368. `toDisplayString`
  369. );
  370. const MERGE_PROPS = /* @__PURE__ */ Symbol(`mergeProps` );
  371. const NORMALIZE_CLASS = /* @__PURE__ */ Symbol(
  372. `normalizeClass`
  373. );
  374. const NORMALIZE_STYLE = /* @__PURE__ */ Symbol(
  375. `normalizeStyle`
  376. );
  377. const NORMALIZE_PROPS = /* @__PURE__ */ Symbol(
  378. `normalizeProps`
  379. );
  380. const GUARD_REACTIVE_PROPS = /* @__PURE__ */ Symbol(
  381. `guardReactiveProps`
  382. );
  383. const TO_HANDLERS = /* @__PURE__ */ Symbol(`toHandlers` );
  384. const CAMELIZE = /* @__PURE__ */ Symbol(`camelize` );
  385. const CAPITALIZE = /* @__PURE__ */ Symbol(`capitalize` );
  386. const TO_HANDLER_KEY = /* @__PURE__ */ Symbol(
  387. `toHandlerKey`
  388. );
  389. const SET_BLOCK_TRACKING = /* @__PURE__ */ Symbol(
  390. `setBlockTracking`
  391. );
  392. const PUSH_SCOPE_ID = /* @__PURE__ */ Symbol(`pushScopeId` );
  393. const POP_SCOPE_ID = /* @__PURE__ */ Symbol(`popScopeId` );
  394. const WITH_CTX = /* @__PURE__ */ Symbol(`withCtx` );
  395. const UNREF = /* @__PURE__ */ Symbol(`unref` );
  396. const IS_REF = /* @__PURE__ */ Symbol(`isRef` );
  397. const WITH_MEMO = /* @__PURE__ */ Symbol(`withMemo` );
  398. const IS_MEMO_SAME = /* @__PURE__ */ Symbol(`isMemoSame` );
  399. const helperNameMap = {
  400. [FRAGMENT]: `Fragment`,
  401. [TELEPORT]: `Teleport`,
  402. [SUSPENSE]: `Suspense`,
  403. [KEEP_ALIVE]: `KeepAlive`,
  404. [BASE_TRANSITION]: `BaseTransition`,
  405. [OPEN_BLOCK]: `openBlock`,
  406. [CREATE_BLOCK]: `createBlock`,
  407. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  408. [CREATE_VNODE]: `createVNode`,
  409. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  410. [CREATE_COMMENT]: `createCommentVNode`,
  411. [CREATE_TEXT]: `createTextVNode`,
  412. [CREATE_STATIC]: `createStaticVNode`,
  413. [RESOLVE_COMPONENT]: `resolveComponent`,
  414. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  415. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  416. [RESOLVE_FILTER]: `resolveFilter`,
  417. [WITH_DIRECTIVES]: `withDirectives`,
  418. [RENDER_LIST]: `renderList`,
  419. [RENDER_SLOT]: `renderSlot`,
  420. [CREATE_SLOTS]: `createSlots`,
  421. [TO_DISPLAY_STRING]: `toDisplayString`,
  422. [MERGE_PROPS]: `mergeProps`,
  423. [NORMALIZE_CLASS]: `normalizeClass`,
  424. [NORMALIZE_STYLE]: `normalizeStyle`,
  425. [NORMALIZE_PROPS]: `normalizeProps`,
  426. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  427. [TO_HANDLERS]: `toHandlers`,
  428. [CAMELIZE]: `camelize`,
  429. [CAPITALIZE]: `capitalize`,
  430. [TO_HANDLER_KEY]: `toHandlerKey`,
  431. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  432. [PUSH_SCOPE_ID]: `pushScopeId`,
  433. [POP_SCOPE_ID]: `popScopeId`,
  434. [WITH_CTX]: `withCtx`,
  435. [UNREF]: `unref`,
  436. [IS_REF]: `isRef`,
  437. [WITH_MEMO]: `withMemo`,
  438. [IS_MEMO_SAME]: `isMemoSame`
  439. };
  440. function registerRuntimeHelpers(helpers) {
  441. Object.getOwnPropertySymbols(helpers).forEach((s) => {
  442. helperNameMap[s] = helpers[s];
  443. });
  444. }
  445. const Namespaces = {
  446. "HTML": 0,
  447. "0": "HTML",
  448. "SVG": 1,
  449. "1": "SVG",
  450. "MATH_ML": 2,
  451. "2": "MATH_ML"
  452. };
  453. const NodeTypes = {
  454. "ROOT": 0,
  455. "0": "ROOT",
  456. "ELEMENT": 1,
  457. "1": "ELEMENT",
  458. "TEXT": 2,
  459. "2": "TEXT",
  460. "COMMENT": 3,
  461. "3": "COMMENT",
  462. "SIMPLE_EXPRESSION": 4,
  463. "4": "SIMPLE_EXPRESSION",
  464. "INTERPOLATION": 5,
  465. "5": "INTERPOLATION",
  466. "ATTRIBUTE": 6,
  467. "6": "ATTRIBUTE",
  468. "DIRECTIVE": 7,
  469. "7": "DIRECTIVE",
  470. "COMPOUND_EXPRESSION": 8,
  471. "8": "COMPOUND_EXPRESSION",
  472. "IF": 9,
  473. "9": "IF",
  474. "IF_BRANCH": 10,
  475. "10": "IF_BRANCH",
  476. "FOR": 11,
  477. "11": "FOR",
  478. "TEXT_CALL": 12,
  479. "12": "TEXT_CALL",
  480. "VNODE_CALL": 13,
  481. "13": "VNODE_CALL",
  482. "JS_CALL_EXPRESSION": 14,
  483. "14": "JS_CALL_EXPRESSION",
  484. "JS_OBJECT_EXPRESSION": 15,
  485. "15": "JS_OBJECT_EXPRESSION",
  486. "JS_PROPERTY": 16,
  487. "16": "JS_PROPERTY",
  488. "JS_ARRAY_EXPRESSION": 17,
  489. "17": "JS_ARRAY_EXPRESSION",
  490. "JS_FUNCTION_EXPRESSION": 18,
  491. "18": "JS_FUNCTION_EXPRESSION",
  492. "JS_CONDITIONAL_EXPRESSION": 19,
  493. "19": "JS_CONDITIONAL_EXPRESSION",
  494. "JS_CACHE_EXPRESSION": 20,
  495. "20": "JS_CACHE_EXPRESSION",
  496. "JS_BLOCK_STATEMENT": 21,
  497. "21": "JS_BLOCK_STATEMENT",
  498. "JS_TEMPLATE_LITERAL": 22,
  499. "22": "JS_TEMPLATE_LITERAL",
  500. "JS_IF_STATEMENT": 23,
  501. "23": "JS_IF_STATEMENT",
  502. "JS_ASSIGNMENT_EXPRESSION": 24,
  503. "24": "JS_ASSIGNMENT_EXPRESSION",
  504. "JS_SEQUENCE_EXPRESSION": 25,
  505. "25": "JS_SEQUENCE_EXPRESSION",
  506. "JS_RETURN_STATEMENT": 26,
  507. "26": "JS_RETURN_STATEMENT"
  508. };
  509. const ElementTypes = {
  510. "ELEMENT": 0,
  511. "0": "ELEMENT",
  512. "COMPONENT": 1,
  513. "1": "COMPONENT",
  514. "SLOT": 2,
  515. "2": "SLOT",
  516. "TEMPLATE": 3,
  517. "3": "TEMPLATE"
  518. };
  519. const ConstantTypes = {
  520. "NOT_CONSTANT": 0,
  521. "0": "NOT_CONSTANT",
  522. "CAN_SKIP_PATCH": 1,
  523. "1": "CAN_SKIP_PATCH",
  524. "CAN_CACHE": 2,
  525. "2": "CAN_CACHE",
  526. "CAN_STRINGIFY": 3,
  527. "3": "CAN_STRINGIFY"
  528. };
  529. const locStub = {
  530. start: { line: 1, column: 1, offset: 0 },
  531. end: { line: 1, column: 1, offset: 0 },
  532. source: ""
  533. };
  534. function createRoot(children, source = "") {
  535. return {
  536. type: 0,
  537. source,
  538. children,
  539. helpers: /* @__PURE__ */ new Set(),
  540. components: [],
  541. directives: [],
  542. hoists: [],
  543. imports: [],
  544. cached: [],
  545. temps: 0,
  546. codegenNode: void 0,
  547. loc: locStub
  548. };
  549. }
  550. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  551. if (context) {
  552. if (isBlock) {
  553. context.helper(OPEN_BLOCK);
  554. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  555. } else {
  556. context.helper(getVNodeHelper(context.inSSR, isComponent));
  557. }
  558. if (directives) {
  559. context.helper(WITH_DIRECTIVES);
  560. }
  561. }
  562. return {
  563. type: 13,
  564. tag,
  565. props,
  566. children,
  567. patchFlag,
  568. dynamicProps,
  569. directives,
  570. isBlock,
  571. disableTracking,
  572. isComponent,
  573. loc
  574. };
  575. }
  576. function createArrayExpression(elements, loc = locStub) {
  577. return {
  578. type: 17,
  579. loc,
  580. elements
  581. };
  582. }
  583. function createObjectExpression(properties, loc = locStub) {
  584. return {
  585. type: 15,
  586. loc,
  587. properties
  588. };
  589. }
  590. function createObjectProperty(key, value) {
  591. return {
  592. type: 16,
  593. loc: locStub,
  594. key: isString$1(key) ? createSimpleExpression(key, true) : key,
  595. value
  596. };
  597. }
  598. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0) {
  599. return {
  600. type: 4,
  601. loc,
  602. content,
  603. isStatic,
  604. constType: isStatic ? 3 : constType
  605. };
  606. }
  607. function createInterpolation(content, loc) {
  608. return {
  609. type: 5,
  610. loc,
  611. content: isString$1(content) ? createSimpleExpression(content, false, loc) : content
  612. };
  613. }
  614. function createCompoundExpression(children, loc = locStub) {
  615. return {
  616. type: 8,
  617. loc,
  618. children
  619. };
  620. }
  621. function createCallExpression(callee, args = [], loc = locStub) {
  622. return {
  623. type: 14,
  624. loc,
  625. callee,
  626. arguments: args
  627. };
  628. }
  629. function createFunctionExpression(params, returns = void 0, newline = false, isSlot = false, loc = locStub) {
  630. return {
  631. type: 18,
  632. params,
  633. returns,
  634. newline,
  635. isSlot,
  636. loc
  637. };
  638. }
  639. function createConditionalExpression(test, consequent, alternate, newline = true) {
  640. return {
  641. type: 19,
  642. test,
  643. consequent,
  644. alternate,
  645. newline,
  646. loc: locStub
  647. };
  648. }
  649. function createCacheExpression(index, value, needPauseTracking = false, inVOnce = false) {
  650. return {
  651. type: 20,
  652. index,
  653. value,
  654. needPauseTracking,
  655. inVOnce,
  656. needArraySpread: false,
  657. loc: locStub
  658. };
  659. }
  660. function createBlockStatement(body) {
  661. return {
  662. type: 21,
  663. body,
  664. loc: locStub
  665. };
  666. }
  667. function createTemplateLiteral(elements) {
  668. return {
  669. type: 22,
  670. elements,
  671. loc: locStub
  672. };
  673. }
  674. function createIfStatement(test, consequent, alternate) {
  675. return {
  676. type: 23,
  677. test,
  678. consequent,
  679. alternate,
  680. loc: locStub
  681. };
  682. }
  683. function createAssignmentExpression(left, right) {
  684. return {
  685. type: 24,
  686. left,
  687. right,
  688. loc: locStub
  689. };
  690. }
  691. function createSequenceExpression(expressions) {
  692. return {
  693. type: 25,
  694. expressions,
  695. loc: locStub
  696. };
  697. }
  698. function createReturnStatement(returns) {
  699. return {
  700. type: 26,
  701. returns,
  702. loc: locStub
  703. };
  704. }
  705. function getVNodeHelper(ssr, isComponent) {
  706. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  707. }
  708. function getVNodeBlockHelper(ssr, isComponent) {
  709. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  710. }
  711. function convertToBlock(node, { helper, removeHelper, inSSR }) {
  712. if (!node.isBlock) {
  713. node.isBlock = true;
  714. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  715. helper(OPEN_BLOCK);
  716. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  717. }
  718. }
  719. // Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134
  720. var _a$1;
  721. const decodeMap = new Map([
  722. [0, 65533],
  723. // C1 Unicode control character reference replacements
  724. [128, 8364],
  725. [130, 8218],
  726. [131, 402],
  727. [132, 8222],
  728. [133, 8230],
  729. [134, 8224],
  730. [135, 8225],
  731. [136, 710],
  732. [137, 8240],
  733. [138, 352],
  734. [139, 8249],
  735. [140, 338],
  736. [142, 381],
  737. [145, 8216],
  738. [146, 8217],
  739. [147, 8220],
  740. [148, 8221],
  741. [149, 8226],
  742. [150, 8211],
  743. [151, 8212],
  744. [152, 732],
  745. [153, 8482],
  746. [154, 353],
  747. [155, 8250],
  748. [156, 339],
  749. [158, 382],
  750. [159, 376],
  751. ]);
  752. /**
  753. * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point.
  754. */
  755. const fromCodePoint =
  756. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, n/no-unsupported-features/es-builtins
  757. (_a$1 = String.fromCodePoint) !== null && _a$1 !== void 0 ? _a$1 : ((codePoint) => {
  758. let output = "";
  759. if (codePoint > 65535) {
  760. codePoint -= 65536;
  761. output += String.fromCharCode(((codePoint >>> 10) & 1023) | 55296);
  762. codePoint = 56320 | (codePoint & 1023);
  763. }
  764. output += String.fromCharCode(codePoint);
  765. return output;
  766. });
  767. /**
  768. * Replace the given code point with a replacement character if it is a
  769. * surrogate or is outside the valid range. Otherwise return the code
  770. * point unchanged.
  771. */
  772. function replaceCodePoint(codePoint) {
  773. var _a;
  774. if ((codePoint >= 55296 && codePoint <= 57343) ||
  775. codePoint > 1114111) {
  776. return 65533;
  777. }
  778. return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint;
  779. }
  780. var global$1 = (typeof global !== "undefined" ? global :
  781. typeof self !== "undefined" ? self :
  782. typeof window !== "undefined" ? window : {});
  783. var lookup = [];
  784. var revLookup = [];
  785. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  786. var inited = false;
  787. function init () {
  788. inited = true;
  789. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  790. for (var i = 0, len = code.length; i < len; ++i) {
  791. lookup[i] = code[i];
  792. revLookup[code.charCodeAt(i)] = i;
  793. }
  794. revLookup['-'.charCodeAt(0)] = 62;
  795. revLookup['_'.charCodeAt(0)] = 63;
  796. }
  797. function toByteArray (b64) {
  798. if (!inited) {
  799. init();
  800. }
  801. var i, j, l, tmp, placeHolders, arr;
  802. var len = b64.length;
  803. if (len % 4 > 0) {
  804. throw new Error('Invalid string. Length must be a multiple of 4')
  805. }
  806. // the number of equal signs (place holders)
  807. // if there are two placeholders, than the two characters before it
  808. // represent one byte
  809. // if there is only one, then the three characters before it represent 2 bytes
  810. // this is just a cheap hack to not do indexOf twice
  811. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  812. // base64 is 4/3 + up to two characters of the original data
  813. arr = new Arr(len * 3 / 4 - placeHolders);
  814. // if there are placeholders, only get up to the last complete 4 chars
  815. l = placeHolders > 0 ? len - 4 : len;
  816. var L = 0;
  817. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  818. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  819. arr[L++] = (tmp >> 16) & 0xFF;
  820. arr[L++] = (tmp >> 8) & 0xFF;
  821. arr[L++] = tmp & 0xFF;
  822. }
  823. if (placeHolders === 2) {
  824. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  825. arr[L++] = tmp & 0xFF;
  826. } else if (placeHolders === 1) {
  827. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  828. arr[L++] = (tmp >> 8) & 0xFF;
  829. arr[L++] = tmp & 0xFF;
  830. }
  831. return arr
  832. }
  833. function tripletToBase64 (num) {
  834. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  835. }
  836. function encodeChunk (uint8, start, end) {
  837. var tmp;
  838. var output = [];
  839. for (var i = start; i < end; i += 3) {
  840. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  841. output.push(tripletToBase64(tmp));
  842. }
  843. return output.join('')
  844. }
  845. function fromByteArray (uint8) {
  846. if (!inited) {
  847. init();
  848. }
  849. var tmp;
  850. var len = uint8.length;
  851. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  852. var output = '';
  853. var parts = [];
  854. var maxChunkLength = 16383; // must be multiple of 3
  855. // go through the array every three bytes, we'll deal with trailing stuff later
  856. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  857. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  858. }
  859. // pad the end with zeros, but make sure to not forget the extra bytes
  860. if (extraBytes === 1) {
  861. tmp = uint8[len - 1];
  862. output += lookup[tmp >> 2];
  863. output += lookup[(tmp << 4) & 0x3F];
  864. output += '==';
  865. } else if (extraBytes === 2) {
  866. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  867. output += lookup[tmp >> 10];
  868. output += lookup[(tmp >> 4) & 0x3F];
  869. output += lookup[(tmp << 2) & 0x3F];
  870. output += '=';
  871. }
  872. parts.push(output);
  873. return parts.join('')
  874. }
  875. function read (buffer, offset, isLE, mLen, nBytes) {
  876. var e, m;
  877. var eLen = nBytes * 8 - mLen - 1;
  878. var eMax = (1 << eLen) - 1;
  879. var eBias = eMax >> 1;
  880. var nBits = -7;
  881. var i = isLE ? (nBytes - 1) : 0;
  882. var d = isLE ? -1 : 1;
  883. var s = buffer[offset + i];
  884. i += d;
  885. e = s & ((1 << (-nBits)) - 1);
  886. s >>= (-nBits);
  887. nBits += eLen;
  888. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  889. m = e & ((1 << (-nBits)) - 1);
  890. e >>= (-nBits);
  891. nBits += mLen;
  892. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  893. if (e === 0) {
  894. e = 1 - eBias;
  895. } else if (e === eMax) {
  896. return m ? NaN : ((s ? -1 : 1) * Infinity)
  897. } else {
  898. m = m + Math.pow(2, mLen);
  899. e = e - eBias;
  900. }
  901. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  902. }
  903. function write (buffer, value, offset, isLE, mLen, nBytes) {
  904. var e, m, c;
  905. var eLen = nBytes * 8 - mLen - 1;
  906. var eMax = (1 << eLen) - 1;
  907. var eBias = eMax >> 1;
  908. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  909. var i = isLE ? 0 : (nBytes - 1);
  910. var d = isLE ? 1 : -1;
  911. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  912. value = Math.abs(value);
  913. if (isNaN(value) || value === Infinity) {
  914. m = isNaN(value) ? 1 : 0;
  915. e = eMax;
  916. } else {
  917. e = Math.floor(Math.log(value) / Math.LN2);
  918. if (value * (c = Math.pow(2, -e)) < 1) {
  919. e--;
  920. c *= 2;
  921. }
  922. if (e + eBias >= 1) {
  923. value += rt / c;
  924. } else {
  925. value += rt * Math.pow(2, 1 - eBias);
  926. }
  927. if (value * c >= 2) {
  928. e++;
  929. c /= 2;
  930. }
  931. if (e + eBias >= eMax) {
  932. m = 0;
  933. e = eMax;
  934. } else if (e + eBias >= 1) {
  935. m = (value * c - 1) * Math.pow(2, mLen);
  936. e = e + eBias;
  937. } else {
  938. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  939. e = 0;
  940. }
  941. }
  942. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  943. e = (e << mLen) | m;
  944. eLen += mLen;
  945. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  946. buffer[offset + i - d] |= s * 128;
  947. }
  948. var toString$1 = {}.toString;
  949. var isArray$2 = Array.isArray || function (arr) {
  950. return toString$1.call(arr) == '[object Array]';
  951. };
  952. /*!
  953. * The buffer module from node.js, for the browser.
  954. *
  955. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  956. * @license MIT
  957. */
  958. /* eslint-disable no-proto */
  959. var INSPECT_MAX_BYTES = 50;
  960. /**
  961. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  962. * === true Use Uint8Array implementation (fastest)
  963. * === false Use Object implementation (most compatible, even IE6)
  964. *
  965. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  966. * Opera 11.6+, iOS 4.2+.
  967. *
  968. * Due to various browser bugs, sometimes the Object implementation will be used even
  969. * when the browser supports typed arrays.
  970. *
  971. * Note:
  972. *
  973. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  974. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  975. *
  976. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  977. *
  978. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  979. * incorrect length in some situations.
  980. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  981. * get the Object implementation, which is slower but behaves correctly.
  982. */
  983. Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  984. ? global$1.TYPED_ARRAY_SUPPORT
  985. : true;
  986. /*
  987. * Export kMaxLength after typed array support is determined.
  988. */
  989. kMaxLength();
  990. function kMaxLength () {
  991. return Buffer$1.TYPED_ARRAY_SUPPORT
  992. ? 0x7fffffff
  993. : 0x3fffffff
  994. }
  995. function createBuffer (that, length) {
  996. if (kMaxLength() < length) {
  997. throw new RangeError('Invalid typed array length')
  998. }
  999. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1000. // Return an augmented `Uint8Array` instance, for best performance
  1001. that = new Uint8Array(length);
  1002. that.__proto__ = Buffer$1.prototype;
  1003. } else {
  1004. // Fallback: Return an object instance of the Buffer class
  1005. if (that === null) {
  1006. that = new Buffer$1(length);
  1007. }
  1008. that.length = length;
  1009. }
  1010. return that
  1011. }
  1012. /**
  1013. * The Buffer constructor returns instances of `Uint8Array` that have their
  1014. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  1015. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  1016. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  1017. * returns a single octet.
  1018. *
  1019. * The `Uint8Array` prototype remains unmodified.
  1020. */
  1021. function Buffer$1 (arg, encodingOrOffset, length) {
  1022. if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) {
  1023. return new Buffer$1(arg, encodingOrOffset, length)
  1024. }
  1025. // Common case.
  1026. if (typeof arg === 'number') {
  1027. if (typeof encodingOrOffset === 'string') {
  1028. throw new Error(
  1029. 'If encoding is specified then the first argument must be a string'
  1030. )
  1031. }
  1032. return allocUnsafe(this, arg)
  1033. }
  1034. return from(this, arg, encodingOrOffset, length)
  1035. }
  1036. Buffer$1.poolSize = 8192; // not used by this implementation
  1037. // TODO: Legacy, not needed anymore. Remove in next major version.
  1038. Buffer$1._augment = function (arr) {
  1039. arr.__proto__ = Buffer$1.prototype;
  1040. return arr
  1041. };
  1042. function from (that, value, encodingOrOffset, length) {
  1043. if (typeof value === 'number') {
  1044. throw new TypeError('"value" argument must not be a number')
  1045. }
  1046. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  1047. return fromArrayBuffer(that, value, encodingOrOffset, length)
  1048. }
  1049. if (typeof value === 'string') {
  1050. return fromString(that, value, encodingOrOffset)
  1051. }
  1052. return fromObject(that, value)
  1053. }
  1054. /**
  1055. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  1056. * if value is a number.
  1057. * Buffer.from(str[, encoding])
  1058. * Buffer.from(array)
  1059. * Buffer.from(buffer)
  1060. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  1061. **/
  1062. Buffer$1.from = function (value, encodingOrOffset, length) {
  1063. return from(null, value, encodingOrOffset, length)
  1064. };
  1065. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1066. Buffer$1.prototype.__proto__ = Uint8Array.prototype;
  1067. Buffer$1.__proto__ = Uint8Array;
  1068. if (typeof Symbol !== 'undefined' && Symbol.species &&
  1069. Buffer$1[Symbol.species] === Buffer$1) ;
  1070. }
  1071. function assertSize (size) {
  1072. if (typeof size !== 'number') {
  1073. throw new TypeError('"size" argument must be a number')
  1074. } else if (size < 0) {
  1075. throw new RangeError('"size" argument must not be negative')
  1076. }
  1077. }
  1078. function alloc (that, size, fill, encoding) {
  1079. assertSize(size);
  1080. if (size <= 0) {
  1081. return createBuffer(that, size)
  1082. }
  1083. if (fill !== undefined) {
  1084. // Only pay attention to encoding if it's a string. This
  1085. // prevents accidentally sending in a number that would
  1086. // be interpretted as a start offset.
  1087. return typeof encoding === 'string'
  1088. ? createBuffer(that, size).fill(fill, encoding)
  1089. : createBuffer(that, size).fill(fill)
  1090. }
  1091. return createBuffer(that, size)
  1092. }
  1093. /**
  1094. * Creates a new filled Buffer instance.
  1095. * alloc(size[, fill[, encoding]])
  1096. **/
  1097. Buffer$1.alloc = function (size, fill, encoding) {
  1098. return alloc(null, size, fill, encoding)
  1099. };
  1100. function allocUnsafe (that, size) {
  1101. assertSize(size);
  1102. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  1103. if (!Buffer$1.TYPED_ARRAY_SUPPORT) {
  1104. for (var i = 0; i < size; ++i) {
  1105. that[i] = 0;
  1106. }
  1107. }
  1108. return that
  1109. }
  1110. /**
  1111. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  1112. * */
  1113. Buffer$1.allocUnsafe = function (size) {
  1114. return allocUnsafe(null, size)
  1115. };
  1116. /**
  1117. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  1118. */
  1119. Buffer$1.allocUnsafeSlow = function (size) {
  1120. return allocUnsafe(null, size)
  1121. };
  1122. function fromString (that, string, encoding) {
  1123. if (typeof encoding !== 'string' || encoding === '') {
  1124. encoding = 'utf8';
  1125. }
  1126. if (!Buffer$1.isEncoding(encoding)) {
  1127. throw new TypeError('"encoding" must be a valid string encoding')
  1128. }
  1129. var length = byteLength(string, encoding) | 0;
  1130. that = createBuffer(that, length);
  1131. var actual = that.write(string, encoding);
  1132. if (actual !== length) {
  1133. // Writing a hex string, for example, that contains invalid characters will
  1134. // cause everything after the first invalid character to be ignored. (e.g.
  1135. // 'abxxcd' will be treated as 'ab')
  1136. that = that.slice(0, actual);
  1137. }
  1138. return that
  1139. }
  1140. function fromArrayLike (that, array) {
  1141. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  1142. that = createBuffer(that, length);
  1143. for (var i = 0; i < length; i += 1) {
  1144. that[i] = array[i] & 255;
  1145. }
  1146. return that
  1147. }
  1148. function fromArrayBuffer (that, array, byteOffset, length) {
  1149. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  1150. if (byteOffset < 0 || array.byteLength < byteOffset) {
  1151. throw new RangeError('\'offset\' is out of bounds')
  1152. }
  1153. if (array.byteLength < byteOffset + (length || 0)) {
  1154. throw new RangeError('\'length\' is out of bounds')
  1155. }
  1156. if (byteOffset === undefined && length === undefined) {
  1157. array = new Uint8Array(array);
  1158. } else if (length === undefined) {
  1159. array = new Uint8Array(array, byteOffset);
  1160. } else {
  1161. array = new Uint8Array(array, byteOffset, length);
  1162. }
  1163. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1164. // Return an augmented `Uint8Array` instance, for best performance
  1165. that = array;
  1166. that.__proto__ = Buffer$1.prototype;
  1167. } else {
  1168. // Fallback: Return an object instance of the Buffer class
  1169. that = fromArrayLike(that, array);
  1170. }
  1171. return that
  1172. }
  1173. function fromObject (that, obj) {
  1174. if (internalIsBuffer(obj)) {
  1175. var len = checked(obj.length) | 0;
  1176. that = createBuffer(that, len);
  1177. if (that.length === 0) {
  1178. return that
  1179. }
  1180. obj.copy(that, 0, 0, len);
  1181. return that
  1182. }
  1183. if (obj) {
  1184. if ((typeof ArrayBuffer !== 'undefined' &&
  1185. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  1186. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  1187. return createBuffer(that, 0)
  1188. }
  1189. return fromArrayLike(that, obj)
  1190. }
  1191. if (obj.type === 'Buffer' && isArray$2(obj.data)) {
  1192. return fromArrayLike(that, obj.data)
  1193. }
  1194. }
  1195. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  1196. }
  1197. function checked (length) {
  1198. // Note: cannot use `length < kMaxLength()` here because that fails when
  1199. // length is NaN (which is otherwise coerced to zero.)
  1200. if (length >= kMaxLength()) {
  1201. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  1202. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  1203. }
  1204. return length | 0
  1205. }
  1206. Buffer$1.isBuffer = isBuffer$1;
  1207. function internalIsBuffer (b) {
  1208. return !!(b != null && b._isBuffer)
  1209. }
  1210. Buffer$1.compare = function compare (a, b) {
  1211. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  1212. throw new TypeError('Arguments must be Buffers')
  1213. }
  1214. if (a === b) return 0
  1215. var x = a.length;
  1216. var y = b.length;
  1217. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  1218. if (a[i] !== b[i]) {
  1219. x = a[i];
  1220. y = b[i];
  1221. break
  1222. }
  1223. }
  1224. if (x < y) return -1
  1225. if (y < x) return 1
  1226. return 0
  1227. };
  1228. Buffer$1.isEncoding = function isEncoding (encoding) {
  1229. switch (String(encoding).toLowerCase()) {
  1230. case 'hex':
  1231. case 'utf8':
  1232. case 'utf-8':
  1233. case 'ascii':
  1234. case 'latin1':
  1235. case 'binary':
  1236. case 'base64':
  1237. case 'ucs2':
  1238. case 'ucs-2':
  1239. case 'utf16le':
  1240. case 'utf-16le':
  1241. return true
  1242. default:
  1243. return false
  1244. }
  1245. };
  1246. Buffer$1.concat = function concat (list, length) {
  1247. if (!isArray$2(list)) {
  1248. throw new TypeError('"list" argument must be an Array of Buffers')
  1249. }
  1250. if (list.length === 0) {
  1251. return Buffer$1.alloc(0)
  1252. }
  1253. var i;
  1254. if (length === undefined) {
  1255. length = 0;
  1256. for (i = 0; i < list.length; ++i) {
  1257. length += list[i].length;
  1258. }
  1259. }
  1260. var buffer = Buffer$1.allocUnsafe(length);
  1261. var pos = 0;
  1262. for (i = 0; i < list.length; ++i) {
  1263. var buf = list[i];
  1264. if (!internalIsBuffer(buf)) {
  1265. throw new TypeError('"list" argument must be an Array of Buffers')
  1266. }
  1267. buf.copy(buffer, pos);
  1268. pos += buf.length;
  1269. }
  1270. return buffer
  1271. };
  1272. function byteLength (string, encoding) {
  1273. if (internalIsBuffer(string)) {
  1274. return string.length
  1275. }
  1276. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  1277. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  1278. return string.byteLength
  1279. }
  1280. if (typeof string !== 'string') {
  1281. string = '' + string;
  1282. }
  1283. var len = string.length;
  1284. if (len === 0) return 0
  1285. // Use a for loop to avoid recursion
  1286. var loweredCase = false;
  1287. for (;;) {
  1288. switch (encoding) {
  1289. case 'ascii':
  1290. case 'latin1':
  1291. case 'binary':
  1292. return len
  1293. case 'utf8':
  1294. case 'utf-8':
  1295. case undefined:
  1296. return utf8ToBytes(string).length
  1297. case 'ucs2':
  1298. case 'ucs-2':
  1299. case 'utf16le':
  1300. case 'utf-16le':
  1301. return len * 2
  1302. case 'hex':
  1303. return len >>> 1
  1304. case 'base64':
  1305. return base64ToBytes(string).length
  1306. default:
  1307. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  1308. encoding = ('' + encoding).toLowerCase();
  1309. loweredCase = true;
  1310. }
  1311. }
  1312. }
  1313. Buffer$1.byteLength = byteLength;
  1314. function slowToString (encoding, start, end) {
  1315. var loweredCase = false;
  1316. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  1317. // property of a typed array.
  1318. // This behaves neither like String nor Uint8Array in that we set start/end
  1319. // to their upper/lower bounds if the value passed is out of range.
  1320. // undefined is handled specially as per ECMA-262 6th Edition,
  1321. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  1322. if (start === undefined || start < 0) {
  1323. start = 0;
  1324. }
  1325. // Return early if start > this.length. Done here to prevent potential uint32
  1326. // coercion fail below.
  1327. if (start > this.length) {
  1328. return ''
  1329. }
  1330. if (end === undefined || end > this.length) {
  1331. end = this.length;
  1332. }
  1333. if (end <= 0) {
  1334. return ''
  1335. }
  1336. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  1337. end >>>= 0;
  1338. start >>>= 0;
  1339. if (end <= start) {
  1340. return ''
  1341. }
  1342. if (!encoding) encoding = 'utf8';
  1343. while (true) {
  1344. switch (encoding) {
  1345. case 'hex':
  1346. return hexSlice(this, start, end)
  1347. case 'utf8':
  1348. case 'utf-8':
  1349. return utf8Slice(this, start, end)
  1350. case 'ascii':
  1351. return asciiSlice(this, start, end)
  1352. case 'latin1':
  1353. case 'binary':
  1354. return latin1Slice(this, start, end)
  1355. case 'base64':
  1356. return base64Slice(this, start, end)
  1357. case 'ucs2':
  1358. case 'ucs-2':
  1359. case 'utf16le':
  1360. case 'utf-16le':
  1361. return utf16leSlice(this, start, end)
  1362. default:
  1363. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1364. encoding = (encoding + '').toLowerCase();
  1365. loweredCase = true;
  1366. }
  1367. }
  1368. }
  1369. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  1370. // Buffer instances.
  1371. Buffer$1.prototype._isBuffer = true;
  1372. function swap (b, n, m) {
  1373. var i = b[n];
  1374. b[n] = b[m];
  1375. b[m] = i;
  1376. }
  1377. Buffer$1.prototype.swap16 = function swap16 () {
  1378. var len = this.length;
  1379. if (len % 2 !== 0) {
  1380. throw new RangeError('Buffer size must be a multiple of 16-bits')
  1381. }
  1382. for (var i = 0; i < len; i += 2) {
  1383. swap(this, i, i + 1);
  1384. }
  1385. return this
  1386. };
  1387. Buffer$1.prototype.swap32 = function swap32 () {
  1388. var len = this.length;
  1389. if (len % 4 !== 0) {
  1390. throw new RangeError('Buffer size must be a multiple of 32-bits')
  1391. }
  1392. for (var i = 0; i < len; i += 4) {
  1393. swap(this, i, i + 3);
  1394. swap(this, i + 1, i + 2);
  1395. }
  1396. return this
  1397. };
  1398. Buffer$1.prototype.swap64 = function swap64 () {
  1399. var len = this.length;
  1400. if (len % 8 !== 0) {
  1401. throw new RangeError('Buffer size must be a multiple of 64-bits')
  1402. }
  1403. for (var i = 0; i < len; i += 8) {
  1404. swap(this, i, i + 7);
  1405. swap(this, i + 1, i + 6);
  1406. swap(this, i + 2, i + 5);
  1407. swap(this, i + 3, i + 4);
  1408. }
  1409. return this
  1410. };
  1411. Buffer$1.prototype.toString = function toString () {
  1412. var length = this.length | 0;
  1413. if (length === 0) return ''
  1414. if (arguments.length === 0) return utf8Slice(this, 0, length)
  1415. return slowToString.apply(this, arguments)
  1416. };
  1417. Buffer$1.prototype.equals = function equals (b) {
  1418. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1419. if (this === b) return true
  1420. return Buffer$1.compare(this, b) === 0
  1421. };
  1422. Buffer$1.prototype.inspect = function inspect () {
  1423. var str = '';
  1424. var max = INSPECT_MAX_BYTES;
  1425. if (this.length > 0) {
  1426. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  1427. if (this.length > max) str += ' ... ';
  1428. }
  1429. return '<Buffer ' + str + '>'
  1430. };
  1431. Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  1432. if (!internalIsBuffer(target)) {
  1433. throw new TypeError('Argument must be a Buffer')
  1434. }
  1435. if (start === undefined) {
  1436. start = 0;
  1437. }
  1438. if (end === undefined) {
  1439. end = target ? target.length : 0;
  1440. }
  1441. if (thisStart === undefined) {
  1442. thisStart = 0;
  1443. }
  1444. if (thisEnd === undefined) {
  1445. thisEnd = this.length;
  1446. }
  1447. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  1448. throw new RangeError('out of range index')
  1449. }
  1450. if (thisStart >= thisEnd && start >= end) {
  1451. return 0
  1452. }
  1453. if (thisStart >= thisEnd) {
  1454. return -1
  1455. }
  1456. if (start >= end) {
  1457. return 1
  1458. }
  1459. start >>>= 0;
  1460. end >>>= 0;
  1461. thisStart >>>= 0;
  1462. thisEnd >>>= 0;
  1463. if (this === target) return 0
  1464. var x = thisEnd - thisStart;
  1465. var y = end - start;
  1466. var len = Math.min(x, y);
  1467. var thisCopy = this.slice(thisStart, thisEnd);
  1468. var targetCopy = target.slice(start, end);
  1469. for (var i = 0; i < len; ++i) {
  1470. if (thisCopy[i] !== targetCopy[i]) {
  1471. x = thisCopy[i];
  1472. y = targetCopy[i];
  1473. break
  1474. }
  1475. }
  1476. if (x < y) return -1
  1477. if (y < x) return 1
  1478. return 0
  1479. };
  1480. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  1481. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  1482. //
  1483. // Arguments:
  1484. // - buffer - a Buffer to search
  1485. // - val - a string, Buffer, or number
  1486. // - byteOffset - an index into `buffer`; will be clamped to an int32
  1487. // - encoding - an optional encoding, relevant is val is a string
  1488. // - dir - true for indexOf, false for lastIndexOf
  1489. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  1490. // Empty buffer means no match
  1491. if (buffer.length === 0) return -1
  1492. // Normalize byteOffset
  1493. if (typeof byteOffset === 'string') {
  1494. encoding = byteOffset;
  1495. byteOffset = 0;
  1496. } else if (byteOffset > 0x7fffffff) {
  1497. byteOffset = 0x7fffffff;
  1498. } else if (byteOffset < -2147483648) {
  1499. byteOffset = -2147483648;
  1500. }
  1501. byteOffset = +byteOffset; // Coerce to Number.
  1502. if (isNaN(byteOffset)) {
  1503. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  1504. byteOffset = dir ? 0 : (buffer.length - 1);
  1505. }
  1506. // Normalize byteOffset: negative offsets start from the end of the buffer
  1507. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  1508. if (byteOffset >= buffer.length) {
  1509. if (dir) return -1
  1510. else byteOffset = buffer.length - 1;
  1511. } else if (byteOffset < 0) {
  1512. if (dir) byteOffset = 0;
  1513. else return -1
  1514. }
  1515. // Normalize val
  1516. if (typeof val === 'string') {
  1517. val = Buffer$1.from(val, encoding);
  1518. }
  1519. // Finally, search either indexOf (if dir is true) or lastIndexOf
  1520. if (internalIsBuffer(val)) {
  1521. // Special case: looking for empty string/buffer always fails
  1522. if (val.length === 0) {
  1523. return -1
  1524. }
  1525. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  1526. } else if (typeof val === 'number') {
  1527. val = val & 0xFF; // Search for a byte value [0-255]
  1528. if (Buffer$1.TYPED_ARRAY_SUPPORT &&
  1529. typeof Uint8Array.prototype.indexOf === 'function') {
  1530. if (dir) {
  1531. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  1532. } else {
  1533. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  1534. }
  1535. }
  1536. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  1537. }
  1538. throw new TypeError('val must be string, number or Buffer')
  1539. }
  1540. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  1541. var indexSize = 1;
  1542. var arrLength = arr.length;
  1543. var valLength = val.length;
  1544. if (encoding !== undefined) {
  1545. encoding = String(encoding).toLowerCase();
  1546. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  1547. encoding === 'utf16le' || encoding === 'utf-16le') {
  1548. if (arr.length < 2 || val.length < 2) {
  1549. return -1
  1550. }
  1551. indexSize = 2;
  1552. arrLength /= 2;
  1553. valLength /= 2;
  1554. byteOffset /= 2;
  1555. }
  1556. }
  1557. function read (buf, i) {
  1558. if (indexSize === 1) {
  1559. return buf[i]
  1560. } else {
  1561. return buf.readUInt16BE(i * indexSize)
  1562. }
  1563. }
  1564. var i;
  1565. if (dir) {
  1566. var foundIndex = -1;
  1567. for (i = byteOffset; i < arrLength; i++) {
  1568. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  1569. if (foundIndex === -1) foundIndex = i;
  1570. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  1571. } else {
  1572. if (foundIndex !== -1) i -= i - foundIndex;
  1573. foundIndex = -1;
  1574. }
  1575. }
  1576. } else {
  1577. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  1578. for (i = byteOffset; i >= 0; i--) {
  1579. var found = true;
  1580. for (var j = 0; j < valLength; j++) {
  1581. if (read(arr, i + j) !== read(val, j)) {
  1582. found = false;
  1583. break
  1584. }
  1585. }
  1586. if (found) return i
  1587. }
  1588. }
  1589. return -1
  1590. }
  1591. Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) {
  1592. return this.indexOf(val, byteOffset, encoding) !== -1
  1593. };
  1594. Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  1595. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  1596. };
  1597. Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  1598. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  1599. };
  1600. function hexWrite (buf, string, offset, length) {
  1601. offset = Number(offset) || 0;
  1602. var remaining = buf.length - offset;
  1603. if (!length) {
  1604. length = remaining;
  1605. } else {
  1606. length = Number(length);
  1607. if (length > remaining) {
  1608. length = remaining;
  1609. }
  1610. }
  1611. // must be an even number of digits
  1612. var strLen = string.length;
  1613. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  1614. if (length > strLen / 2) {
  1615. length = strLen / 2;
  1616. }
  1617. for (var i = 0; i < length; ++i) {
  1618. var parsed = parseInt(string.substr(i * 2, 2), 16);
  1619. if (isNaN(parsed)) return i
  1620. buf[offset + i] = parsed;
  1621. }
  1622. return i
  1623. }
  1624. function utf8Write (buf, string, offset, length) {
  1625. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  1626. }
  1627. function asciiWrite (buf, string, offset, length) {
  1628. return blitBuffer(asciiToBytes(string), buf, offset, length)
  1629. }
  1630. function latin1Write (buf, string, offset, length) {
  1631. return asciiWrite(buf, string, offset, length)
  1632. }
  1633. function base64Write (buf, string, offset, length) {
  1634. return blitBuffer(base64ToBytes(string), buf, offset, length)
  1635. }
  1636. function ucs2Write (buf, string, offset, length) {
  1637. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  1638. }
  1639. Buffer$1.prototype.write = function write (string, offset, length, encoding) {
  1640. // Buffer#write(string)
  1641. if (offset === undefined) {
  1642. encoding = 'utf8';
  1643. length = this.length;
  1644. offset = 0;
  1645. // Buffer#write(string, encoding)
  1646. } else if (length === undefined && typeof offset === 'string') {
  1647. encoding = offset;
  1648. length = this.length;
  1649. offset = 0;
  1650. // Buffer#write(string, offset[, length][, encoding])
  1651. } else if (isFinite(offset)) {
  1652. offset = offset | 0;
  1653. if (isFinite(length)) {
  1654. length = length | 0;
  1655. if (encoding === undefined) encoding = 'utf8';
  1656. } else {
  1657. encoding = length;
  1658. length = undefined;
  1659. }
  1660. // legacy write(string, encoding, offset, length) - remove in v0.13
  1661. } else {
  1662. throw new Error(
  1663. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  1664. )
  1665. }
  1666. var remaining = this.length - offset;
  1667. if (length === undefined || length > remaining) length = remaining;
  1668. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  1669. throw new RangeError('Attempt to write outside buffer bounds')
  1670. }
  1671. if (!encoding) encoding = 'utf8';
  1672. var loweredCase = false;
  1673. for (;;) {
  1674. switch (encoding) {
  1675. case 'hex':
  1676. return hexWrite(this, string, offset, length)
  1677. case 'utf8':
  1678. case 'utf-8':
  1679. return utf8Write(this, string, offset, length)
  1680. case 'ascii':
  1681. return asciiWrite(this, string, offset, length)
  1682. case 'latin1':
  1683. case 'binary':
  1684. return latin1Write(this, string, offset, length)
  1685. case 'base64':
  1686. // Warning: maxLength not taken into account in base64Write
  1687. return base64Write(this, string, offset, length)
  1688. case 'ucs2':
  1689. case 'ucs-2':
  1690. case 'utf16le':
  1691. case 'utf-16le':
  1692. return ucs2Write(this, string, offset, length)
  1693. default:
  1694. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1695. encoding = ('' + encoding).toLowerCase();
  1696. loweredCase = true;
  1697. }
  1698. }
  1699. };
  1700. Buffer$1.prototype.toJSON = function toJSON () {
  1701. return {
  1702. type: 'Buffer',
  1703. data: Array.prototype.slice.call(this._arr || this, 0)
  1704. }
  1705. };
  1706. function base64Slice (buf, start, end) {
  1707. if (start === 0 && end === buf.length) {
  1708. return fromByteArray(buf)
  1709. } else {
  1710. return fromByteArray(buf.slice(start, end))
  1711. }
  1712. }
  1713. function utf8Slice (buf, start, end) {
  1714. end = Math.min(buf.length, end);
  1715. var res = [];
  1716. var i = start;
  1717. while (i < end) {
  1718. var firstByte = buf[i];
  1719. var codePoint = null;
  1720. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1721. : (firstByte > 0xDF) ? 3
  1722. : (firstByte > 0xBF) ? 2
  1723. : 1;
  1724. if (i + bytesPerSequence <= end) {
  1725. var secondByte, thirdByte, fourthByte, tempCodePoint;
  1726. switch (bytesPerSequence) {
  1727. case 1:
  1728. if (firstByte < 0x80) {
  1729. codePoint = firstByte;
  1730. }
  1731. break
  1732. case 2:
  1733. secondByte = buf[i + 1];
  1734. if ((secondByte & 0xC0) === 0x80) {
  1735. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  1736. if (tempCodePoint > 0x7F) {
  1737. codePoint = tempCodePoint;
  1738. }
  1739. }
  1740. break
  1741. case 3:
  1742. secondByte = buf[i + 1];
  1743. thirdByte = buf[i + 2];
  1744. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1745. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  1746. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1747. codePoint = tempCodePoint;
  1748. }
  1749. }
  1750. break
  1751. case 4:
  1752. secondByte = buf[i + 1];
  1753. thirdByte = buf[i + 2];
  1754. fourthByte = buf[i + 3];
  1755. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1756. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  1757. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1758. codePoint = tempCodePoint;
  1759. }
  1760. }
  1761. }
  1762. }
  1763. if (codePoint === null) {
  1764. // we did not generate a valid codePoint so insert a
  1765. // replacement char (U+FFFD) and advance only 1 byte
  1766. codePoint = 0xFFFD;
  1767. bytesPerSequence = 1;
  1768. } else if (codePoint > 0xFFFF) {
  1769. // encode to utf16 (surrogate pair dance)
  1770. codePoint -= 0x10000;
  1771. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  1772. codePoint = 0xDC00 | codePoint & 0x3FF;
  1773. }
  1774. res.push(codePoint);
  1775. i += bytesPerSequence;
  1776. }
  1777. return decodeCodePointsArray(res)
  1778. }
  1779. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1780. // the lowest limit is Chrome, with 0x10000 args.
  1781. // We go 1 magnitude less, for safety
  1782. var MAX_ARGUMENTS_LENGTH = 0x1000;
  1783. function decodeCodePointsArray (codePoints) {
  1784. var len = codePoints.length;
  1785. if (len <= MAX_ARGUMENTS_LENGTH) {
  1786. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1787. }
  1788. // Decode in chunks to avoid "call stack size exceeded".
  1789. var res = '';
  1790. var i = 0;
  1791. while (i < len) {
  1792. res += String.fromCharCode.apply(
  1793. String,
  1794. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1795. );
  1796. }
  1797. return res
  1798. }
  1799. function asciiSlice (buf, start, end) {
  1800. var ret = '';
  1801. end = Math.min(buf.length, end);
  1802. for (var i = start; i < end; ++i) {
  1803. ret += String.fromCharCode(buf[i] & 0x7F);
  1804. }
  1805. return ret
  1806. }
  1807. function latin1Slice (buf, start, end) {
  1808. var ret = '';
  1809. end = Math.min(buf.length, end);
  1810. for (var i = start; i < end; ++i) {
  1811. ret += String.fromCharCode(buf[i]);
  1812. }
  1813. return ret
  1814. }
  1815. function hexSlice (buf, start, end) {
  1816. var len = buf.length;
  1817. if (!start || start < 0) start = 0;
  1818. if (!end || end < 0 || end > len) end = len;
  1819. var out = '';
  1820. for (var i = start; i < end; ++i) {
  1821. out += toHex(buf[i]);
  1822. }
  1823. return out
  1824. }
  1825. function utf16leSlice (buf, start, end) {
  1826. var bytes = buf.slice(start, end);
  1827. var res = '';
  1828. for (var i = 0; i < bytes.length; i += 2) {
  1829. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1830. }
  1831. return res
  1832. }
  1833. Buffer$1.prototype.slice = function slice (start, end) {
  1834. var len = this.length;
  1835. start = ~~start;
  1836. end = end === undefined ? len : ~~end;
  1837. if (start < 0) {
  1838. start += len;
  1839. if (start < 0) start = 0;
  1840. } else if (start > len) {
  1841. start = len;
  1842. }
  1843. if (end < 0) {
  1844. end += len;
  1845. if (end < 0) end = 0;
  1846. } else if (end > len) {
  1847. end = len;
  1848. }
  1849. if (end < start) end = start;
  1850. var newBuf;
  1851. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1852. newBuf = this.subarray(start, end);
  1853. newBuf.__proto__ = Buffer$1.prototype;
  1854. } else {
  1855. var sliceLen = end - start;
  1856. newBuf = new Buffer$1(sliceLen, undefined);
  1857. for (var i = 0; i < sliceLen; ++i) {
  1858. newBuf[i] = this[i + start];
  1859. }
  1860. }
  1861. return newBuf
  1862. };
  1863. /*
  1864. * Need to make sure that buffer isn't trying to write out of bounds.
  1865. */
  1866. function checkOffset (offset, ext, length) {
  1867. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1868. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1869. }
  1870. Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1871. offset = offset | 0;
  1872. byteLength = byteLength | 0;
  1873. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1874. var val = this[offset];
  1875. var mul = 1;
  1876. var i = 0;
  1877. while (++i < byteLength && (mul *= 0x100)) {
  1878. val += this[offset + i] * mul;
  1879. }
  1880. return val
  1881. };
  1882. Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1883. offset = offset | 0;
  1884. byteLength = byteLength | 0;
  1885. if (!noAssert) {
  1886. checkOffset(offset, byteLength, this.length);
  1887. }
  1888. var val = this[offset + --byteLength];
  1889. var mul = 1;
  1890. while (byteLength > 0 && (mul *= 0x100)) {
  1891. val += this[offset + --byteLength] * mul;
  1892. }
  1893. return val
  1894. };
  1895. Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1896. if (!noAssert) checkOffset(offset, 1, this.length);
  1897. return this[offset]
  1898. };
  1899. Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1900. if (!noAssert) checkOffset(offset, 2, this.length);
  1901. return this[offset] | (this[offset + 1] << 8)
  1902. };
  1903. Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1904. if (!noAssert) checkOffset(offset, 2, this.length);
  1905. return (this[offset] << 8) | this[offset + 1]
  1906. };
  1907. Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1908. if (!noAssert) checkOffset(offset, 4, this.length);
  1909. return ((this[offset]) |
  1910. (this[offset + 1] << 8) |
  1911. (this[offset + 2] << 16)) +
  1912. (this[offset + 3] * 0x1000000)
  1913. };
  1914. Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1915. if (!noAssert) checkOffset(offset, 4, this.length);
  1916. return (this[offset] * 0x1000000) +
  1917. ((this[offset + 1] << 16) |
  1918. (this[offset + 2] << 8) |
  1919. this[offset + 3])
  1920. };
  1921. Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1922. offset = offset | 0;
  1923. byteLength = byteLength | 0;
  1924. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1925. var val = this[offset];
  1926. var mul = 1;
  1927. var i = 0;
  1928. while (++i < byteLength && (mul *= 0x100)) {
  1929. val += this[offset + i] * mul;
  1930. }
  1931. mul *= 0x80;
  1932. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1933. return val
  1934. };
  1935. Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1936. offset = offset | 0;
  1937. byteLength = byteLength | 0;
  1938. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1939. var i = byteLength;
  1940. var mul = 1;
  1941. var val = this[offset + --i];
  1942. while (i > 0 && (mul *= 0x100)) {
  1943. val += this[offset + --i] * mul;
  1944. }
  1945. mul *= 0x80;
  1946. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1947. return val
  1948. };
  1949. Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1950. if (!noAssert) checkOffset(offset, 1, this.length);
  1951. if (!(this[offset] & 0x80)) return (this[offset])
  1952. return ((0xff - this[offset] + 1) * -1)
  1953. };
  1954. Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1955. if (!noAssert) checkOffset(offset, 2, this.length);
  1956. var val = this[offset] | (this[offset + 1] << 8);
  1957. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1958. };
  1959. Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1960. if (!noAssert) checkOffset(offset, 2, this.length);
  1961. var val = this[offset + 1] | (this[offset] << 8);
  1962. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1963. };
  1964. Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1965. if (!noAssert) checkOffset(offset, 4, this.length);
  1966. return (this[offset]) |
  1967. (this[offset + 1] << 8) |
  1968. (this[offset + 2] << 16) |
  1969. (this[offset + 3] << 24)
  1970. };
  1971. Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1972. if (!noAssert) checkOffset(offset, 4, this.length);
  1973. return (this[offset] << 24) |
  1974. (this[offset + 1] << 16) |
  1975. (this[offset + 2] << 8) |
  1976. (this[offset + 3])
  1977. };
  1978. Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1979. if (!noAssert) checkOffset(offset, 4, this.length);
  1980. return read(this, offset, true, 23, 4)
  1981. };
  1982. Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1983. if (!noAssert) checkOffset(offset, 4, this.length);
  1984. return read(this, offset, false, 23, 4)
  1985. };
  1986. Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1987. if (!noAssert) checkOffset(offset, 8, this.length);
  1988. return read(this, offset, true, 52, 8)
  1989. };
  1990. Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1991. if (!noAssert) checkOffset(offset, 8, this.length);
  1992. return read(this, offset, false, 52, 8)
  1993. };
  1994. function checkInt (buf, value, offset, ext, max, min) {
  1995. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1996. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1997. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1998. }
  1999. Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  2000. value = +value;
  2001. offset = offset | 0;
  2002. byteLength = byteLength | 0;
  2003. if (!noAssert) {
  2004. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  2005. checkInt(this, value, offset, byteLength, maxBytes, 0);
  2006. }
  2007. var mul = 1;
  2008. var i = 0;
  2009. this[offset] = value & 0xFF;
  2010. while (++i < byteLength && (mul *= 0x100)) {
  2011. this[offset + i] = (value / mul) & 0xFF;
  2012. }
  2013. return offset + byteLength
  2014. };
  2015. Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  2016. value = +value;
  2017. offset = offset | 0;
  2018. byteLength = byteLength | 0;
  2019. if (!noAssert) {
  2020. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  2021. checkInt(this, value, offset, byteLength, maxBytes, 0);
  2022. }
  2023. var i = byteLength - 1;
  2024. var mul = 1;
  2025. this[offset + i] = value & 0xFF;
  2026. while (--i >= 0 && (mul *= 0x100)) {
  2027. this[offset + i] = (value / mul) & 0xFF;
  2028. }
  2029. return offset + byteLength
  2030. };
  2031. Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  2032. value = +value;
  2033. offset = offset | 0;
  2034. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  2035. if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  2036. this[offset] = (value & 0xff);
  2037. return offset + 1
  2038. };
  2039. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  2040. if (value < 0) value = 0xffff + value + 1;
  2041. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  2042. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  2043. (littleEndian ? i : 1 - i) * 8;
  2044. }
  2045. }
  2046. Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  2047. value = +value;
  2048. offset = offset | 0;
  2049. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  2050. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2051. this[offset] = (value & 0xff);
  2052. this[offset + 1] = (value >>> 8);
  2053. } else {
  2054. objectWriteUInt16(this, value, offset, true);
  2055. }
  2056. return offset + 2
  2057. };
  2058. Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  2059. value = +value;
  2060. offset = offset | 0;
  2061. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  2062. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2063. this[offset] = (value >>> 8);
  2064. this[offset + 1] = (value & 0xff);
  2065. } else {
  2066. objectWriteUInt16(this, value, offset, false);
  2067. }
  2068. return offset + 2
  2069. };
  2070. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  2071. if (value < 0) value = 0xffffffff + value + 1;
  2072. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  2073. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  2074. }
  2075. }
  2076. Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  2077. value = +value;
  2078. offset = offset | 0;
  2079. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  2080. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2081. this[offset + 3] = (value >>> 24);
  2082. this[offset + 2] = (value >>> 16);
  2083. this[offset + 1] = (value >>> 8);
  2084. this[offset] = (value & 0xff);
  2085. } else {
  2086. objectWriteUInt32(this, value, offset, true);
  2087. }
  2088. return offset + 4
  2089. };
  2090. Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  2091. value = +value;
  2092. offset = offset | 0;
  2093. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  2094. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2095. this[offset] = (value >>> 24);
  2096. this[offset + 1] = (value >>> 16);
  2097. this[offset + 2] = (value >>> 8);
  2098. this[offset + 3] = (value & 0xff);
  2099. } else {
  2100. objectWriteUInt32(this, value, offset, false);
  2101. }
  2102. return offset + 4
  2103. };
  2104. Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  2105. value = +value;
  2106. offset = offset | 0;
  2107. if (!noAssert) {
  2108. var limit = Math.pow(2, 8 * byteLength - 1);
  2109. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  2110. }
  2111. var i = 0;
  2112. var mul = 1;
  2113. var sub = 0;
  2114. this[offset] = value & 0xFF;
  2115. while (++i < byteLength && (mul *= 0x100)) {
  2116. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  2117. sub = 1;
  2118. }
  2119. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  2120. }
  2121. return offset + byteLength
  2122. };
  2123. Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  2124. value = +value;
  2125. offset = offset | 0;
  2126. if (!noAssert) {
  2127. var limit = Math.pow(2, 8 * byteLength - 1);
  2128. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  2129. }
  2130. var i = byteLength - 1;
  2131. var mul = 1;
  2132. var sub = 0;
  2133. this[offset + i] = value & 0xFF;
  2134. while (--i >= 0 && (mul *= 0x100)) {
  2135. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  2136. sub = 1;
  2137. }
  2138. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  2139. }
  2140. return offset + byteLength
  2141. };
  2142. Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  2143. value = +value;
  2144. offset = offset | 0;
  2145. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);
  2146. if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  2147. if (value < 0) value = 0xff + value + 1;
  2148. this[offset] = (value & 0xff);
  2149. return offset + 1
  2150. };
  2151. Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  2152. value = +value;
  2153. offset = offset | 0;
  2154. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
  2155. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2156. this[offset] = (value & 0xff);
  2157. this[offset + 1] = (value >>> 8);
  2158. } else {
  2159. objectWriteUInt16(this, value, offset, true);
  2160. }
  2161. return offset + 2
  2162. };
  2163. Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  2164. value = +value;
  2165. offset = offset | 0;
  2166. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
  2167. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2168. this[offset] = (value >>> 8);
  2169. this[offset + 1] = (value & 0xff);
  2170. } else {
  2171. objectWriteUInt16(this, value, offset, false);
  2172. }
  2173. return offset + 2
  2174. };
  2175. Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  2176. value = +value;
  2177. offset = offset | 0;
  2178. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
  2179. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2180. this[offset] = (value & 0xff);
  2181. this[offset + 1] = (value >>> 8);
  2182. this[offset + 2] = (value >>> 16);
  2183. this[offset + 3] = (value >>> 24);
  2184. } else {
  2185. objectWriteUInt32(this, value, offset, true);
  2186. }
  2187. return offset + 4
  2188. };
  2189. Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  2190. value = +value;
  2191. offset = offset | 0;
  2192. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
  2193. if (value < 0) value = 0xffffffff + value + 1;
  2194. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2195. this[offset] = (value >>> 24);
  2196. this[offset + 1] = (value >>> 16);
  2197. this[offset + 2] = (value >>> 8);
  2198. this[offset + 3] = (value & 0xff);
  2199. } else {
  2200. objectWriteUInt32(this, value, offset, false);
  2201. }
  2202. return offset + 4
  2203. };
  2204. function checkIEEE754 (buf, value, offset, ext, max, min) {
  2205. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2206. if (offset < 0) throw new RangeError('Index out of range')
  2207. }
  2208. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2209. if (!noAssert) {
  2210. checkIEEE754(buf, value, offset, 4);
  2211. }
  2212. write(buf, value, offset, littleEndian, 23, 4);
  2213. return offset + 4
  2214. }
  2215. Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  2216. return writeFloat(this, value, offset, true, noAssert)
  2217. };
  2218. Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  2219. return writeFloat(this, value, offset, false, noAssert)
  2220. };
  2221. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2222. if (!noAssert) {
  2223. checkIEEE754(buf, value, offset, 8);
  2224. }
  2225. write(buf, value, offset, littleEndian, 52, 8);
  2226. return offset + 8
  2227. }
  2228. Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  2229. return writeDouble(this, value, offset, true, noAssert)
  2230. };
  2231. Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  2232. return writeDouble(this, value, offset, false, noAssert)
  2233. };
  2234. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2235. Buffer$1.prototype.copy = function copy (target, targetStart, start, end) {
  2236. if (!start) start = 0;
  2237. if (!end && end !== 0) end = this.length;
  2238. if (targetStart >= target.length) targetStart = target.length;
  2239. if (!targetStart) targetStart = 0;
  2240. if (end > 0 && end < start) end = start;
  2241. // Copy 0 bytes; we're done
  2242. if (end === start) return 0
  2243. if (target.length === 0 || this.length === 0) return 0
  2244. // Fatal error conditions
  2245. if (targetStart < 0) {
  2246. throw new RangeError('targetStart out of bounds')
  2247. }
  2248. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2249. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2250. // Are we oob?
  2251. if (end > this.length) end = this.length;
  2252. if (target.length - targetStart < end - start) {
  2253. end = target.length - targetStart + start;
  2254. }
  2255. var len = end - start;
  2256. var i;
  2257. if (this === target && start < targetStart && targetStart < end) {
  2258. // descending copy from end
  2259. for (i = len - 1; i >= 0; --i) {
  2260. target[i + targetStart] = this[i + start];
  2261. }
  2262. } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) {
  2263. // ascending copy from start
  2264. for (i = 0; i < len; ++i) {
  2265. target[i + targetStart] = this[i + start];
  2266. }
  2267. } else {
  2268. Uint8Array.prototype.set.call(
  2269. target,
  2270. this.subarray(start, start + len),
  2271. targetStart
  2272. );
  2273. }
  2274. return len
  2275. };
  2276. // Usage:
  2277. // buffer.fill(number[, offset[, end]])
  2278. // buffer.fill(buffer[, offset[, end]])
  2279. // buffer.fill(string[, offset[, end]][, encoding])
  2280. Buffer$1.prototype.fill = function fill (val, start, end, encoding) {
  2281. // Handle string cases:
  2282. if (typeof val === 'string') {
  2283. if (typeof start === 'string') {
  2284. encoding = start;
  2285. start = 0;
  2286. end = this.length;
  2287. } else if (typeof end === 'string') {
  2288. encoding = end;
  2289. end = this.length;
  2290. }
  2291. if (val.length === 1) {
  2292. var code = val.charCodeAt(0);
  2293. if (code < 256) {
  2294. val = code;
  2295. }
  2296. }
  2297. if (encoding !== undefined && typeof encoding !== 'string') {
  2298. throw new TypeError('encoding must be a string')
  2299. }
  2300. if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) {
  2301. throw new TypeError('Unknown encoding: ' + encoding)
  2302. }
  2303. } else if (typeof val === 'number') {
  2304. val = val & 255;
  2305. }
  2306. // Invalid ranges are not set to a default, so can range check early.
  2307. if (start < 0 || this.length < start || this.length < end) {
  2308. throw new RangeError('Out of range index')
  2309. }
  2310. if (end <= start) {
  2311. return this
  2312. }
  2313. start = start >>> 0;
  2314. end = end === undefined ? this.length : end >>> 0;
  2315. if (!val) val = 0;
  2316. var i;
  2317. if (typeof val === 'number') {
  2318. for (i = start; i < end; ++i) {
  2319. this[i] = val;
  2320. }
  2321. } else {
  2322. var bytes = internalIsBuffer(val)
  2323. ? val
  2324. : utf8ToBytes(new Buffer$1(val, encoding).toString());
  2325. var len = bytes.length;
  2326. for (i = 0; i < end - start; ++i) {
  2327. this[i + start] = bytes[i % len];
  2328. }
  2329. }
  2330. return this
  2331. };
  2332. // HELPER FUNCTIONS
  2333. // ================
  2334. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  2335. function base64clean (str) {
  2336. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2337. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  2338. // Node converts strings with length < 2 to ''
  2339. if (str.length < 2) return ''
  2340. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2341. while (str.length % 4 !== 0) {
  2342. str = str + '=';
  2343. }
  2344. return str
  2345. }
  2346. function stringtrim (str) {
  2347. if (str.trim) return str.trim()
  2348. return str.replace(/^\s+|\s+$/g, '')
  2349. }
  2350. function toHex (n) {
  2351. if (n < 16) return '0' + n.toString(16)
  2352. return n.toString(16)
  2353. }
  2354. function utf8ToBytes (string, units) {
  2355. units = units || Infinity;
  2356. var codePoint;
  2357. var length = string.length;
  2358. var leadSurrogate = null;
  2359. var bytes = [];
  2360. for (var i = 0; i < length; ++i) {
  2361. codePoint = string.charCodeAt(i);
  2362. // is surrogate component
  2363. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2364. // last char was a lead
  2365. if (!leadSurrogate) {
  2366. // no lead yet
  2367. if (codePoint > 0xDBFF) {
  2368. // unexpected trail
  2369. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2370. continue
  2371. } else if (i + 1 === length) {
  2372. // unpaired lead
  2373. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2374. continue
  2375. }
  2376. // valid lead
  2377. leadSurrogate = codePoint;
  2378. continue
  2379. }
  2380. // 2 leads in a row
  2381. if (codePoint < 0xDC00) {
  2382. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2383. leadSurrogate = codePoint;
  2384. continue
  2385. }
  2386. // valid surrogate pair
  2387. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  2388. } else if (leadSurrogate) {
  2389. // valid bmp char, but last char was a lead
  2390. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2391. }
  2392. leadSurrogate = null;
  2393. // encode utf8
  2394. if (codePoint < 0x80) {
  2395. if ((units -= 1) < 0) break
  2396. bytes.push(codePoint);
  2397. } else if (codePoint < 0x800) {
  2398. if ((units -= 2) < 0) break
  2399. bytes.push(
  2400. codePoint >> 0x6 | 0xC0,
  2401. codePoint & 0x3F | 0x80
  2402. );
  2403. } else if (codePoint < 0x10000) {
  2404. if ((units -= 3) < 0) break
  2405. bytes.push(
  2406. codePoint >> 0xC | 0xE0,
  2407. codePoint >> 0x6 & 0x3F | 0x80,
  2408. codePoint & 0x3F | 0x80
  2409. );
  2410. } else if (codePoint < 0x110000) {
  2411. if ((units -= 4) < 0) break
  2412. bytes.push(
  2413. codePoint >> 0x12 | 0xF0,
  2414. codePoint >> 0xC & 0x3F | 0x80,
  2415. codePoint >> 0x6 & 0x3F | 0x80,
  2416. codePoint & 0x3F | 0x80
  2417. );
  2418. } else {
  2419. throw new Error('Invalid code point')
  2420. }
  2421. }
  2422. return bytes
  2423. }
  2424. function asciiToBytes (str) {
  2425. var byteArray = [];
  2426. for (var i = 0; i < str.length; ++i) {
  2427. // Node's code seems to be doing this and not & 0x7F..
  2428. byteArray.push(str.charCodeAt(i) & 0xFF);
  2429. }
  2430. return byteArray
  2431. }
  2432. function utf16leToBytes (str, units) {
  2433. var c, hi, lo;
  2434. var byteArray = [];
  2435. for (var i = 0; i < str.length; ++i) {
  2436. if ((units -= 2) < 0) break
  2437. c = str.charCodeAt(i);
  2438. hi = c >> 8;
  2439. lo = c % 256;
  2440. byteArray.push(lo);
  2441. byteArray.push(hi);
  2442. }
  2443. return byteArray
  2444. }
  2445. function base64ToBytes (str) {
  2446. return toByteArray(base64clean(str))
  2447. }
  2448. function blitBuffer (src, dst, offset, length) {
  2449. for (var i = 0; i < length; ++i) {
  2450. if ((i + offset >= dst.length) || (i >= src.length)) break
  2451. dst[i + offset] = src[i];
  2452. }
  2453. return i
  2454. }
  2455. function isnan (val) {
  2456. return val !== val // eslint-disable-line no-self-compare
  2457. }
  2458. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  2459. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2460. // Object.prototype.constructor. Remove this eventually
  2461. function isBuffer$1(obj) {
  2462. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  2463. }
  2464. function isFastBuffer (obj) {
  2465. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2466. }
  2467. // For Node v0.10 support. Remove this eventually.
  2468. function isSlowBuffer (obj) {
  2469. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  2470. }
  2471. /*
  2472. * Shared base64 decode helper for generated decode data.
  2473. * Assumes global atob is available.
  2474. */
  2475. function decodeBase64(input) {
  2476. const binary =
  2477. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2478. typeof atob === "function"
  2479. ? // Browser (and Node >=16)
  2480. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2481. atob(input)
  2482. : // Older Node versions (<16)
  2483. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2484. typeof Buffer$1.from === "function"
  2485. ? // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2486. Buffer$1.from(input, "base64").toString("binary")
  2487. : // eslint-disable-next-line unicorn/no-new-buffer, n/no-deprecated-api
  2488. new Buffer$1(input, "base64").toString("binary");
  2489. const evenLength = binary.length & -2; // Round down to even length
  2490. const out = new Uint16Array(evenLength / 2);
  2491. for (let index = 0, outIndex = 0; index < evenLength; index += 2) {
  2492. const lo = binary.charCodeAt(index);
  2493. const hi = binary.charCodeAt(index + 1);
  2494. out[outIndex++] = lo | (hi << 8);
  2495. }
  2496. return out;
  2497. }
  2498. // Generated using scripts/write-decode-map.ts
  2499. const htmlDecodeTree = /* #__PURE__ */ decodeBase64("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0EBRAFKAU0B8iFvbgxhZABpAGwAO4DHAMdAcgBjAAhhbiJpbnQAAKAwIm8AdAAKYQABZG5ZAV0BaSJsbGEAuGB0I2VyRG90ALdg8gA5AWkAp2NyImNsZQAAAkRNUFRwAXQBeQF9AW8AdAAAoJkiaSJudXMAAKCWIuwhdXMAoJUiaSJtZXMAAKCXIm8AAAFjc4cBlAFrKndpc2VDb250b3VySW50ZWdyYWwAAKAyImUjQ3VybHkAAAFEUZwBpAFvJXVibGVRdW90ZQAAoB0gdSJvdGUAAKAZIAACbG5wdbABtgHNAdgBbwBuAGWgNyIAoHQqgAFnaXQAvAHBAcUB8iJ1ZW50AKBhIm4AdAAAoC8i7yV1ckludGVncmFsAKAuIgABZnLRAdMBAKACIe8iZHVjdACgECJuLnRlckNsb2Nrd2lzZUNvbnRvdXJJbnRlZ3JhbAAAoDMi7yFzcwCgLypjAHIAAOA12J7ccABDoNMiYQBwAACgTSKABURKU1phY2VmaW9zAAsCEgIVAhgCGwIsAjQCOQI9AnMCfwNvoEUh9CJyYWhkAKARKWMAeQACZGMAeQAFZGMAeQAPZIABZ3JzACECJQIoAuchZXIAoCEgcgAAoKEhaAB2AACg5CoAAWF5MAIzAvIhb24OYRRkbAB0oAciYQCUY3IAAOA12AfdAAFhZkECawIAAWNtRQJnAvIjaXRpY2FsAAJBREdUUAJUAl8CYwJjInV0ZQC0YG8AdAFZAloC2WJiJGxlQWN1dGUA3WJyImF2ZQBgYGkibGRlANxi7yFuZACgxCJmJWVyZW50aWFsRAAAoEYhcAR9AgAAAAAAAIECjgIAABoDZgAA4DXYO91EoagAhQKJAm8AdAAAoNwgcSJ1YWwAAKBQIuIhbGUAA0NETFJVVpkCqAK1Au8C/wIRA28AbgB0AG8AdQByAEkAbgB0AGUAZwByAGEA7ADEAW8AdAKvAgAAAACwAqhgbiNBcnJvdwAAoNMhAAFlb7kC0AJmAHQAgAFBUlQAwQLGAs0CciJyb3cAAKDQIekkZ2h0QXJyb3cAoNQhZQDlACsCbgBnAAABTFLWAugC5SFmdAABQVLcAuECciJyb3cAAKD4J+kkZ2h0QXJyb3cAoPon6SRnaHRBcnJvdwCg+SdpImdodAAAAUFU9gL7AnIicm93AACg0iFlAGUAAKCoInAAQQIGAwAAAAALA3Iicm93AACg0SFvJHduQXJyb3cAAKDVIWUlcnRpY2FsQmFyAACgJSJuAAADQUJMUlRhJAM2AzoDWgNxA3oDciJyb3cAAKGTIUJVLAMwA2EAcgAAoBMpcCNBcnJvdwAAoPUhciJldmUAEWPlIWZ00gJDAwAASwMAAFIDaSVnaHRWZWN0b3IAAKBQKWUkZVZlY3RvcgAAoF4p5SJjdG9yQqC9IWEAcgAAoFYpaSJnaHQA1AFiAwAAaQNlJGVWZWN0b3IAAKBfKeUiY3RvckKgwSFhAHIAAKBXKWUAZQBBoKQiciJyb3cAAKCnIXIAcgBvAPcAtAIAAWN0gwOHA3IAAOA12J/c8iFvaxBhAAhOVGFjZGZnbG1vcHFzdHV4owOlA6kDsAO/A8IDxgPNA9ID8gP9AwEEFAQeBCAEJQRHAEphSAA7gNAA0EBjAHUAdABlADuAyQDJQIABYWl5ALYDuQO+A/Ihb24aYXIAYwA7gMoAykAtZG8AdAAWYXIAAOA12AjdcgBhAHYAZQA7gMgAyEDlIm1lbnQAoAgiAAFhcNYD2QNjAHIAEmF0AHkAUwLhAwAAAADpA20lYWxsU3F1YXJlAACg+yVlJ3J5U21hbGxTcXVhcmUAAKCrJQABZ3D2A/kDbwBuABhhZgAA4DXYPN3zImlsb26VY3UAAAFhaQYEDgRsAFSgdSppImxkZQAAoEIi7CNpYnJpdW0AoMwhAAFjaRgEGwRyAACgMCFtAACgcyphAJdjbQBsADuAywDLQAABaXApBC0E8yF0cwCgAyLvJG5lbnRpYWxFAKBHIYACY2Zpb3MAPQQ/BEMEXQRyBHkAJGRyAADgNdgJ3WwibGVkAFMCTAQAAAAAVARtJWFsbFNxdWFyZQAAoPwlZSdyeVNtYWxsU3F1YXJlAACgqiVwA2UEAABpBAAAAABtBGYAAOA12D3dwSFsbACgACLyI2llcnRyZgCgMSFjAPIAcQQABkpUYWJjZGZnb3JzdIgEiwSOBJMElwSkBKcEqwStBLIE5QTqBGMAeQADZDuAPgA+QO0hbWFkoJMD3GNyImV2ZQAeYYABZWl5AJ0EoASjBOQhaWwiYXIAYwAcYRNkbwB0ACBhcgAA4DXYCt0AoNkicABmAADgNdg+3eUiYXRlcgADRUZHTFNUvwTIBM8E1QTZBOAEcSJ1YWwATKBlIuUhc3MAoNsidSRsbEVxdWFsAACgZyJyI2VhdGVyAACgoirlIXNzAKB3IuwkYW50RXF1YWwAoH4qaSJsZGUAAKBzImMAcgAA4DXYotwAoGsiAARBYWNmaW9zdfkE/QQFBQgFCwUTBSIFKwVSIkRjeQAqZAABY3QBBQQFZQBrAMdiXmDpIXJjJGFyAACgDCFsJWJlcnRTcGFjZQAAoAsh8AEYBQAAGwVmAACgDSHpJXpvbnRhbExpbmUAoAAlAAFjdCYFKAXyABIF8iFvayZhbQBwAEQBMQU5BW8AdwBuAEgAdQBtAPAAAAFxInVhbAAAoE8iAAdFSk9hY2RmZ21ub3N0dVMFVgVZBVwFYwVtBXAFcwV6BZAFtgXFBckFzQVjAHkAFWTsIWlnMmFjAHkAAWRjAHUAdABlADuAzQDNQAABaXlnBWwFcgBjADuAzgDOQBhkbwB0ADBhcgAAoBEhcgBhAHYAZQA7gMwAzEAAoREhYXB/BYsFAAFjZ4MFhQVyACphaSNuYXJ5SQAAoEghbABpAGUA8wD6AvQBlQUAAKUFZaAsIgABZ3KaBZ4F8iFhbACgKyLzI2VjdGlvbgCgwiJpI3NpYmxlAAABQ1SsBbEFbyJtbWEAAKBjIGkibWVzAACgYiCAAWdwdAC8Bb8FwwVvAG4ALmFmAADgNdhA3WEAmWNjAHIAAKAQIWkibGRlAChh6wHSBQAA1QVjAHkABmRsADuAzwDPQIACY2Zvc3UA4QXpBe0F8gX9BQABaXnlBegFcgBjADRhGWRyAADgNdgN3XAAZgAA4DXYQd3jAfcFAAD7BXIAAOA12KXc8iFjeQhk6yFjeQRkgANISmFjZm9zAAwGDwYSBhUGHQYhBiYGYwB5ACVkYwB5AAxk8CFwYZpjAAFleRkGHAbkIWlsNmEaZHIAAOA12A7dcABmAADgNdhC3WMAcgAA4DXYptyABUpUYWNlZmxtb3N0AD0GQAZDBl4GawZkB2gHcAd0B80H2gdjAHkACWQ7gDwAPECAAmNtbnByAEwGTwZSBlUGWwb1IXRlOWHiIWRhm2NnAACg6ifsI2FjZXRyZgCgEiFyAACgniGAAWFleQBkBmcGagbyIW9uPWHkIWlsO2EbZAABZnNvBjQHdAAABUFDREZSVFVWYXKABp4GpAbGBssG3AYDByEHwQIqBwABbnKEBowGZyVsZUJyYWNrZXQAAKDoJ/Ihb3cAoZAhQlKTBpcGYQByAACg5CHpJGdodEFycm93AKDGIWUjaWxpbmcAAKAII28A9QGqBgAAsgZiJWxlQnJhY2tldAAAoOYnbgDUAbcGAAC+BmUkZVZlY3RvcgAAoGEp5SJjdG9yQqDDIWEAcgAAoFkpbCJvb3IAAKAKI2kiZ2h0AAABQVbSBtcGciJyb3cAAKCUIeUiY3RvcgCgTikAAWVy4AbwBmUAAKGjIkFW5gbrBnIicm93AACgpCHlImN0b3IAoFopaSNhbmdsZQBCorIi+wYAAAAA/wZhAHIAAKDPKXEidWFsAACgtCJwAIABRFRWAAoHEQcYB+8kd25WZWN0b3IAoFEpZSRlVmVjdG9yAACgYCnlImN0b3JCoL8hYQByAACgWCnlImN0b3JCoLwhYQByAACgUilpAGcAaAB0AGEAcgByAG8A9wDMAnMAAANFRkdMU1Q/B0cHTgdUB1gHXwfxJXVhbEdyZWF0ZXIAoNoidSRsbEVxdWFsAACgZiJyI2VhdGVyAACgdiLlIXNzAKChKuwkYW50RXF1YWwAoH0qaSJsZGUAAKByInIAAOA12A/dZaDYIuYjdGFycm93AKDaIWkiZG90AD9hgAFucHcAege1B7kHZwAAAkxSbHKCB5QHmwerB+UhZnQAAUFSiAeNB3Iicm93AACg9SfpJGdodEFycm93AKD3J+kkZ2h0QXJyb3cAoPYn5SFmdAABYXLcAqEHaQBnAGgAdABhAHIAcgBvAPcA5wJpAGcAaAB0AGEAcgByAG8A9wDuAmYAAOA12EPdZQByAAABTFK/B8YHZSRmdEFycm93AACgmSHpJGdodEFycm93AKCYIYABY2h0ANMH1QfXB/IAWgYAoLAh8iFva0FhAKBqIgAEYWNlZmlvc3XpB+wH7gf/BwMICQgOCBEIcAAAoAUpeQAcZAABZGzyB/kHaSR1bVNwYWNlAACgXyBsI2ludHJmAACgMyFyAADgNdgQ3e4jdXNQbHVzAKATInAAZgAA4DXYRN1jAPIA/gecY4AESmFjZWZvc3R1ACEIJAgoCDUIgQiFCDsKQApHCmMAeQAKZGMidXRlAENhgAFhZXkALggxCDQI8iFvbkdh5CFpbEVhHWSAAWdzdwA7CGEIfQjhInRpdmWAAU1UVgBECEwIWQhlJWRpdW1TcGFjZQAAoAsgaABpAAABY25SCFMIawBTAHAAYQBjAOUASwhlAHIAeQBUAGgAaQDuAFQI9CFlZAABR0xnCHUIcgBlAGEAdABlAHIARwByAGUAYQB0AGUA8gDrBGUAcwBzAEwAZQBzAPMA2wdMImluZQAKYHIAAOA12BHdAAJCbnB0jAiRCJkInAhyImVhawAAoGAgwiZyZWFraW5nU3BhY2WgYGYAAKAVIUOq7CqzCMIIzQgAAOcIGwkAAAAAAAAtCQAAbwkAAIcJAACdCcAJGQoAADQKAAFvdbYIvAjuI2dydWVudACgYiJwIkNhcAAAoG0ibyh1YmxlVmVydGljYWxCYXIAAKAmIoABbHF4ANII1wjhCOUibWVudACgCSL1IWFsVKBgImkibGRlAADgQiI4A2kic3RzAACgBCJyI2VhdGVyAACjbyJFRkdMU1T1CPoIAgkJCQ0JFQlxInVhbAAAoHEidSRsbEVxdWFsAADgZyI4A3IjZWF0ZXIAAOBrIjgD5SFzcwCgeSLsJGFudEVxdWFsAOB+KjgDaSJsZGUAAKB1IvUhbXBEASAJJwnvI3duSHVtcADgTiI4A3EidWFsAADgTyI4A2UAAAFmczEJRgn0JFRyaWFuZ2xlQqLqIj0JAAAAAEIJYQByAADgzyk4A3EidWFsAACg7CJzAICibiJFR0xTVABRCVYJXAlhCWkJcSJ1YWwAAKBwInIjZWF0ZXIAAKB4IuUhc3MA4GoiOAPsJGFudEVxdWFsAOB9KjgDaSJsZGUAAKB0IuUic3RlZAABR0x1CX8J8iZlYXRlckdyZWF0ZXIA4KIqOAPlI3NzTGVzcwDgoSo4A/IjZWNlZGVzAKGAIkVTjwmVCXEidWFsAADgryo4A+wkYW50RXF1YWwAoOAiAAFlaaAJqQl2JmVyc2VFbGVtZW50AACgDCLnJWh0VHJpYW5nbGVCousitgkAAAAAuwlhAHIAAODQKTgDcSJ1YWwAAKDtIgABcXXDCeAJdSNhcmVTdQAAAWJwywnVCfMhZXRF4I8iOANxInVhbAAAoOIi5SJyc2V0ReCQIjgDcSJ1YWwAAKDjIoABYmNwAOYJ8AkNCvMhZXRF4IIi0iBxInVhbAAAoIgi4yJlZWRzgKGBIkVTVAD6CQAKBwpxInVhbAAA4LAqOAPsJGFudEVxdWFsAKDhImkibGRlAADgfyI4A+UicnNldEXggyLSIHEidWFsAACgiSJpImxkZQCAoUEiRUZUACIKJwouCnEidWFsAACgRCJ1JGxsRXF1YWwAAKBHImkibGRlAACgSSJlJXJ0aWNhbEJhcgAAoCQiYwByAADgNdip3GkAbABkAGUAO4DRANFAnWMAB0VhY2RmZ21vcHJzdHV2XgphCmgKcgp2CnoKgQqRCpYKqwqtCrsKyArNCuwhaWdSYWMAdQB0AGUAO4DTANNAAAFpeWwKcQpyAGMAO4DUANRAHmRiImxhYwBQYXIAAOA12BLdcgBhAHYAZQA7gNIA0kCAAWFlaQCHCooKjQpjAHIATGFnAGEAqWNjInJvbgCfY3AAZgAA4DXYRt3lI25DdXJseQABRFGeCqYKbyV1YmxlUXVvdGUAAKAcIHUib3RlAACgGCAAoFQqAAFjbLEKtQpyAADgNdiq3GEAcwBoADuA2ADYQGkAbAHACsUKZABlADuA1QDVQGUAcwAAoDcqbQBsADuA1gDWQGUAcgAAAUJQ0wrmCgABYXLXCtoKcgAAoD4gYQBjAAABZWvgCuIKAKDeI2UAdAAAoLQjYSVyZW50aGVzaXMAAKDcI4AEYWNmaGlsb3JzAP0KAwsFCwkLCwsMCxELIwtaC3IjdGlhbEQAAKACInkAH2RyAADgNdgT3WkApmOgY/Ujc01pbnVzsWAAAWlwFQsgC24AYwBhAHIAZQBwAGwAYQBuAOUACgVmAACgGSGAobsqZWlvACoLRQtJC+MiZWRlc4CheiJFU1QANAs5C0ALcSJ1YWwAAKCvKuwkYW50RXF1YWwAoHwiaSJsZGUAAKB+Im0AZQAAoDMgAAFkcE0LUQv1IWN0AKAPIm8jcnRpb24AYaA3ImwAAKAdIgABY2leC2ILcgAA4DXYq9yoYwACVWZvc2oLbwtzC3cLTwBUADuAIgAiQHIAAOA12BTdcABmAACgGiFjAHIAAOA12KzcAAZCRWFjZWZoaW9yc3WPC5MLlwupC7YL2AvbC90LhQyTDJoMowzhIXJyAKAQKUcAO4CuAK5AgAFjbnIAnQugC6ML9SF0ZVRhZwAAoOsncgB0oKAhbAAAoBYpgAFhZXkArwuyC7UL8iFvblhh5CFpbFZhIGR2oBwhZSJyc2UAAAFFVb8LzwsAAWxxwwvIC+UibWVudACgCyL1JGlsaWJyaXVtAKDLIXAmRXF1aWxpYnJpdW0AAKBvKXIAAKAcIW8AoWPnIWh0AARBQ0RGVFVWYewLCgwQDDIMNwxeDHwM9gIAAW5y8Av4C2clbGVCcmFja2V0AACg6SfyIW93AKGSIUJM/wsDDGEAcgAAoOUhZSRmdEFycm93AACgxCFlI2lsaW5nAACgCSNvAPUBFgwAAB4MYiVsZUJyYWNrZXQAAKDnJ24A1AEjDAAAKgxlJGVWZWN0b3IAAKBdKeUiY3RvckKgwiFhAHIAAKBVKWwib29yAACgCyMAAWVyOwxLDGUAAKGiIkFWQQxGDHIicm93AACgpiHlImN0b3IAoFspaSNhbmdsZQBCorMiVgwAAAAAWgxhAHIAAKDQKXEidWFsAACgtSJwAIABRFRWAGUMbAxzDO8kd25WZWN0b3IAoE8pZSRlVmVjdG9yAACgXCnlImN0b3JCoL4hYQByAACgVCnlImN0b3JCoMAhYQByAACgUykAAXB1iQyMDGYAAKAdIe4kZEltcGxpZXMAoHAp6SRnaHRhcnJvdwCg2yEAAWNongyhDHIAAKAbIQCgsSHsJGVEZWxheWVkAKD0KYAGSE9hY2ZoaW1vcXN0dQC/DMgMzAzQDOIM5gwKDQ0NFA0ZDU8NVA1YDQABQ2PDDMYMyCFjeSlkeQAoZEYiVGN5ACxkYyJ1dGUAWmEAorwqYWVpedgM2wzeDOEM8iFvbmBh5CFpbF5hcgBjAFxhIWRyAADgNdgW3e8hcnQAAkRMUlXvDPYM/QwEDW8kd25BcnJvdwAAoJMhZSRmdEFycm93AACgkCHpJGdodEFycm93AKCSIXAjQXJyb3cAAKCRIechbWGjY+EkbGxDaXJjbGUAoBgicABmAADgNdhK3XICHw0AAAAAIg10AACgGiLhIXJlgKGhJUlTVQAqDTINSg3uJXRlcnNlY3Rpb24AoJMidQAAAWJwNw1ADfMhZXRFoI8icSJ1YWwAAKCRIuUicnNldEWgkCJxInVhbAAAoJIibiJpb24AAKCUImMAcgAA4DXYrtxhAHIAAKDGIgACYmNtcF8Nag2ODZANc6DQImUAdABFoNAicSJ1YWwAAKCGIgABY2huDYkNZSJlZHMAgKF7IkVTVAB4DX0NhA1xInVhbAAAoLAq7CRhbnRFcXVhbACgfSJpImxkZQAAoH8iVABoAGEA9ADHCwCgESIAodEiZXOVDZ8NciJzZXQARaCDInEidWFsAACghyJlAHQAAKDRIoAFSFJTYWNmaGlvcnMAtQ27Db8NyA3ODdsN3w3+DRgOHQ4jDk8AUgBOADuA3gDeQMEhREUAoCIhAAFIY8MNxg1jAHkAC2R5ACZkAAFidcwNzQ0JYKRjgAFhZXkA1A3XDdoN8iFvbmRh5CFpbGJhImRyAADgNdgX3QABZWnjDe4N8gHoDQAA7Q3lImZvcmUAoDQiYQCYYwABY27yDfkNayNTcGFjZQAA4F8gCiDTInBhY2UAoAkg7CFkZYChPCJFRlQABw4MDhMOcSJ1YWwAAKBDInUkbGxFcXVhbAAAoEUiaSJsZGUAAKBIInAAZgAA4DXYS93pI3BsZURvdACg2yAAAWN0Jw4rDnIAAOA12K/c8iFva2Zh4QpFDlYOYA5qDgAAbg5yDgAAAAAAAAAAAAB5DnwOqA6zDgAADg8RDxYPGg8AAWNySA5ODnUAdABlADuA2gDaQHIAb6CfIeMhaXIAoEkpcgDjAVsOAABdDnkADmR2AGUAbGEAAWl5Yw5oDnIAYwA7gNsA20AjZGIibGFjAHBhcgAA4DXYGN1yAGEAdgBlADuA2QDZQOEhY3JqYQABZGl/Dp8OZQByAAABQlCFDpcOAAFhcokOiw5yAF9gYQBjAAABZWuRDpMOAKDfI2UAdAAAoLUjYSVyZW50aGVzaXMAAKDdI28AbgBQoMMi7CF1cwCgjiIAAWdwqw6uDm8AbgByYWYAAOA12EzdAARBREVUYWRwc78O0g7ZDuEOBQPqDvMOBw9yInJvdwDCoZEhyA4AAMwOYQByAACgEilvJHduQXJyb3cAAKDFIW8kd25BcnJvdwAAoJUhcSV1aWxpYnJpdW0AAKBuKWUAZQBBoKUiciJyb3cAAKClIW8AdwBuAGEAcgByAG8A9wAQA2UAcgAAAUxS+Q4AD2UkZnRBcnJvdwAAoJYh6SRnaHRBcnJvdwCglyFpAGyg0gNvAG4ApWPpIW5nbmFjAHIAAOA12LDcaSJsZGUAaGFtAGwAO4DcANxAgAREYmNkZWZvc3YALQ8xDzUPNw89D3IPdg97D4AP4SFzaACgqyJhAHIAAKDrKnkAEmThIXNobKCpIgCg5ioAAWVyQQ9DDwCgwSKAAWJ0eQBJD00Paw9hAHIAAKAWIGmgFiDjIWFsAAJCTFNUWA9cD18PZg9hAHIAAKAjIukhbmV8YGUkcGFyYXRvcgAAoFgnaSJsZGUAAKBAItQkaGluU3BhY2UAoAogcgAA4DXYGd1wAGYAAOA12E3dYwByAADgNdix3GQiYXNoAACgqiKAAmNlZm9zAI4PkQ+VD5kPng/pIXJjdGHkIWdlAKDAInIAAOA12BrdcABmAADgNdhO3WMAcgAA4DXYstwAAmZpb3OqD64Prw+0D3IAAOA12BvdnmNwAGYAAOA12E/dYwByAADgNdiz3IAEQUlVYWNmb3N1AMgPyw/OD9EP2A/gD+QP6Q/uD2MAeQAvZGMAeQAHZGMAeQAuZGMAdQB0AGUAO4DdAN1AAAFpedwP3w9yAGMAdmErZHIAAOA12BzdcABmAADgNdhQ3WMAcgAA4DXYtNxtAGwAeGEABEhhY2RlZm9z/g8BEAUQDRAQEB0QIBAkEGMAeQAWZGMidXRlAHlhAAFheQkQDBDyIW9ufWEXZG8AdAB7YfIBFRAAABwQbwBXAGkAZAB0AOgAVAhhAJZjcgAAoCghcABmAACgJCFjAHIAAOA12LXc4QtCEEkQTRAAAGcQbRByEAAAAAAAAAAAeRCKEJcQ8hD9EAAAGxEhETIROREAAD4RYwB1AHQAZQA7gOEA4UByImV2ZQADYYCiPiJFZGl1eQBWEFkQWxBgEGUQAOA+IjMDAKA/InIAYwA7gOIA4kB0AGUAO4C0ALRAMGRsAGkAZwA7gOYA5kByoGEgAOA12B7dcgBhAHYAZQA7gOAA4EAAAWVwfBCGEAABZnCAEIQQ8yF5bQCgNSHoAIMQaABhALFjAAFhcI0QWwAAAWNskRCTEHIAAWFnAACgPypkApwQAAAAALEQAKInImFkc3ajEKcQqRCuEG4AZAAAoFUqAKBcKmwib3BlAACgWCoAoFoqAKMgImVsbXJzersQvRDAEN0Q5RDtEACgpCllAACgICJzAGQAYaAhImEEzhDQENIQ1BDWENgQ2hDcEACgqCkAoKkpAKCqKQCgqykAoKwpAKCtKQCgrikAoK8pdAB2oB8iYgBkoL4iAKCdKQABcHTpEOwQaAAAoCIixWDhIXJyAKB8IwABZ3D1EPgQbwBuAAVhZgAA4DXYUt0Ao0giRWFlaW9wBxEJEQ0RDxESERQRAKBwKuMhaXIAoG8qAKBKImQAAKBLInMAJ2DyIW94ZaBIIvEADhFpAG4AZwA7gOUA5UCAAWN0eQAmESoRKxFyAADgNdi23CpgbQBwAGWgSCLxAPgBaQBsAGQAZQA7gOMA40BtAGwAO4DkAORAAAFjaUERRxFvAG4AaQBuAPQA6AFuAHQAAKARKgAITmFiY2RlZmlrbG5vcHJzdWQRaBGXEZ8RpxGrEdIR1hErEjASexKKEn0RThNbE3oTbwB0AACg7SoAAWNybBGJEWsAAAJjZXBzdBF4EX0RghHvIW5nAKBMInAjc2lsb24A9mNyImltZQAAoDUgaQBtAGWgPSJxAACgzSJ2AY0RkRFlAGUAAKC9ImUAZABnoAUjZQAAoAUjcgBrAHSgtSPiIXJrAKC2IwABb3mjEaYRbgDnAHcRMWTxIXVvAKAeIIACY21wcnQAtBG5Eb4RwRHFEeEhdXPloDUi5ABwInR5dgAAoLApcwDpAH0RbgBvAPUA6gCAAWFodwDLEcwRzhGyYwCgNiHlIWVuAKBsInIAAOA12B/dZwCAA2Nvc3R1dncA4xHyEQUSEhIhEiYSKRKAAWFpdQDpEesR7xHwAKMFcgBjAACg7yVwAACgwyKAAWRwdAD4EfwRABJvAHQAAKAAKuwhdXMAoAEqaSJtZXMAAKACKnECCxIAAAAADxLjIXVwAKAGKmEAcgAAoAUm8iNpYW5nbGUAAWR1GhIeEu8hd24AoL0lcAAAoLMlcCJsdXMAAKAEKmUA5QBCD+UAkg9hInJvdwAAoA0pgAFha28ANhJoEncSAAFjbjoSZRJrAIABbHN0AEESRxJNEm8jemVuZ2UAAKDrKXEAdQBhAHIA5QBcBPIjaWFuZ2xlgKG0JWRscgBYElwSYBLvIXduAKC+JeUhZnQAoMIlaSJnaHQAAKC4JWsAAKAjJLEBbRIAAHUSsgFxEgAAcxIAoJIlAKCRJTQAAKCTJWMAawAAoIglAAFlb38ShxJx4D0A5SD1IWl2AOBhIuUgdAAAoBAjAAJwdHd4kRKVEpsSnxJmAADgNdhT3XSgpSJvAG0AAKClIvQhaWUAoMgiAAZESFVWYmRobXB0dXayEsES0RLgEvcS+xIKExoTHxMjEygTNxMAAkxSbHK5ErsSvRK/EgCgVyUAoFQlAKBWJQCgUyUAolAlRFVkdckSyxLNEs8SAKBmJQCgaSUAoGQlAKBnJQACTFJsctgS2hLcEt4SAKBdJQCgWiUAoFwlAKBZJQCjUSVITFJobHLrEu0S7xLxEvMS9RIAoGwlAKBjJQCgYCUAoGslAKBiJQCgXyVvAHgAAKDJKQACTFJscgITBBMGEwgTAKBVJQCgUiUAoBAlAKAMJQCiACVEVWR1EhMUExYTGBMAoGUlAKBoJQCgLCUAoDQlaSJudXMAAKCfIuwhdXMAoJ4iaSJtZXMAAKCgIgACTFJsci8TMRMzEzUTAKBbJQCgWCUAoBglAKAUJQCjAiVITFJobHJCE0QTRhNIE0oTTBMAoGolAKBhJQCgXiUAoDwlAKAkJQCgHCUAAWV2UhNVE3YA5QD5AGIAYQByADuApgCmQAACY2Vpb2ITZhNqE24TcgAA4DXYt9xtAGkAAKBPIG0A5aA9IogRbAAAoVwAYmh0E3YTAKDFKfMhdWIAoMgnbAF+E4QTbABloCIgdAAAoCIgcAAAoU4iRWWJE4sTAKCuKvGgTyI8BeEMqRMAAN8TABQDFB8UAAAjFDQUAAAAAIUUAAAAAI0UAAAAANcU4xT3FPsUAACIFQAAlhWAAWNwcgCuE7ET1RP1IXRlB2GAoikiYWJjZHMAuxO/E8QTzhPSE24AZAAAoEQqciJjdXAAAKBJKgABYXXIE8sTcAAAoEsqcAAAoEcqbwB0AACgQCoA4CkiAP4AAWVv2RPcE3QAAKBBIO4ABAUAAmFlaXXlE+8T9RP4E/AB6hMAAO0TcwAAoE0qbwBuAA1hZABpAGwAO4DnAOdAcgBjAAlhcABzAHOgTCptAACgUCpvAHQAC2GAAWRtbgAIFA0UEhRpAGwAO4C4ALhAcCJ0eXYAAKCyKXQAAIGiADtlGBQZFKJAcgBkAG8A9ABiAXIAAOA12CDdgAFjZWkAKBQqFDIUeQBHZGMAawBtoBMn4SFyawCgEyfHY3IAAKPLJUVjZWZtcz8UQRRHFHcUfBSAFACgwykAocYCZWxGFEkUcQAAoFciZQBhAlAUAAAAAGAUciJyb3cAAAFsclYUWhTlIWZ0AKC6IWkiZ2h0AACguyGAAlJTYWNkAGgUaRRrFG8UcxSuYACgyCRzAHQAAKCbIukhcmMAoJoi4SFzaACgnSJuImludAAAoBAqaQBkAACg7yrjIWlyAKDCKfUhYnN1oGMmaQB0AACgYybsApMUmhS2FAAAwxRvAG4AZaA6APGgVCKrAG0CnxQAAAAAoxRhAHSgLABAYAChASJmbKcUqRTuABMNZQAAAW14rhSyFOUhbnQAoAEiZQDzANIB5wG6FAAAwBRkoEUibwB0AACgbSpuAPQAzAGAAWZyeQDIFMsUzhQA4DXYVN1vAOQA1wEAgakAO3MeAdMUcgAAoBchAAFhb9oU3hRyAHIAAKC1IXMAcwAAoBcnAAFjdeYU6hRyAADgNdi43AABYnDuFPIUZaDPKgCg0SploNAqAKDSKuQhb3QAoO8igANkZWxwcnZ3AAYVEBUbFSEVRBVlFYQV4SFycgABbHIMFQ4VAKA4KQCgNSlwAhYVAAAAABkVcgAAoN4iYwAAoN8i4SFycnCgtiEAoD0pgKIqImJjZG9zACsVMBU6FT4VQRVyImNhcAAAoEgqAAFhdTQVNxVwAACgRipwAACgSipvAHQAAKCNInIAAKBFKgDgKiIA/gACYWxydksVURVuFXMVcgByAG2gtyEAoDwpeQCAAWV2dwBYFWUVaRVxAHACXxUAAAAAYxVyAGUA4wAXFXUA4wAZFWUAZQAAoM4iZSJkZ2UAAKDPImUAbgA7gKQApEBlI2Fycm93AAABbHJ7FX8V5SFmdACgtiFpImdodAAAoLchZQDkAG0VAAFjaYsVkRVvAG4AaQBuAPQAkwFuAHQAAKAxImwiY3R5AACgLSOACUFIYWJjZGVmaGlqbG9yc3R1d3oAuBW7Fb8V1RXgFegV+RUKFhUWHxZUFlcWZRbFFtsW7xb7FgUXChdyAPIAtAJhAHIAAKBlKQACZ2xyc8YVyhXOFdAV5yFlcgCgICDlIXRoAKA4IfIA9QxoAHagECAAoKMiawHZFd4VYSJyb3cAAKAPKWEA4wBfAgABYXnkFecV8iFvbg9hNGQAoUYhYW/tFfQVAAFnciEC8RVyAACgyiF0InNlcQAAoHcqgAFnbG0A/xUCFgUWO4CwALBAdABhALRjcCJ0eXYAAKCxKQABaXIOFhIW8yFodACgfykA4DXYId1hAHIAAAFschsWHRYAoMMhAKDCIYACYWVnc3YAKBauAjYWOhY+Fm0AAKHEIm9zLhY0Fm4AZABzoMQi9SFpdACgZiZhIm1tYQDdY2kAbgAAoPIiAKH3AGlvQxZRFmQAZQAAgfcAO29KFksW90BuI3RpbWVzAACgxyJuAPgAUBZjAHkAUmRjAG8CXhYAAAAAYhZyAG4AAKAeI28AcAAAoA0jgAJscHR1dwBuFnEWdRaSFp4W7CFhciRgZgAA4DXYVd0AotkCZW1wc30WhBaJFo0WcQBkoFAibwB0AACgUSJpIm51cwAAoDgi7CF1cwCgFCLxInVhcmUAoKEiYgBsAGUAYgBhAHIAdwBlAGQAZwDlANcAbgCAAWFkaAClFqoWtBZyAHIAbwD3APUMbwB3AG4AYQByAHIAbwB3APMA8xVhI3Jwb29uAAABbHK8FsAWZQBmAPQAHBZpAGcAaAD0AB4WYgHJFs8WawBhAHIAbwD3AJILbwLUFgAAAADYFnIAbgAAoB8jbwBwAACgDCOAAWNvdADhFukW7BYAAXJ55RboFgDgNdi53FVkbAAAoPYp8iFvaxFhAAFkcvMW9xZvAHQAAKDxImkA5qC/JVsSAAFhaP8WAhdyAPIANQNhAPIA1wvhIm5nbGUAoKYpAAFjaQ4XEBd5AF9k5yJyYXJyAKD/JwAJRGFjZGVmZ2xtbm9wcXJzdHV4MRc4F0YXWxcyBF4XaRd5F40XrBe0F78X2RcVGCEYLRg1GEAYAAFEbzUXgRZvAPQA+BUAAWNzPBdCF3UAdABlADuA6QDpQPQhZXIAoG4qAAJhaW95TRdQF1YXWhfyIW9uG2FyAGOgViI7gOoA6kDsIW9uAKBVIk1kbwB0ABdhAAFEcmIXZhdvAHQAAKBSIgDgNdgi3XKhmipuF3QXYQB2AGUAO4DoAOhAZKCWKm8AdAAAoJgqgKGZKmlscwCAF4UXhxfuInRlcnMAoOcjAKATIWSglSpvAHQAAKCXKoABYXBzAJMXlheiF2MAcgATYXQAeQBzogUinxcAAAAAoRdlAHQAAKAFInAAMaADIDMBqRerFwCgBCAAoAUgAAFnc7AXsRdLYXAAAKACIAABZ3C4F7sXbwBuABlhZgAA4DXYVt2AAWFscwDFF8sXzxdyAHOg1SJsAACg4yl1AHMAAKBxKmkAAKG1A2x21RfYF28AbgC1Y/VjAAJjc3V24BfoF/0XEBgAAWlv5BdWF3IAYwAAoFYiaQLuFwAAAADwF+0ADQThIW50AAFnbPUX+Rd0AHIAAKCWKuUhc3MAoJUqgAFhZWkAAxgGGAoYbABzAD1gcwB0AACgXyJ2AESgYSJEAACgeCrwImFyc2wAoOUpAAFEYRkYHRhvAHQAAKBTInIAcgAAoHEpgAFjZGkAJxgqGO0XcgAAoC8hbwD0AIwCAAFhaDEYMhi3YzuA8ADwQAABbXI5GD0YbAA7gOsA60BvAACgrCCAAWNpcABGGEgYSxhsACFgcwD0ACwEAAFlb08YVxhjAHQAYQB0AGkAbwDuABoEbgBlAG4AdABpAGEAbADlADME4Ql1GAAAgRgAAIMYiBgAAAAAoRilGAAAqhgAALsYvhjRGAAA1xgnGWwAbABpAG4AZwBkAG8AdABzAGUA8QBlF3kARGRtImFsZQAAoEAmgAFpbHIAjRiRGJ0Y7CFpZwCgA/tpApcYAAAAAJoYZwAAoAD7aQBnAACgBPsA4DXYI93sIWlnAKAB++whaWcA4GYAagCAAWFsdACvGLIYthh0AACgbSZpAGcAAKAC+24AcwAAoLElbwBmAJJh8AHCGAAAxhhmAADgNdhX3QABYWvJGMwYbADsAGsEdqDUIgCg2SphI3J0aW50AACgDSoAAWFv2hgiGQABY3PeGB8ZsQPnGP0YBRkSGRUZAAAdGbID7xjyGPQY9xj5GAAA+xg7gL0AvUAAoFMhO4C8ALxAAKBVIQCgWSEAoFshswEBGQAAAxkAoFQhAKBWIbQCCxkOGQAAAAAQGTuAvgC+QACgVyEAoFwhNQAAoFghtgEZGQAAGxkAoFohAKBdITgAAKBeIWwAAKBEIHcAbgAAoCIjYwByAADgNdi73IAIRWFiY2RlZmdpamxub3JzdHYARhlKGVoZXhlmGWkZkhmWGZkZnRmgGa0ZxhnLGc8Z4BkjGmygZyIAoIwqgAFjbXAAUBlTGVgZ9SF0ZfVhbQBhAOSgswM6FgCghipyImV2ZQAfYQABaXliGWUZcgBjAB1hM2RvAHQAIWGAoWUibHFzAMYEcBl6GfGhZSLOBAAAdhlsAGEAbgD0AN8EgKF+KmNkbACBGYQZjBljAACgqSpvAHQAb6CAKmyggioAoIQqZeDbIgD+cwAAoJQqcgAA4DXYJN3noGsirATtIWVsAKA3IWMAeQBTZIChdyJFYWoApxmpGasZAKCSKgCgpSoAoKQqAAJFYWVztBm2Gb0ZwhkAoGkicABwoIoq8iFveACgiipxoIgq8aCIKrUZaQBtAACg5yJwAGYAAOA12FjdYQB2AOUAYwIAAWNp0xnWGXIAAKAKIW0AAKFzImVs3BneGQCgjioAoJAqAIM+ADtjZGxxco0E6xn0GfgZ/BkBGgABY2nvGfEZAKCnKnIAAKB6Km8AdAAAoNci0CFhcgCglSl1ImVzdAAAoHwqgAJhZGVscwAKGvQZFhrVBCAa8AEPGgAAFBpwAHIAbwD4AFkZcgAAoHgpcQAAAWxxxAQbGmwAZQBzAPMASRlpAO0A5AQAAWVuJxouGnIjdG5lcXEAAOBpIgD+xQAsGgAFQWFiY2Vma29zeUAaQxpmGmoabRqDGocalhrCGtMacgDyAMwCAAJpbG1yShpOGlAaVBpyAHMA8ABxD2YAvWBpAGwA9AASBQABZHJYGlsaYwB5AEpkAKGUIWN3YBpkGmkAcgAAoEgpAKCtIWEAcgAAoA8h6SFyYyVhgAFhbHIAcxp7Gn8a8iF0c3WgZSZpAHQAAKBlJuwhaXAAoCYg4yFvbgCguSJyAADgNdgl3XMAAAFld4wakRphInJvdwAAoCUpYSJyb3cAAKAmKYACYW1vcHIAnxqjGqcauhq+GnIAcgAAoP8h9CFodACgOyJrAAABbHKsGrMaZSRmdGFycm93AACgqSHpJGdodGFycm93AKCqIWYAAOA12Fnd4iFhcgCgFSCAAWNsdADIGswa0BpyAADgNdi93GEAcwDoAGka8iFvaydhAAFicNca2xr1IWxsAKBDIOghZW4AoBAg4Qr2GgAA/RoAAAgbExsaGwAAIRs7GwAAAAA+G2IbmRuVG6sbAACyG80b0htjAHUAdABlADuA7QDtQAChYyBpeQEbBhtyAGMAO4DuAO5AOGQAAWN4CxsNG3kANWRjAGwAO4ChAKFAAAFmcssCFhsA4DXYJt1yAGEAdgBlADuA7ADsQIChSCFpbm8AJxsyGzYbAAFpbisbLxtuAHQAAKAMKnQAAKAtIuYhaW4AoNwpdABhAACgKSHsIWlnM2GAAWFvcABDG1sbXhuAAWNndABJG0sbWRtyACthgAFlbHAAcQVRG1UbaQBuAOUAyAVhAHIA9AByBWgAMWFmAACgtyJlAGQAtWEAoggiY2ZvdGkbbRt1G3kb4SFyZQCgBSFpAG4AdKAeImkAZQAAoN0pZABvAPQAWxsAoisiY2VscIEbhRuPG5QbYQBsAACguiIAAWdyiRuNG2UAcgDzACMQ4wCCG2EicmhrAACgFyryIW9kAKA8KgACY2dwdJ8boRukG6gbeQBRZG8AbgAvYWYAAOA12FrdYQC5Y3UAZQBzAHQAO4C/AL9AAAFjabUbuRtyAADgNdi+3G4AAKIIIkVkc3bCG8QbyBvQAwCg+SJvAHQAAKD1Inag9CIAoPMiaaBiIOwhZGUpYesB1hsAANkbYwB5AFZkbAA7gO8A70AAA2NmbW9zdeYb7hvyG/Ub+hsFHAABaXnqG+0bcgBjADVhOWRyAADgNdgn3eEhdGg3YnAAZgAA4DXYW93jAf8bAAADHHIAAOA12L/c8iFjeVhk6yFjeVRkAARhY2ZnaGpvcxUcGhwiHCYcKhwtHDAcNRzwIXBhdqC6A/BjAAFleR4cIRzkIWlsN2E6ZHIAAOA12CjdciJlZW4AOGFjAHkARWRjAHkAXGRwAGYAAOA12FzdYwByAADgNdjA3IALQUJFSGFiY2RlZmdoamxtbm9wcnN0dXYAXhxtHHEcdRx5HN8cBx0dHTwd3B3tHfEdAR4EHh0eLB5FHrwewx7hHgkfPR9LH4ABYXJ0AGQcZxxpHHIA8gBvB/IAxQLhIWlsAKAbKeEhcnIAoA4pZ6BmIgCgiyphAHIAAKBiKWMJjRwAAJAcAACVHAAAAAAAAAAAAACZHJwcAACmHKgcrRwAANIc9SF0ZTph7SJwdHl2AKC0KXIAYQDuAFoG4iFkYbtjZwAAoegnZGyhHKMcAKCRKeUAiwYAoIUqdQBvADuAqwCrQHIAgKOQIWJmaGxwc3QAuhy/HMIcxBzHHMoczhxmoOQhcwAAoB8pcwAAoB0p6wCyGnAAAKCrIWwAAKA5KWkAbQAAoHMpbAAAoKIhAKGrKmFl1hzaHGkAbAAAoBkpc6CtKgDgrSoA/oABYWJyAOUc6RztHHIAcgAAoAwpcgBrAACgcicAAWFr8Rz4HGMAAAFla/Yc9xx7YFtgAAFlc/wc/hwAoIspbAAAAWR1Ax0FHQCgjykAoI0pAAJhZXV5Dh0RHRodHB3yIW9uPmEAAWRpFR0YHWkAbAA8YewAowbiAPccO2QAAmNxcnMkHScdLB05HWEAAKA2KXUAbwDyoBwgqhEAAWR1MB00HeghYXIAoGcpcyJoYXIAAKBLKWgAAKCyIQCiZCJmZ3FzRB1FB5Qdnh10AIACYWhscnQATh1WHWUdbB2NHXIicm93AHSgkCFhAOkAzxxhI3Jwb29uAAABZHVeHWId7yF3bgCgvSFwAACgvCHlJGZ0YXJyb3dzAKDHIWkiZ2h0AIABYWhzAHUdex2DHXIicm93APOglCGdBmEAcgBwAG8AbwBuAPMAzgtxAHUAaQBnAGEAcgByAG8A9wBlGugkcmVldGltZXMAoMsi8aFkIk0HAACaHWwAYQBuAPQAXgcAon0qY2Rnc6YdqR2xHbcdYwAAoKgqbwB0AG+gfypyoIEqAKCDKmXg2iIA/nMAAKCTKoACYWRlZ3MAwB3GHcod1h3ZHXAAcAByAG8A+ACmHG8AdAAAoNYicQAAAWdxzx3SHXQA8gBGB2cAdADyAHQcdADyAFMHaQDtAGMHgAFpbHIA4h3mHeod8yFodACgfClvAG8A8gDKBgDgNdgp3UWgdiIAoJEqYQH1Hf4dcgAAAWR1YB35HWygvCEAoGopbABrAACghCVjAHkAWWQAomoiYWNodAweDx4VHhkecgDyAGsdbwByAG4AZQDyAGAW4SFyZACgaylyAGkAAKD6JQABaW8hHiQe5CFvdEBh9SFzdGGgsCPjIWhlAKCwIwACRWFlczMeNR48HkEeAKBoInAAcKCJKvIhb3gAoIkqcaCHKvGghyo0HmkAbQAAoOYiAARhYm5vcHR3elIeXB5fHoUelh6mHqsetB4AAW5yVh5ZHmcAAKDsJ3IAAKD9IXIA6wCwBmcAgAFsbXIAZh52Hnse5SFmdAABYXKIB2weaQBnAGgAdABhAHIAcgBvAPcAkwfhInBzdG8AoPwnaQBnAGgAdABhAHIAcgBvAPcAmgdwI2Fycm93AAABbHKNHpEeZQBmAPQAxhxpImdodAAAoKwhgAFhZmwAnB6fHqIecgAAoIUpAOA12F3ddQBzAACgLSppIm1lcwAAoDQqYQGvHrMecwB0AACgFyLhAIoOZaHKJbkeRhLuIWdlAKDKJWEAcgBsoCgAdAAAoJMpgAJhY2htdADMHs8e1R7bHt0ecgDyAJ0GbwByAG4AZQDyANYWYQByAGSgyyEAoG0pAKAOIHIAaQAAoL8iAANhY2hpcXTrHu8e1QfzHv0eBh/xIXVvAKA5IHIAAOA12MHcbQDloXIi+h4AAPweAKCNKgCgjyoAAWJ19xwBH28AcqAYIACgGiDyIW9rQmEAhDwAO2NkaGlscXJCBhcfxh0gHyQfKB8sHzEfAAFjaRsfHR8AoKYqcgAAoHkqcgBlAOUAkx3tIWVzAKDJIuEhcnIAoHYpdSJlc3QAAKB7KgABUGk1HzkfYQByAACglillocMlAgdfEnIAAAFkdUIfRx9zImhhcgAAoEop6CFhcgCgZikAAWVuTx9WH3IjdG5lcXEAAOBoIgD+xQBUHwAHRGFjZGVmaGlsbm9wc3VuH3Ifoh+rH68ftx+7H74f5h/uH/MfBwj/HwsgxCFvdACgOiIAAmNscHJ5H30fiR+eH3IAO4CvAK9AAAFldIEfgx8AoEImZaAgJ3MAZQAAoCAnc6CmIXQAbwCAoaYhZGx1AJQfmB+cH28AdwDuAHkDZQBmAPQA6gbwAOkO6yFlcgCgriUAAW95ph+qH+0hbWEAoCkqPGThIXNoAKAUIOElc3VyZWRhbmdsZQCgISJyAADgNdgq3W8AAKAnIYABY2RuAMQfyR/bH3IAbwA7gLUAtUBhoiMi0B8AANMf1x9zAPQAKxFpAHIAAKDwKm8AdAA7gLcAt0B1AHMA4qESIh4TAADjH3WgOCIAoCoqYwHqH+0fcAAAoNsq8gB+GnAAbAB1APMACAgAAWRw9x/7H+UhbHMAoKciZgAA4DXYXt0AAWN0AyAHIHIAAOA12MLc8CFvcwCgPiJsobwDECAVIPQiaW1hcACguCJhAPAAEyAADEdMUlZhYmNkZWZnaGlqbG1vcHJzdHV2dzwgRyBmIG0geSCqILgg2iDeIBEhFSEyIUMhTSFQIZwhnyHSIQAiIyKLIrEivyIUIwABZ3RAIEMgAODZIjgD9uBrItIgBwmAAWVsdABNIF8gYiBmAHQAAAFhclMgWCByInJvdwAAoM0h6SRnaHRhcnJvdwCgziEA4NgiOAP24Goi0iBfCekkZ2h0YXJyb3cAoM8hAAFEZHEgdSDhIXNoAKCvIuEhc2gAoK4igAJiY25wdACCIIYgiSCNIKIgbABhAACgByL1IXRlRGFnAADgICLSIACiSSJFaW9wlSCYIJwgniAA4HAqOANkAADgSyI4A3MASWFyAG8A+AAyCnUAcgBhoG4mbADzoG4mmwjzAa8gAACzIHAAO4CgAKBAbQBwAOXgTiI4AyoJgAJhZW91eQDBIMogzSDWINkg8AHGIAAAyCAAoEMqbwBuAEhh5CFpbEZhbgBnAGSgRyJvAHQAAOBtKjgDcAAAoEIqPWThIXNoAKATIACjYCJBYWRxc3jpIO0g+SD+IAIhDCFyAHIAAKDXIXIAAAFocvIg9SBrAACgJClvoJch9wAGD28AdAAA4FAiOAN1AGkA9gC7CAABZWkGIQohYQByAACgKCntAN8I6SFzdPOgBCLlCHIAAOA12CvdAAJFZXN0/wgcISshLiHxoXEiIiEAABMJ8aFxIgAJAAAnIWwAYQBuAPQAEwlpAO0AGQlyoG8iAKBvIoABQWFwADghOyE/IXIA8gBeIHIAcgAAoK4hYQByAACg8ipzogsiSiEAAAAAxwtkoPwiAKD6ImMAeQBaZIADQUVhZGVzdABcIV8hYiFmIWkhkyGWIXIA8gBXIADgZiI4A3IAcgAAoJohcgAAoCUggKFwImZxcwBwIYQhjiF0AAABYXJ1IXohcgByAG8A9wBlIWkAZwBoAHQAYQByAHIAbwD3AD4h8aFwImAhAACKIWwAYQBuAPQAZwlz4H0qOAMAoG4iaQDtAG0JcqBuImkA5aDqIkUJaQDkADoKAAFwdKMhpyFmAADgNdhf3YCBrAA7aW4AriGvIcchrEBuAIChCSJFZHYAtyG6Ib8hAOD5IjgDbwB0AADg9SI4A+EB1gjEIcYhAKD3IgCg9iJpAHagDCLhAagJzyHRIQCg/iIAoP0igAFhb3IA2CHsIfEhcgCAoSYiYXN0AOAh5SHpIWwAbABlAOwAywhsAADg/SrlIADgAiI4A2wiaW50AACgFCrjoYAi9yEAAPohdQDlAJsJY+CvKjgDZaCAIvEAkwkAAkFhaXQHIgoiFyIeInIA8gBsIHIAcgAAoZshY3cRIhQiAOAzKTgDAOCdITgDZyRodGFycm93AACgmyFyAGkA5aDrIr4JgANjaGltcHF1AC8iPCJHIpwhTSJQIloigKGBImNlcgA2Iv0JOSJ1AOUABgoA4DXYw9zvIXJ0bQKdIQAAAABEImEAcgDhAOEhbQBloEEi8aBEIiYKYQDyAMsIcwB1AAABYnBWIlgi5QDUCeUA3wmAAWJjcABgInMieCKAoYQiRWVzAGci7glqIgDgxSo4A2UAdABl4IIi0iBxAPGgiCJoImMAZaCBIvEA/gmAoYUiRWVzAH8iFgqCIgDgxio4A2UAdABl4IMi0iBxAPGgiSKAIgACZ2lscpIilCKaIpwi7AAMCWwAZABlADuA8QDxQOcAWwlpI2FuZ2xlAAABbHKkIqoi5SFmdGWg6iLxAEUJaSJnaHQAZaDrIvEAvgltoL0DAKEjAGVzuCK8InIAbwAAoBYhcAAAoAcggARESGFkZ2lscnMAziLSItYi2iLeIugi7SICIw8j4SFzaACgrSLhIXJyAKAEKXAAAOBNItIg4SFzaACgrCIAAWV04iLlIgDgZSLSIADgPgDSIG4iZmluAACg3imAAUFldADzIvci+iJyAHIAAKACKQDgZCLSIHLgPADSIGkAZQAA4LQi0iAAAUF0BiMKI3IAcgAAoAMp8iFpZQDgtSLSIGkAbQAA4Dwi0iCAAUFhbgAaIx4jKiNyAHIAAKDWIXIAAAFociMjJiNrAACgIylvoJYh9wD/DuUhYXIAoCcpUxJqFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVCMAAF4jaSN/I4IjjSOeI8AUAAAAAKYjwCMAANoj3yMAAO8jHiQvJD8kRCQAAWNzVyNsFHUAdABlADuA8wDzQAABaXlhI2cjcgBjoJoiO4D0APRAPmSAAmFiaW9zAHEjdCN3I3EBeiNzAOgAdhTsIWFjUWF2AACgOCrvIWxkAKC8KewhaWdTYQABY3KFI4kjaQByAACgvykA4DXYLN1vA5QjAAAAAJYjAACcI24A22JhAHYAZQA7gPIA8kAAoMEpAAFibaEjjAphAHIAAKC1KQACYWNpdKwjryO6I70jcgDyAFkUAAFpcrMjtiNyAACgvinvIXNzAKC7KW4A5QDZCgCgwCmAAWFlaQDFI8gjyyNjAHIATWFnAGEAyWOAAWNkbgDRI9Qj1iPyIW9uv2MAoLYpdQDzAHgBcABmAADgNdhg3YABYWVsAOQj5yPrI3IAAKC3KXIAcAAAoLkpdQDzAHwBAKMoImFkaW9zdvkj/CMPJBMkFiQbJHIA8gBeFIChXSplZm0AAyQJJAwkcgBvoDQhZgAAoDQhO4CqAKpAO4C6ALpA5yFvZgCgtiJyAACgVipsIm9wZQAAoFcqAKBbKoABY2xvACMkJSQrJPIACCRhAHMAaAA7gPgA+EBsAACgmCJpAGwBMyQ4JGQAZQA7gPUA9UBlAHMAYaCXInMAAKA2Km0AbAA7gPYA9kDiIWFyAKA9I+EKXiQAAHokAAB8JJQkAACYJKkkAAAAALUkEQsAAPAkAAAAAAQleiUAAIMlcgCAoSUiYXN0AGUkbyQBCwCBtgA7bGokayS2QGwAZQDsABgDaQJ1JAAAAAB4JG0AAKDzKgCg/Sp5AD9kcgCAAmNpbXB0AIUkiCSLJJkSjyRuAHQAJWBvAGQALmBpAGwAAKAwIOUhbmsAoDEgcgAA4DXYLd2AAWltbwCdJKAkpCR2oMYD1WNtAGEA9AD+B24AZQAAoA4m9KHAA64kAAC0JGMjaGZvcmsAAKDUItZjAAFhdbgkxCRuAAABY2u9JMIkawBooA8hAKAOIfYAaRpzAACkKwBhYmNkZW1zdNMkIRPXJNsk4STjJOck6yTjIWlyAKAjKmkAcgAAoCIqAAFvdYsW3yQAoCUqAKByKm4AO4CxALFAaQBtAACgJip3AG8AAKAnKoABaXB1APUk+iT+JO4idGludACgFSpmAADgNdhh3W4AZAA7gKMAo0CApHoiRWFjZWlub3N1ABMlFSUYJRslTCVRJVklSSV1JQCgsypwAACgtyp1AOUAPwtjoK8qgKJ6ImFjZW5zACclLSU0JTYlSSVwAHAAcgBvAPgAFyV1AHIAbAB5AGUA8QA/C/EAOAuAAWFlcwA8JUElRSXwInByb3gAoLkqcQBxAACgtSppAG0AAKDoImkA7QBEC20AZQDzoDIgIguAAUVhcwBDJVclRSXwAEAlgAFkZnAATwtfJXElgAFhbHMAZSVpJW0l7CFhcgCgLiPpIW5lAKASI/UhcmYAoBMjdKAdIu8AWQvyIWVsAKCwIgABY2l9JYElcgAA4DXYxdzIY24iY3NwAACgCCAAA2Zpb3BzdZElKxuVJZolnyWkJXIAAOA12C7dcABmAADgNdhi3XIiaW1lAACgVyBjAHIAAOA12MbcgAFhZW8AqiW6JcAldAAAAWVpryW2JXIAbgBpAG8AbgDzABkFbgB0AACgFipzAHQAZaA/APEACRj0AG0LgApBQkhhYmNkZWZoaWxtbm9wcnN0dXgA4yXyJfYl+iVpJpAmpia9JtUm5ib4JlonaCdxJ3UnnietJ7EnyCfiJ+cngAFhcnQA6SXsJe4lcgDyAJkM8gD6AuEhaWwAoBwpYQByAPIA3BVhAHIAAKBkKYADY2RlbnFydAAGJhAmEyYYJiYmKyZaJgABZXUKJg0mAOA9IjEDdABlAFVhaQDjACAN7SJwdHl2AKCzKWcAgKHpJ2RlbAAgJiImJCYAoJIpAKClKeUA9wt1AG8AO4C7ALtAcgAApZIhYWJjZmhscHN0dz0mQCZFJkcmSiZMJk4mUSZVJlgmcAAAoHUpZqDlIXMAAKAgKQCgMylzAACgHinrALka8ACVHmwAAKBFKWkAbQAAoHQpbAAAoKMhAKCdIQABYWleJmImaQBsAACgGilvAG6gNiJhAGwA8wB2C4ABYWJyAG8mciZ2JnIA8gAvEnIAawAAoHMnAAFha3omgSZjAAABZWt/JoAmfWBdYAABZXOFJocmAKCMKWwAAAFkdYwmjiYAoI4pAKCQKQACYWV1eZcmmiajJqUm8iFvbllhAAFkaZ4moSZpAGwAV2HsAA8M4gCAJkBkAAJjbHFzrSawJrUmuiZhAACgNylkImhhcgAAoGkpdQBvAPKgHSCjAWgAAKCzIYABYWNnAMMm0iaUC2wAgKEcIWlwcwDLJs4migxuAOUAoAxhAHIA9ADaC3QAAKCtJYABaWxyANsm3ybjJvMhaHQAoH0pbwBvAPIANgwA4DXYL90AAWFv6ib1JnIAAAFkde8m8SYAoMEhbKDAIQCgbCl2oMED8WOAAWducwD+Jk4nUCdoAHQAAANhaGxyc3QKJxInISc1Jz0nRydyInJvdwB0oJIhYQDpAFYmYSNycG9vbgAAAWR1GiceJ28AdwDuAPAmcAAAoMAh5SFmdAABYWgnJy0ncgByAG8AdwDzAAkMYQByAHAAbwBvAG4A8wATBGklZ2h0YXJyb3dzAACgySFxAHUAaQBnAGEAcgByAG8A9wBZJugkcmVldGltZXMAoMwiZwDaYmkAbgBnAGQAbwB0AHMAZQDxABwYgAFhaG0AYCdjJ2YncgDyAAkMYQDyABMEAKAPIG8idXN0AGGgsSPjIWhlAKCxI+0haWQAoO4qAAJhYnB0fCeGJ4knmScAAW5ygCeDJ2cAAKDtJ3IAAKD+IXIA6wAcDIABYWZsAI8nkieVJ3IAAKCGKQDgNdhj3XUAcwAAoC4qaSJtZXMAAKA1KgABYXCiJ6gncgBnoCkAdAAAoJQp7yJsaW50AKASKmEAcgDyADwnAAJhY2hxuCe8J6EMwCfxIXVvAKA6IHIAAOA12MfcAAFidYAmxCdvAPKgGSCoAYABaGlyAM4n0ifWJ3IAZQDlAE0n7SFlcwCgyiJpAIChuSVlZmwAXAxjEt4n9CFyaQCgzinsInVoYXIAoGgpAKAeIWENBSgJKA0oSyhVKIYoAACLKLAoAAAAAOMo5ygAABApJCkxKW0pcSmHKaYpAACYKgAAAACxKmMidXRlAFthcQB1AO8ABR+ApHsiRWFjZWlucHN5ABwoHignKCooLygyKEEoRihJKACgtCrwASMoAAAlKACguCpvAG4AYWF1AOUAgw1koLAqaQBsAF9hcgBjAF1hgAFFYXMAOCg6KD0oAKC2KnAAAKC6KmkAbQAAoOki7yJsaW50AKATKmkA7QCIDUFkbwB0AGKixSKRFgAAAABTKACgZiqAA0FhY21zdHgAYChkKG8ocyh1KHkogihyAHIAAKDYIXIAAAFocmkoayjrAJAab6CYIfcAzAd0ADuApwCnQGkAO2D3IWFyAKApKW0AAAFpbn4ozQBuAHUA8wDOAHQAAKA2J3IA7+A12DDdIxkAAmFjb3mRKJUonSisKHIAcAAAoG8mAAFoeZkonChjAHkASWRIZHIAdABtAqUoAAAAAKgoaQDkAFsPYQByAGEA7ABsJDuArQCtQAABZ22zKLsobQBhAAChwwNmdroouijCY4CjPCJkZWdsbnByAMgozCjPKNMo1yjaKN4obwB0AACgairxoEMiCw5FoJ4qAKCgKkWgnSoAoJ8qZQAAoEYi7CF1cwCgJCrhIXJyAKByKWEAcgDyAPwMAAJhZWl07Sj8KAEpCCkAAWxz8Sj4KGwAcwBlAHQAbQDpAH8oaABwAACgMyrwImFyc2wAoOQpAAFkbFoPBSllAACgIyNloKoqc6CsKgDgrCoA/oABZmxwABUpGCkfKfQhY3lMZGKgLwBhoMQpcgAAoD8jZgAA4DXYZN1hAAABZHIoKRcDZQBzAHWgYCZpAHQAAKBgJoABY3N1ADYpRilhKQABYXU6KUApcABzoJMiAOCTIgD+cABzoJQiAOCUIgD+dQAAAWJwSylWKQChjyJlcz4NUCllAHQAZaCPIvEAPw0AoZAiZXNIDVspZQB0AGWgkCLxAEkNAKGhJWFmZilbBHIAZQFrKVwEAKChJWEAcgDyAAMNAAJjZW10dyl7KX8pgilyAADgNdjI3HQAbQDuAM4AaQDsAAYpYQByAOYAVw0AAWFyiimOKXIA5qAGJhESAAFhbpIpoylpImdodAAAAWVwmSmgKXAAcwBpAGwAbwDuANkXaADpAKAkcwCvYIACYmNtbnAArin8KY4NJSooKgCkgiJFZGVtbnByc7wpvinCKcgpzCnUKdgp3CkAoMUqbwB0AACgvSpkoIYibwB0AACgwyr1IWx0AKDBKgABRWXQKdIpAKDLKgCgiiLsIXVzAKC/KuEhcnIAoHkpgAFlaXUA4inxKfQpdAAAoYIiZW7oKewpcQDxoIYivSllAHEA8aCKItEpbQAAoMcqAAFicPgp+ikAoNUqAKDTKmMAgKJ7ImFjZW5zAAcqDSoUKhYqRihwAHAAcgBvAPgAIyh1AHIAbAB5AGUA8QCDDfEAfA2AAWFlcwAcKiIqPShwAHAAcgBvAPgAPChxAPEAOShnAACgaiYApoMiMTIzRWRlaGxtbnBzPCo/KkIqRSpHKlIqWCpjKmcqaypzKncqO4C5ALlAO4CyALJAO4CzALNAAKDGKgABb3NLKk4qdAAAoL4qdQBiAACg2CpkoIcibwB0AACgxCpzAAABb3VdKmAqbAAAoMknYgAAoNcq4SFycgCgeyn1IWx0AKDCKgABRWVvKnEqAKDMKgCgiyLsIXVzAKDAKoABZWl1AH0qjCqPKnQAAKGDImVugyqHKnEA8aCHIkYqZQBxAPGgiyJwKm0AAKDIKgABYnCTKpUqAKDUKgCg1iqAAUFhbgCdKqEqrCpyAHIAAKDZIXIAAAFocqYqqCrrAJUab6CZIfcAxQf3IWFyAKAqKWwAaQBnADuA3wDfQOELzyrZKtwq6SrsKvEqAAD1KjQrAAAAAAAAAAAAAEwrbCsAAHErvSsAAAAAAADRK3IC1CoAAAAA2CrnIWV0AKAWI8RjcgDrAOUKgAFhZXkA4SrkKucq8iFvbmVh5CFpbGNhQmRvAPQAIg5sInJlYwAAoBUjcgAA4DXYMd0AAmVpa2/7KhIrKCsuK/IBACsAAAkrZQAAATRm6g0EK28AcgDlAOsNYQBzorgDECsAAAAAEit5AG0A0WMAAWNuFislK2sAAAFhcxsrIStwAHAAcgBvAPgAFw5pAG0AAKA8InMA8AD9DQABYXMsKyEr8AAXDnIAbgA7gP4A/kDsATgrOyswG2QA5QBnAmUAcwCAgdcAO2JkAEMrRCtJK9dAYaCgInIAAKAxKgCgMCqAAWVwcwBRK1MraSvhAAkh4qKkIlsrXysAAAAAYytvAHQAAKA2I2kAcgAAoPEqb+A12GXdcgBrAACg2irhAHgociJpbWUAAKA0IIABYWlwAHYreSu3K2QA5QC+DYADYWRlbXBzdACFK6MrmiunK6wrsCuzK24iZ2xlAACitSVkbHFykCuUK5ornCvvIXduAKC/JeUhZnRloMMl8QACBwCgXCJpImdodABloLkl8QBdDG8AdAAAoOwlaSJudXMAAKA6KuwhdXMAoDkqYgAAoM0p6SFtZQCgOyrlInppdW0AoOIjgAFjaHQAwivKK80rAAFyecYrySsA4DXYydxGZGMAeQBbZPIhb2tnYQABaW/UK9creAD0ANERaCJlYWQAAAFsct4r5ytlAGYAdABhAHIAcgBvAPcAXQbpJGdodGFycm93AKCgIQAJQUhhYmNkZmdobG1vcHJzdHV3CiwNLBEsHSwnLDEsQCxLLFIsYix6LIQsjyzLLOgs7Sz/LAotcgDyAAkDYQByAACgYykAAWNyFSwbLHUAdABlADuA+gD6QPIACQ1yAOMBIywAACUseQBeZHYAZQBtYQABaXkrLDAscgBjADuA+wD7QENkgAFhYmgANyw6LD0scgDyANEO7CFhY3FhYQDyAOAOAAFpckQsSCzzIWh0AKB+KQDgNdgy3XIAYQB2AGUAO4D5APlAYQFWLF8scgAAAWxyWixcLACgvyEAoL4hbABrAACggCUAAWN0Zix2LG8CbCwAAAAAcyxyAG4AZaAcI3IAAKAcI28AcAAAoA8jcgBpAACg+CUAAWFsfiyBLGMAcgBrYTuAqACoQAABZ3CILIssbwBuAHNhZgAA4DXYZt0AA2FkaGxzdZksniynLLgsuyzFLHIAcgBvAPcACQ1vAHcAbgBhAHIAcgBvAPcA2A5hI3Jwb29uAAABbHKvLLMsZQBmAPQAWyxpAGcAaAD0AF0sdQDzAKYOaQAAocUDaGzBLMIs0mNvAG4AxWPwI2Fycm93cwCgyCGAAWNpdADRLOEs5CxvAtcsAAAAAN4scgBuAGWgHSNyAACgHSNvAHAAAKAOI24AZwBvYXIAaQAAoPklYwByAADgNdjK3IABZGlyAPMs9yz6LG8AdAAAoPAi7CFkZWlhaQBmoLUlAKC0JQABYW0DLQYtcgDyAMosbAA7gPwA/EDhIm5nbGUAoKcpgAdBQkRhY2RlZmxub3Byc3oAJy0qLTAtNC2bLZ0toS2/LcMtxy3TLdgt3C3gLfwtcgDyABADYQByAHag6CoAoOkqYQBzAOgA/gIAAW5yOC08LechcnQAoJwpgANla25wcnN0AJkpSC1NLVQtXi1iLYItYQBwAHAA4QAaHG8AdABoAGkAbgDnAKEXgAFoaXIAoSmzJFotbwBwAPQAdCVooJUh7wD4JgABaXVmLWotZwBtAOEAuygAAWJwbi14LXMjZXRuZXEAceCKIgD+AODLKgD+cyNldG5lcQBx4IsiAP4A4MwqAP4AAWhyhi2KLWUAdADhABIraSNhbmdsZQAAAWxyki2WLeUhZnQAoLIiaSJnaHQAAKCzInkAMmThIXNoAKCiIoABZWxyAKcttC24LWKiKCKuLQAAAACyLWEAcgAAoLsicQAAoFoi7CFpcACg7iIAAWJ0vC1eD2EA8gBfD3IAAOA12DPddAByAOkAlS1zAHUAAAFicM0t0C0A4IIi0iAA4IMi0iBwAGYAAOA12GfdcgBvAPAAWQt0AHIA6QCaLQABY3XkLegtcgAA4DXYy9wAAWJw7C30LW4AAAFFZXUt8S0A4IoiAP5uAAABRWV/LfktAOCLIgD+6SJnemFnAKCaKYADY2Vmb3BycwANLhAuJS4pLiMuLi40LukhcmN1YQABZGkULiEuAAFiZxguHC5hAHIAAKBfKmUAcaAnIgCgWSLlIXJwAKAYIXIAAOA12DTdcABmAADgNdho3WWgQCJhAHQA6ABqD2MAcgAA4DXYzNzjCuQRUC4AAFQuAABYLmIuAAAAAGMubS5wLnQuAAAAAIguki4AAJouJxIqEnQAcgDpAB0ScgAA4DXYNd0AAUFhWy5eLnIA8gDnAnIA8gCTB75jAAFBYWYuaS5yAPIA4AJyAPIAjAdhAPAAeh5pAHMAAKD7IoABZHB0APgReS6DLgABZmx9LoAuAOA12GnddQDzAP8RaQBtAOUABBIAAUFhiy6OLnIA8gDuAnIA8gCaBwABY3GVLgoScgAA4DXYzdwAAXB0nS6hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");
  2500. /**
  2501. * Bit flags & masks for the binary trie encoding used for entity decoding.
  2502. *
  2503. * Bit layout (16 bits total):
  2504. * 15..14 VALUE_LENGTH (+1 encoding; 0 => no value)
  2505. * 13 FLAG13. If valueLength>0: semicolon required flag (implicit ';').
  2506. * If valueLength==0: compact run flag.
  2507. * 12..7 BRANCH_LENGTH Branch length (0 => single branch in 6..0 if jumpOffset==char) OR run length (when compact run)
  2508. * 6..0 JUMP_TABLE Jump offset (jump table) OR single-branch char code OR first run char
  2509. */
  2510. var BinTrieFlags;
  2511. (function (BinTrieFlags) {
  2512. BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
  2513. BinTrieFlags[BinTrieFlags["FLAG13"] = 8192] = "FLAG13";
  2514. BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 8064] = "BRANCH_LENGTH";
  2515. BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE";
  2516. })(BinTrieFlags || (BinTrieFlags = {}));
  2517. var CharCodes;
  2518. (function (CharCodes) {
  2519. CharCodes[CharCodes["NUM"] = 35] = "NUM";
  2520. CharCodes[CharCodes["SEMI"] = 59] = "SEMI";
  2521. CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS";
  2522. CharCodes[CharCodes["ZERO"] = 48] = "ZERO";
  2523. CharCodes[CharCodes["NINE"] = 57] = "NINE";
  2524. CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A";
  2525. CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F";
  2526. CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X";
  2527. CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z";
  2528. CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A";
  2529. CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F";
  2530. CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z";
  2531. })(CharCodes || (CharCodes = {}));
  2532. /** Bit that needs to be set to convert an upper case ASCII character to lower case */
  2533. const TO_LOWER_BIT = 32;
  2534. function isNumber$1(code) {
  2535. return code >= CharCodes.ZERO && code <= CharCodes.NINE;
  2536. }
  2537. function isHexadecimalCharacter(code) {
  2538. return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) ||
  2539. (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F));
  2540. }
  2541. function isAsciiAlphaNumeric(code) {
  2542. return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) ||
  2543. (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) ||
  2544. isNumber$1(code));
  2545. }
  2546. /**
  2547. * Checks if the given character is a valid end character for an entity in an attribute.
  2548. *
  2549. * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.
  2550. * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
  2551. */
  2552. function isEntityInAttributeInvalidEnd(code) {
  2553. return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code);
  2554. }
  2555. var EntityDecoderState;
  2556. (function (EntityDecoderState) {
  2557. EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart";
  2558. EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart";
  2559. EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal";
  2560. EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex";
  2561. EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity";
  2562. })(EntityDecoderState || (EntityDecoderState = {}));
  2563. var DecodingMode;
  2564. (function (DecodingMode) {
  2565. /** Entities in text nodes that can end with any character. */
  2566. DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy";
  2567. /** Only allow entities terminated with a semicolon. */
  2568. DecodingMode[DecodingMode["Strict"] = 1] = "Strict";
  2569. /** Entities in attributes have limitations on ending characters. */
  2570. DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute";
  2571. })(DecodingMode || (DecodingMode = {}));
  2572. /**
  2573. * Token decoder with support of writing partial entities.
  2574. */
  2575. class EntityDecoder {
  2576. constructor(
  2577. /** The tree used to decode entities. */
  2578. // biome-ignore lint/correctness/noUnusedPrivateClassMembers: False positive
  2579. decodeTree,
  2580. /**
  2581. * The function that is called when a codepoint is decoded.
  2582. *
  2583. * For multi-byte named entities, this will be called multiple times,
  2584. * with the second codepoint, and the same `consumed` value.
  2585. *
  2586. * @param codepoint The decoded codepoint.
  2587. * @param consumed The number of bytes consumed by the decoder.
  2588. */
  2589. emitCodePoint,
  2590. /** An object that is used to produce errors. */
  2591. errors) {
  2592. this.decodeTree = decodeTree;
  2593. this.emitCodePoint = emitCodePoint;
  2594. this.errors = errors;
  2595. /** The current state of the decoder. */
  2596. this.state = EntityDecoderState.EntityStart;
  2597. /** Characters that were consumed while parsing an entity. */
  2598. this.consumed = 1;
  2599. /**
  2600. * The result of the entity.
  2601. *
  2602. * Either the result index of a numeric entity, or the codepoint of a
  2603. * numeric entity.
  2604. */
  2605. this.result = 0;
  2606. /** The current index in the decode tree. */
  2607. this.treeIndex = 0;
  2608. /** The number of characters that were consumed in excess. */
  2609. this.excess = 1;
  2610. /** The mode in which the decoder is operating. */
  2611. this.decodeMode = DecodingMode.Strict;
  2612. /** The number of characters that have been consumed in the current run. */
  2613. this.runConsumed = 0;
  2614. }
  2615. /** Resets the instance to make it reusable. */
  2616. startEntity(decodeMode) {
  2617. this.decodeMode = decodeMode;
  2618. this.state = EntityDecoderState.EntityStart;
  2619. this.result = 0;
  2620. this.treeIndex = 0;
  2621. this.excess = 1;
  2622. this.consumed = 1;
  2623. this.runConsumed = 0;
  2624. }
  2625. /**
  2626. * Write an entity to the decoder. This can be called multiple times with partial entities.
  2627. * If the entity is incomplete, the decoder will return -1.
  2628. *
  2629. * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
  2630. * entity is incomplete, and resume when the next string is written.
  2631. *
  2632. * @param input The string containing the entity (or a continuation of the entity).
  2633. * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
  2634. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2635. */
  2636. write(input, offset) {
  2637. switch (this.state) {
  2638. case EntityDecoderState.EntityStart: {
  2639. if (input.charCodeAt(offset) === CharCodes.NUM) {
  2640. this.state = EntityDecoderState.NumericStart;
  2641. this.consumed += 1;
  2642. return this.stateNumericStart(input, offset + 1);
  2643. }
  2644. this.state = EntityDecoderState.NamedEntity;
  2645. return this.stateNamedEntity(input, offset);
  2646. }
  2647. case EntityDecoderState.NumericStart: {
  2648. return this.stateNumericStart(input, offset);
  2649. }
  2650. case EntityDecoderState.NumericDecimal: {
  2651. return this.stateNumericDecimal(input, offset);
  2652. }
  2653. case EntityDecoderState.NumericHex: {
  2654. return this.stateNumericHex(input, offset);
  2655. }
  2656. case EntityDecoderState.NamedEntity: {
  2657. return this.stateNamedEntity(input, offset);
  2658. }
  2659. }
  2660. }
  2661. /**
  2662. * Switches between the numeric decimal and hexadecimal states.
  2663. *
  2664. * Equivalent to the `Numeric character reference state` in the HTML spec.
  2665. *
  2666. * @param input The string containing the entity (or a continuation of the entity).
  2667. * @param offset The current offset.
  2668. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2669. */
  2670. stateNumericStart(input, offset) {
  2671. if (offset >= input.length) {
  2672. return -1;
  2673. }
  2674. if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
  2675. this.state = EntityDecoderState.NumericHex;
  2676. this.consumed += 1;
  2677. return this.stateNumericHex(input, offset + 1);
  2678. }
  2679. this.state = EntityDecoderState.NumericDecimal;
  2680. return this.stateNumericDecimal(input, offset);
  2681. }
  2682. /**
  2683. * Parses a hexadecimal numeric entity.
  2684. *
  2685. * Equivalent to the `Hexademical character reference state` in the HTML spec.
  2686. *
  2687. * @param input The string containing the entity (or a continuation of the entity).
  2688. * @param offset The current offset.
  2689. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2690. */
  2691. stateNumericHex(input, offset) {
  2692. while (offset < input.length) {
  2693. const char = input.charCodeAt(offset);
  2694. if (isNumber$1(char) || isHexadecimalCharacter(char)) {
  2695. // Convert hex digit to value (0-15); 'a'/'A' -> 10.
  2696. const digit = char <= CharCodes.NINE
  2697. ? char - CharCodes.ZERO
  2698. : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10;
  2699. this.result = this.result * 16 + digit;
  2700. this.consumed++;
  2701. offset++;
  2702. }
  2703. else {
  2704. return this.emitNumericEntity(char, 3);
  2705. }
  2706. }
  2707. return -1; // Incomplete entity
  2708. }
  2709. /**
  2710. * Parses a decimal numeric entity.
  2711. *
  2712. * Equivalent to the `Decimal character reference state` in the HTML spec.
  2713. *
  2714. * @param input The string containing the entity (or a continuation of the entity).
  2715. * @param offset The current offset.
  2716. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2717. */
  2718. stateNumericDecimal(input, offset) {
  2719. while (offset < input.length) {
  2720. const char = input.charCodeAt(offset);
  2721. if (isNumber$1(char)) {
  2722. this.result = this.result * 10 + (char - CharCodes.ZERO);
  2723. this.consumed++;
  2724. offset++;
  2725. }
  2726. else {
  2727. return this.emitNumericEntity(char, 2);
  2728. }
  2729. }
  2730. return -1; // Incomplete entity
  2731. }
  2732. /**
  2733. * Validate and emit a numeric entity.
  2734. *
  2735. * Implements the logic from the `Hexademical character reference start
  2736. * state` and `Numeric character reference end state` in the HTML spec.
  2737. *
  2738. * @param lastCp The last code point of the entity. Used to see if the
  2739. * entity was terminated with a semicolon.
  2740. * @param expectedLength The minimum number of characters that should be
  2741. * consumed. Used to validate that at least one digit
  2742. * was consumed.
  2743. * @returns The number of characters that were consumed.
  2744. */
  2745. emitNumericEntity(lastCp, expectedLength) {
  2746. var _a;
  2747. // Ensure we consumed at least one digit.
  2748. if (this.consumed <= expectedLength) {
  2749. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
  2750. return 0;
  2751. }
  2752. // Figure out if this is a legit end of the entity
  2753. if (lastCp === CharCodes.SEMI) {
  2754. this.consumed += 1;
  2755. }
  2756. else if (this.decodeMode === DecodingMode.Strict) {
  2757. return 0;
  2758. }
  2759. this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
  2760. if (this.errors) {
  2761. if (lastCp !== CharCodes.SEMI) {
  2762. this.errors.missingSemicolonAfterCharacterReference();
  2763. }
  2764. this.errors.validateNumericCharacterReference(this.result);
  2765. }
  2766. return this.consumed;
  2767. }
  2768. /**
  2769. * Parses a named entity.
  2770. *
  2771. * Equivalent to the `Named character reference state` in the HTML spec.
  2772. *
  2773. * @param input The string containing the entity (or a continuation of the entity).
  2774. * @param offset The current offset.
  2775. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2776. */
  2777. stateNamedEntity(input, offset) {
  2778. const { decodeTree } = this;
  2779. let current = decodeTree[this.treeIndex];
  2780. // The length is the number of bytes of the value, including the current byte.
  2781. let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  2782. while (offset < input.length) {
  2783. // Handle compact runs (possibly inline): valueLength == 0 and SEMI_REQUIRED bit set.
  2784. if (valueLength === 0 && (current & BinTrieFlags.FLAG13) !== 0) {
  2785. const runLength = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; /* 2..63 */
  2786. // If we are starting a run, check the first char.
  2787. if (this.runConsumed === 0) {
  2788. const firstChar = current & BinTrieFlags.JUMP_TABLE;
  2789. if (input.charCodeAt(offset) !== firstChar) {
  2790. return this.result === 0
  2791. ? 0
  2792. : this.emitNotTerminatedNamedEntity();
  2793. }
  2794. offset++;
  2795. this.excess++;
  2796. this.runConsumed++;
  2797. }
  2798. // Check remaining characters in the run.
  2799. while (this.runConsumed < runLength) {
  2800. if (offset >= input.length) {
  2801. return -1;
  2802. }
  2803. const charIndexInPacked = this.runConsumed - 1;
  2804. const packedWord = decodeTree[this.treeIndex + 1 + (charIndexInPacked >> 1)];
  2805. const expectedChar = charIndexInPacked % 2 === 0
  2806. ? packedWord & 0xff
  2807. : (packedWord >> 8) & 0xff;
  2808. if (input.charCodeAt(offset) !== expectedChar) {
  2809. this.runConsumed = 0;
  2810. return this.result === 0
  2811. ? 0
  2812. : this.emitNotTerminatedNamedEntity();
  2813. }
  2814. offset++;
  2815. this.excess++;
  2816. this.runConsumed++;
  2817. }
  2818. this.runConsumed = 0;
  2819. this.treeIndex += 1 + (runLength >> 1);
  2820. current = decodeTree[this.treeIndex];
  2821. valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  2822. }
  2823. if (offset >= input.length)
  2824. break;
  2825. const char = input.charCodeAt(offset);
  2826. /*
  2827. * Implicit semicolon handling for nodes that require a semicolon but
  2828. * don't have an explicit ';' branch stored in the trie. If we have
  2829. * a value on the current node, it requires a semicolon, and the
  2830. * current input character is a semicolon, emit the entity using the
  2831. * current node (without descending further).
  2832. */
  2833. if (char === CharCodes.SEMI &&
  2834. valueLength !== 0 &&
  2835. (current & BinTrieFlags.FLAG13) !== 0) {
  2836. return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
  2837. }
  2838. this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
  2839. if (this.treeIndex < 0) {
  2840. return this.result === 0 ||
  2841. // If we are parsing an attribute
  2842. (this.decodeMode === DecodingMode.Attribute &&
  2843. // We shouldn't have consumed any characters after the entity,
  2844. (valueLength === 0 ||
  2845. // And there should be no invalid characters.
  2846. isEntityInAttributeInvalidEnd(char)))
  2847. ? 0
  2848. : this.emitNotTerminatedNamedEntity();
  2849. }
  2850. current = decodeTree[this.treeIndex];
  2851. valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  2852. // If the branch is a value, store it and continue
  2853. if (valueLength !== 0) {
  2854. // If the entity is terminated by a semicolon, we are done.
  2855. if (char === CharCodes.SEMI) {
  2856. return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
  2857. }
  2858. // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it.
  2859. if (this.decodeMode !== DecodingMode.Strict &&
  2860. (current & BinTrieFlags.FLAG13) === 0) {
  2861. this.result = this.treeIndex;
  2862. this.consumed += this.excess;
  2863. this.excess = 0;
  2864. }
  2865. }
  2866. // Increment offset & excess for next iteration
  2867. offset++;
  2868. this.excess++;
  2869. }
  2870. return -1;
  2871. }
  2872. /**
  2873. * Emit a named entity that was not terminated with a semicolon.
  2874. *
  2875. * @returns The number of characters consumed.
  2876. */
  2877. emitNotTerminatedNamedEntity() {
  2878. var _a;
  2879. const { result, decodeTree } = this;
  2880. const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
  2881. this.emitNamedEntityData(result, valueLength, this.consumed);
  2882. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference();
  2883. return this.consumed;
  2884. }
  2885. /**
  2886. * Emit a named entity.
  2887. *
  2888. * @param result The index of the entity in the decode tree.
  2889. * @param valueLength The number of bytes in the entity.
  2890. * @param consumed The number of characters consumed.
  2891. *
  2892. * @returns The number of characters consumed.
  2893. */
  2894. emitNamedEntityData(result, valueLength, consumed) {
  2895. const { decodeTree } = this;
  2896. this.emitCodePoint(valueLength === 1
  2897. ? decodeTree[result] &
  2898. ~(BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)
  2899. : decodeTree[result + 1], consumed);
  2900. if (valueLength === 3) {
  2901. // For multi-byte values, we need to emit the second byte.
  2902. this.emitCodePoint(decodeTree[result + 2], consumed);
  2903. }
  2904. return consumed;
  2905. }
  2906. /**
  2907. * Signal to the parser that the end of the input was reached.
  2908. *
  2909. * Remaining data will be emitted and relevant errors will be produced.
  2910. *
  2911. * @returns The number of characters consumed.
  2912. */
  2913. end() {
  2914. var _a;
  2915. switch (this.state) {
  2916. case EntityDecoderState.NamedEntity: {
  2917. // Emit a named entity if we have one.
  2918. return this.result !== 0 &&
  2919. (this.decodeMode !== DecodingMode.Attribute ||
  2920. this.result === this.treeIndex)
  2921. ? this.emitNotTerminatedNamedEntity()
  2922. : 0;
  2923. }
  2924. // Otherwise, emit a numeric entity if we have one.
  2925. case EntityDecoderState.NumericDecimal: {
  2926. return this.emitNumericEntity(0, 2);
  2927. }
  2928. case EntityDecoderState.NumericHex: {
  2929. return this.emitNumericEntity(0, 3);
  2930. }
  2931. case EntityDecoderState.NumericStart: {
  2932. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
  2933. return 0;
  2934. }
  2935. case EntityDecoderState.EntityStart: {
  2936. // Return 0 if we have no entity.
  2937. return 0;
  2938. }
  2939. }
  2940. }
  2941. }
  2942. /**
  2943. * Creates a function that decodes entities in a string.
  2944. *
  2945. * @param decodeTree The decode tree.
  2946. * @returns A function that decodes entities in a string.
  2947. */
  2948. function getDecoder(decodeTree) {
  2949. let returnValue = "";
  2950. const decoder = new EntityDecoder(decodeTree, (data) => (returnValue += fromCodePoint(data)));
  2951. return function decodeWithTrie(input, decodeMode) {
  2952. let lastIndex = 0;
  2953. let offset = 0;
  2954. while ((offset = input.indexOf("&", offset)) >= 0) {
  2955. returnValue += input.slice(lastIndex, offset);
  2956. decoder.startEntity(decodeMode);
  2957. const length = decoder.write(input,
  2958. // Skip the "&"
  2959. offset + 1);
  2960. if (length < 0) {
  2961. lastIndex = offset + decoder.end();
  2962. break;
  2963. }
  2964. lastIndex = offset + length;
  2965. // If `length` is 0, skip the current `&` and continue.
  2966. offset = length === 0 ? lastIndex + 1 : lastIndex;
  2967. }
  2968. const result = returnValue + input.slice(lastIndex);
  2969. // Make sure we don't keep a reference to the final string.
  2970. returnValue = "";
  2971. return result;
  2972. };
  2973. }
  2974. /**
  2975. * Determines the branch of the current node that is taken given the current
  2976. * character. This function is used to traverse the trie.
  2977. *
  2978. * @param decodeTree The trie.
  2979. * @param current The current node.
  2980. * @param nodeIdx The index right after the current node and its value.
  2981. * @param char The current character.
  2982. * @returns The index of the next node, or -1 if no branch is taken.
  2983. */
  2984. function determineBranch(decodeTree, current, nodeIndex, char) {
  2985. const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
  2986. const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
  2987. // Case 1: Single branch encoded in jump offset
  2988. if (branchCount === 0) {
  2989. return jumpOffset !== 0 && char === jumpOffset ? nodeIndex : -1;
  2990. }
  2991. // Case 2: Multiple branches encoded in jump table
  2992. if (jumpOffset) {
  2993. const value = char - jumpOffset;
  2994. return value < 0 || value >= branchCount
  2995. ? -1
  2996. : decodeTree[nodeIndex + value] - 1;
  2997. }
  2998. // Case 3: Multiple branches encoded in packed dictionary (two keys per uint16)
  2999. const packedKeySlots = (branchCount + 1) >> 1;
  3000. /*
  3001. * Treat packed keys as a virtual sorted array of length `branchCount`.
  3002. * Key(i) = low byte for even i, high byte for odd i in slot i>>1.
  3003. */
  3004. let lo = 0;
  3005. let hi = branchCount - 1;
  3006. while (lo <= hi) {
  3007. const mid = (lo + hi) >>> 1;
  3008. const slot = mid >> 1;
  3009. const packed = decodeTree[nodeIndex + slot];
  3010. const midKey = (packed >> ((mid & 1) * 8)) & 0xff;
  3011. if (midKey < char) {
  3012. lo = mid + 1;
  3013. }
  3014. else if (midKey > char) {
  3015. hi = mid - 1;
  3016. }
  3017. else {
  3018. return decodeTree[nodeIndex + packedKeySlots + mid];
  3019. }
  3020. }
  3021. return -1;
  3022. }
  3023. const htmlDecoder = /* #__PURE__ */ getDecoder(htmlDecodeTree);
  3024. /**
  3025. * Decodes an HTML string.
  3026. *
  3027. * @param htmlString The string to decode.
  3028. * @param mode The decoding mode.
  3029. * @returns The decoded string.
  3030. */
  3031. function decodeHTML(htmlString, mode = DecodingMode.Legacy) {
  3032. return htmlDecoder(htmlString, mode);
  3033. }
  3034. const defaultDelimitersOpen = new Uint8Array([123, 123]);
  3035. const defaultDelimitersClose = new Uint8Array([125, 125]);
  3036. function isTagStartChar(c) {
  3037. return c >= 97 && c <= 122 || c >= 65 && c <= 90;
  3038. }
  3039. function isWhitespace(c) {
  3040. return c === 32 || c === 10 || c === 9 || c === 12 || c === 13;
  3041. }
  3042. function isEndOfTagSection(c) {
  3043. return c === 47 || c === 62 || isWhitespace(c);
  3044. }
  3045. function toCharCodes(str) {
  3046. const ret = new Uint8Array(str.length);
  3047. for (let i = 0; i < str.length; i++) {
  3048. ret[i] = str.charCodeAt(i);
  3049. }
  3050. return ret;
  3051. }
  3052. const Sequences = {
  3053. Cdata: new Uint8Array([67, 68, 65, 84, 65, 91]),
  3054. // CDATA[
  3055. CdataEnd: new Uint8Array([93, 93, 62]),
  3056. // ]]>
  3057. CommentEnd: new Uint8Array([45, 45, 62]),
  3058. // `-->`
  3059. ScriptEnd: new Uint8Array([60, 47, 115, 99, 114, 105, 112, 116]),
  3060. // `<\/script`
  3061. StyleEnd: new Uint8Array([60, 47, 115, 116, 121, 108, 101]),
  3062. // `</style`
  3063. TitleEnd: new Uint8Array([60, 47, 116, 105, 116, 108, 101]),
  3064. // `</title`
  3065. TextareaEnd: new Uint8Array([
  3066. 60,
  3067. 47,
  3068. 116,
  3069. 101,
  3070. 120,
  3071. 116,
  3072. 97,
  3073. 114,
  3074. 101,
  3075. 97
  3076. ])
  3077. // `</textarea
  3078. };
  3079. class Tokenizer {
  3080. constructor(stack, cbs) {
  3081. this.stack = stack;
  3082. this.cbs = cbs;
  3083. /** The current state the tokenizer is in. */
  3084. this.state = 1;
  3085. /** The read buffer. */
  3086. this.buffer = "";
  3087. /** The beginning of the section that is currently being read. */
  3088. this.sectionStart = 0;
  3089. /** The index within the buffer that we are currently looking at. */
  3090. this.index = 0;
  3091. /** The start of the last entity. */
  3092. this.entityStart = 0;
  3093. /** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */
  3094. this.baseState = 1;
  3095. /** For special parsing behavior inside of script and style tags. */
  3096. this.inRCDATA = false;
  3097. /** For disabling RCDATA tags handling */
  3098. this.inXML = false;
  3099. /** For disabling interpolation parsing in v-pre */
  3100. this.inVPre = false;
  3101. /** Record newline positions for fast line / column calculation */
  3102. this.newlines = [];
  3103. this.mode = 0;
  3104. this.delimiterOpen = defaultDelimitersOpen;
  3105. this.delimiterClose = defaultDelimitersClose;
  3106. this.delimiterIndex = -1;
  3107. this.currentSequence = void 0;
  3108. this.sequenceIndex = 0;
  3109. {
  3110. this.entityDecoder = new EntityDecoder(
  3111. htmlDecodeTree,
  3112. (cp, consumed) => this.emitCodePoint(cp, consumed)
  3113. );
  3114. }
  3115. }
  3116. get inSFCRoot() {
  3117. return this.mode === 2 && this.stack.length === 0;
  3118. }
  3119. reset() {
  3120. this.state = 1;
  3121. this.mode = 0;
  3122. this.buffer = "";
  3123. this.sectionStart = 0;
  3124. this.index = 0;
  3125. this.baseState = 1;
  3126. this.inRCDATA = false;
  3127. this.currentSequence = void 0;
  3128. this.newlines.length = 0;
  3129. this.delimiterOpen = defaultDelimitersOpen;
  3130. this.delimiterClose = defaultDelimitersClose;
  3131. }
  3132. /**
  3133. * Generate Position object with line / column information using recorded
  3134. * newline positions. We know the index is always going to be an already
  3135. * processed index, so all the newlines up to this index should have been
  3136. * recorded.
  3137. */
  3138. getPos(index) {
  3139. let line = 1;
  3140. let column = index + 1;
  3141. const length = this.newlines.length;
  3142. let j = -1;
  3143. if (length > 100) {
  3144. let l = -1;
  3145. let r = length;
  3146. while (l + 1 < r) {
  3147. const m = l + r >>> 1;
  3148. this.newlines[m] < index ? l = m : r = m;
  3149. }
  3150. j = l;
  3151. } else {
  3152. for (let i = length - 1; i >= 0; i--) {
  3153. if (index > this.newlines[i]) {
  3154. j = i;
  3155. break;
  3156. }
  3157. }
  3158. }
  3159. if (j >= 0) {
  3160. line = j + 2;
  3161. column = index - this.newlines[j];
  3162. }
  3163. return {
  3164. column,
  3165. line,
  3166. offset: index
  3167. };
  3168. }
  3169. peek() {
  3170. return this.buffer.charCodeAt(this.index + 1);
  3171. }
  3172. stateText(c) {
  3173. if (c === 60) {
  3174. if (this.index > this.sectionStart) {
  3175. this.cbs.ontext(this.sectionStart, this.index);
  3176. }
  3177. this.state = 5;
  3178. this.sectionStart = this.index;
  3179. } else if (c === 38) {
  3180. this.startEntity();
  3181. } else if (!this.inVPre && c === this.delimiterOpen[0]) {
  3182. this.state = 2;
  3183. this.delimiterIndex = 0;
  3184. this.stateInterpolationOpen(c);
  3185. }
  3186. }
  3187. stateInterpolationOpen(c) {
  3188. if (c === this.delimiterOpen[this.delimiterIndex]) {
  3189. if (this.delimiterIndex === this.delimiterOpen.length - 1) {
  3190. const start = this.index + 1 - this.delimiterOpen.length;
  3191. if (start > this.sectionStart) {
  3192. this.cbs.ontext(this.sectionStart, start);
  3193. }
  3194. this.state = 3;
  3195. this.sectionStart = start;
  3196. } else {
  3197. this.delimiterIndex++;
  3198. }
  3199. } else if (this.inRCDATA) {
  3200. this.state = 32;
  3201. this.stateInRCDATA(c);
  3202. } else {
  3203. this.state = 1;
  3204. this.stateText(c);
  3205. }
  3206. }
  3207. stateInterpolation(c) {
  3208. if (c === this.delimiterClose[0]) {
  3209. this.state = 4;
  3210. this.delimiterIndex = 0;
  3211. this.stateInterpolationClose(c);
  3212. }
  3213. }
  3214. stateInterpolationClose(c) {
  3215. if (c === this.delimiterClose[this.delimiterIndex]) {
  3216. if (this.delimiterIndex === this.delimiterClose.length - 1) {
  3217. this.cbs.oninterpolation(this.sectionStart, this.index + 1);
  3218. if (this.inRCDATA) {
  3219. this.state = 32;
  3220. } else {
  3221. this.state = 1;
  3222. }
  3223. this.sectionStart = this.index + 1;
  3224. } else {
  3225. this.delimiterIndex++;
  3226. }
  3227. } else {
  3228. this.state = 3;
  3229. this.stateInterpolation(c);
  3230. }
  3231. }
  3232. stateSpecialStartSequence(c) {
  3233. const isEnd = this.sequenceIndex === this.currentSequence.length;
  3234. const isMatch = isEnd ? (
  3235. // If we are at the end of the sequence, make sure the tag name has ended
  3236. isEndOfTagSection(c)
  3237. ) : (
  3238. // Otherwise, do a case-insensitive comparison
  3239. (c | 32) === this.currentSequence[this.sequenceIndex]
  3240. );
  3241. if (!isMatch) {
  3242. this.inRCDATA = false;
  3243. } else if (!isEnd) {
  3244. this.sequenceIndex++;
  3245. return;
  3246. }
  3247. this.sequenceIndex = 0;
  3248. this.state = 6;
  3249. this.stateInTagName(c);
  3250. }
  3251. /** Look for an end tag. For <title> and <textarea>, also decode entities. */
  3252. stateInRCDATA(c) {
  3253. if (this.sequenceIndex === this.currentSequence.length) {
  3254. if (c === 62 || isWhitespace(c)) {
  3255. const endOfText = this.index - this.currentSequence.length;
  3256. if (this.sectionStart < endOfText) {
  3257. const actualIndex = this.index;
  3258. this.index = endOfText;
  3259. this.cbs.ontext(this.sectionStart, endOfText);
  3260. this.index = actualIndex;
  3261. }
  3262. this.sectionStart = endOfText + 2;
  3263. this.stateInClosingTagName(c);
  3264. this.inRCDATA = false;
  3265. return;
  3266. }
  3267. this.sequenceIndex = 0;
  3268. }
  3269. if ((c | 32) === this.currentSequence[this.sequenceIndex]) {
  3270. this.sequenceIndex += 1;
  3271. } else if (this.sequenceIndex === 0) {
  3272. if (this.currentSequence === Sequences.TitleEnd || this.currentSequence === Sequences.TextareaEnd && !this.inSFCRoot) {
  3273. if (c === 38) {
  3274. this.startEntity();
  3275. } else if (!this.inVPre && c === this.delimiterOpen[0]) {
  3276. this.state = 2;
  3277. this.delimiterIndex = 0;
  3278. this.stateInterpolationOpen(c);
  3279. }
  3280. } else if (this.fastForwardTo(60)) {
  3281. this.sequenceIndex = 1;
  3282. }
  3283. } else {
  3284. this.sequenceIndex = Number(c === 60);
  3285. }
  3286. }
  3287. stateCDATASequence(c) {
  3288. if (c === Sequences.Cdata[this.sequenceIndex]) {
  3289. if (++this.sequenceIndex === Sequences.Cdata.length) {
  3290. this.state = 28;
  3291. this.currentSequence = Sequences.CdataEnd;
  3292. this.sequenceIndex = 0;
  3293. this.sectionStart = this.index + 1;
  3294. }
  3295. } else {
  3296. this.sequenceIndex = 0;
  3297. this.state = 23;
  3298. this.stateInDeclaration(c);
  3299. }
  3300. }
  3301. /**
  3302. * When we wait for one specific character, we can speed things up
  3303. * by skipping through the buffer until we find it.
  3304. *
  3305. * @returns Whether the character was found.
  3306. */
  3307. fastForwardTo(c) {
  3308. while (++this.index < this.buffer.length) {
  3309. const cc = this.buffer.charCodeAt(this.index);
  3310. if (cc === 10) {
  3311. this.newlines.push(this.index);
  3312. }
  3313. if (cc === c) {
  3314. return true;
  3315. }
  3316. }
  3317. this.index = this.buffer.length - 1;
  3318. return false;
  3319. }
  3320. /**
  3321. * Comments and CDATA end with `-->` and `]]>`.
  3322. *
  3323. * Their common qualities are:
  3324. * - Their end sequences have a distinct character they start with.
  3325. * - That character is then repeated, so we have to check multiple repeats.
  3326. * - All characters but the start character of the sequence can be skipped.
  3327. */
  3328. stateInCommentLike(c) {
  3329. if (c === this.currentSequence[this.sequenceIndex]) {
  3330. if (++this.sequenceIndex === this.currentSequence.length) {
  3331. if (this.currentSequence === Sequences.CdataEnd) {
  3332. this.cbs.oncdata(this.sectionStart, this.index - 2);
  3333. } else {
  3334. this.cbs.oncomment(this.sectionStart, this.index - 2);
  3335. }
  3336. this.sequenceIndex = 0;
  3337. this.sectionStart = this.index + 1;
  3338. this.state = 1;
  3339. }
  3340. } else if (this.sequenceIndex === 0) {
  3341. if (this.fastForwardTo(this.currentSequence[0])) {
  3342. this.sequenceIndex = 1;
  3343. }
  3344. } else if (c !== this.currentSequence[this.sequenceIndex - 1]) {
  3345. this.sequenceIndex = 0;
  3346. }
  3347. }
  3348. startSpecial(sequence, offset) {
  3349. this.enterRCDATA(sequence, offset);
  3350. this.state = 31;
  3351. }
  3352. enterRCDATA(sequence, offset) {
  3353. this.inRCDATA = true;
  3354. this.currentSequence = sequence;
  3355. this.sequenceIndex = offset;
  3356. }
  3357. stateBeforeTagName(c) {
  3358. if (c === 33) {
  3359. this.state = 22;
  3360. this.sectionStart = this.index + 1;
  3361. } else if (c === 63) {
  3362. this.state = 24;
  3363. this.sectionStart = this.index + 1;
  3364. } else if (isTagStartChar(c)) {
  3365. this.sectionStart = this.index;
  3366. if (this.mode === 0) {
  3367. this.state = 6;
  3368. } else if (this.inSFCRoot) {
  3369. this.state = 34;
  3370. } else if (!this.inXML) {
  3371. if (c === 116) {
  3372. this.state = 30;
  3373. } else {
  3374. this.state = c === 115 ? 29 : 6;
  3375. }
  3376. } else {
  3377. this.state = 6;
  3378. }
  3379. } else if (c === 47) {
  3380. this.state = 8;
  3381. } else {
  3382. this.state = 1;
  3383. this.stateText(c);
  3384. }
  3385. }
  3386. stateInTagName(c) {
  3387. if (isEndOfTagSection(c)) {
  3388. this.handleTagName(c);
  3389. }
  3390. }
  3391. stateInSFCRootTagName(c) {
  3392. if (isEndOfTagSection(c)) {
  3393. const tag = this.buffer.slice(this.sectionStart, this.index);
  3394. if (tag !== "template") {
  3395. this.enterRCDATA(toCharCodes(`</` + tag), 0);
  3396. }
  3397. this.handleTagName(c);
  3398. }
  3399. }
  3400. handleTagName(c) {
  3401. this.cbs.onopentagname(this.sectionStart, this.index);
  3402. this.sectionStart = -1;
  3403. this.state = 11;
  3404. this.stateBeforeAttrName(c);
  3405. }
  3406. stateBeforeClosingTagName(c) {
  3407. if (isWhitespace(c)) ; else if (c === 62) {
  3408. {
  3409. this.cbs.onerr(14, this.index);
  3410. }
  3411. this.state = 1;
  3412. this.sectionStart = this.index + 1;
  3413. } else {
  3414. this.state = isTagStartChar(c) ? 9 : 27;
  3415. this.sectionStart = this.index;
  3416. }
  3417. }
  3418. stateInClosingTagName(c) {
  3419. if (c === 62 || isWhitespace(c)) {
  3420. this.cbs.onclosetag(this.sectionStart, this.index);
  3421. this.sectionStart = -1;
  3422. this.state = 10;
  3423. this.stateAfterClosingTagName(c);
  3424. }
  3425. }
  3426. stateAfterClosingTagName(c) {
  3427. if (c === 62) {
  3428. this.state = 1;
  3429. this.sectionStart = this.index + 1;
  3430. }
  3431. }
  3432. stateBeforeAttrName(c) {
  3433. if (c === 62) {
  3434. this.cbs.onopentagend(this.index);
  3435. if (this.inRCDATA) {
  3436. this.state = 32;
  3437. } else {
  3438. this.state = 1;
  3439. }
  3440. this.sectionStart = this.index + 1;
  3441. } else if (c === 47) {
  3442. this.state = 7;
  3443. if (this.peek() !== 62) {
  3444. this.cbs.onerr(22, this.index);
  3445. }
  3446. } else if (c === 60 && this.peek() === 47) {
  3447. this.cbs.onopentagend(this.index);
  3448. this.state = 5;
  3449. this.sectionStart = this.index;
  3450. } else if (!isWhitespace(c)) {
  3451. if (c === 61) {
  3452. this.cbs.onerr(
  3453. 19,
  3454. this.index
  3455. );
  3456. }
  3457. this.handleAttrStart(c);
  3458. }
  3459. }
  3460. handleAttrStart(c) {
  3461. if (c === 118 && this.peek() === 45) {
  3462. this.state = 13;
  3463. this.sectionStart = this.index;
  3464. } else if (c === 46 || c === 58 || c === 64 || c === 35) {
  3465. this.cbs.ondirname(this.index, this.index + 1);
  3466. this.state = 14;
  3467. this.sectionStart = this.index + 1;
  3468. } else {
  3469. this.state = 12;
  3470. this.sectionStart = this.index;
  3471. }
  3472. }
  3473. stateInSelfClosingTag(c) {
  3474. if (c === 62) {
  3475. this.cbs.onselfclosingtag(this.index);
  3476. this.state = 1;
  3477. this.sectionStart = this.index + 1;
  3478. this.inRCDATA = false;
  3479. } else if (!isWhitespace(c)) {
  3480. this.state = 11;
  3481. this.stateBeforeAttrName(c);
  3482. }
  3483. }
  3484. stateInAttrName(c) {
  3485. if (c === 61 || isEndOfTagSection(c)) {
  3486. this.cbs.onattribname(this.sectionStart, this.index);
  3487. this.handleAttrNameEnd(c);
  3488. } else if (c === 34 || c === 39 || c === 60) {
  3489. this.cbs.onerr(
  3490. 17,
  3491. this.index
  3492. );
  3493. }
  3494. }
  3495. stateInDirName(c) {
  3496. if (c === 61 || isEndOfTagSection(c)) {
  3497. this.cbs.ondirname(this.sectionStart, this.index);
  3498. this.handleAttrNameEnd(c);
  3499. } else if (c === 58) {
  3500. this.cbs.ondirname(this.sectionStart, this.index);
  3501. this.state = 14;
  3502. this.sectionStart = this.index + 1;
  3503. } else if (c === 46) {
  3504. this.cbs.ondirname(this.sectionStart, this.index);
  3505. this.state = 16;
  3506. this.sectionStart = this.index + 1;
  3507. }
  3508. }
  3509. stateInDirArg(c) {
  3510. if (c === 61 || isEndOfTagSection(c)) {
  3511. this.cbs.ondirarg(this.sectionStart, this.index);
  3512. this.handleAttrNameEnd(c);
  3513. } else if (c === 91) {
  3514. this.state = 15;
  3515. } else if (c === 46) {
  3516. this.cbs.ondirarg(this.sectionStart, this.index);
  3517. this.state = 16;
  3518. this.sectionStart = this.index + 1;
  3519. }
  3520. }
  3521. stateInDynamicDirArg(c) {
  3522. if (c === 93) {
  3523. this.state = 14;
  3524. } else if (c === 61 || isEndOfTagSection(c)) {
  3525. this.cbs.ondirarg(this.sectionStart, this.index + 1);
  3526. this.handleAttrNameEnd(c);
  3527. {
  3528. this.cbs.onerr(
  3529. 27,
  3530. this.index
  3531. );
  3532. }
  3533. }
  3534. }
  3535. stateInDirModifier(c) {
  3536. if (c === 61 || isEndOfTagSection(c)) {
  3537. this.cbs.ondirmodifier(this.sectionStart, this.index);
  3538. this.handleAttrNameEnd(c);
  3539. } else if (c === 46) {
  3540. this.cbs.ondirmodifier(this.sectionStart, this.index);
  3541. this.sectionStart = this.index + 1;
  3542. }
  3543. }
  3544. handleAttrNameEnd(c) {
  3545. this.sectionStart = this.index;
  3546. this.state = 17;
  3547. this.cbs.onattribnameend(this.index);
  3548. this.stateAfterAttrName(c);
  3549. }
  3550. stateAfterAttrName(c) {
  3551. if (c === 61) {
  3552. this.state = 18;
  3553. } else if (c === 47 || c === 62) {
  3554. this.cbs.onattribend(0, this.sectionStart);
  3555. this.sectionStart = -1;
  3556. this.state = 11;
  3557. this.stateBeforeAttrName(c);
  3558. } else if (!isWhitespace(c)) {
  3559. this.cbs.onattribend(0, this.sectionStart);
  3560. this.handleAttrStart(c);
  3561. }
  3562. }
  3563. stateBeforeAttrValue(c) {
  3564. if (c === 34) {
  3565. this.state = 19;
  3566. this.sectionStart = this.index + 1;
  3567. } else if (c === 39) {
  3568. this.state = 20;
  3569. this.sectionStart = this.index + 1;
  3570. } else if (!isWhitespace(c)) {
  3571. this.sectionStart = this.index;
  3572. this.state = 21;
  3573. this.stateInAttrValueNoQuotes(c);
  3574. }
  3575. }
  3576. handleInAttrValue(c, quote) {
  3577. if (c === quote || false) {
  3578. this.cbs.onattribdata(this.sectionStart, this.index);
  3579. this.sectionStart = -1;
  3580. this.cbs.onattribend(
  3581. quote === 34 ? 3 : 2,
  3582. this.index + 1
  3583. );
  3584. this.state = 11;
  3585. } else if (c === 38) {
  3586. this.startEntity();
  3587. }
  3588. }
  3589. stateInAttrValueDoubleQuotes(c) {
  3590. this.handleInAttrValue(c, 34);
  3591. }
  3592. stateInAttrValueSingleQuotes(c) {
  3593. this.handleInAttrValue(c, 39);
  3594. }
  3595. stateInAttrValueNoQuotes(c) {
  3596. if (isWhitespace(c) || c === 62) {
  3597. this.cbs.onattribdata(this.sectionStart, this.index);
  3598. this.sectionStart = -1;
  3599. this.cbs.onattribend(1, this.index);
  3600. this.state = 11;
  3601. this.stateBeforeAttrName(c);
  3602. } else if (c === 34 || c === 39 || c === 60 || c === 61 || c === 96) {
  3603. this.cbs.onerr(
  3604. 18,
  3605. this.index
  3606. );
  3607. } else if (c === 38) {
  3608. this.startEntity();
  3609. }
  3610. }
  3611. stateBeforeDeclaration(c) {
  3612. if (c === 91) {
  3613. this.state = 26;
  3614. this.sequenceIndex = 0;
  3615. } else {
  3616. this.state = c === 45 ? 25 : 23;
  3617. }
  3618. }
  3619. stateInDeclaration(c) {
  3620. if (c === 62 || this.fastForwardTo(62)) {
  3621. this.state = 1;
  3622. this.sectionStart = this.index + 1;
  3623. }
  3624. }
  3625. stateInProcessingInstruction(c) {
  3626. if (c === 62 || this.fastForwardTo(62)) {
  3627. this.cbs.onprocessinginstruction(this.sectionStart, this.index);
  3628. this.state = 1;
  3629. this.sectionStart = this.index + 1;
  3630. }
  3631. }
  3632. stateBeforeComment(c) {
  3633. if (c === 45) {
  3634. this.state = 28;
  3635. this.currentSequence = Sequences.CommentEnd;
  3636. this.sequenceIndex = 2;
  3637. this.sectionStart = this.index + 1;
  3638. } else {
  3639. this.state = 23;
  3640. }
  3641. }
  3642. stateInSpecialComment(c) {
  3643. if (c === 62 || this.fastForwardTo(62)) {
  3644. this.cbs.oncomment(this.sectionStart, this.index);
  3645. this.state = 1;
  3646. this.sectionStart = this.index + 1;
  3647. }
  3648. }
  3649. stateBeforeSpecialS(c) {
  3650. if (c === Sequences.ScriptEnd[3]) {
  3651. this.startSpecial(Sequences.ScriptEnd, 4);
  3652. } else if (c === Sequences.StyleEnd[3]) {
  3653. this.startSpecial(Sequences.StyleEnd, 4);
  3654. } else {
  3655. this.state = 6;
  3656. this.stateInTagName(c);
  3657. }
  3658. }
  3659. stateBeforeSpecialT(c) {
  3660. if (c === Sequences.TitleEnd[3]) {
  3661. this.startSpecial(Sequences.TitleEnd, 4);
  3662. } else if (c === Sequences.TextareaEnd[3]) {
  3663. this.startSpecial(Sequences.TextareaEnd, 4);
  3664. } else {
  3665. this.state = 6;
  3666. this.stateInTagName(c);
  3667. }
  3668. }
  3669. startEntity() {
  3670. {
  3671. this.baseState = this.state;
  3672. this.state = 33;
  3673. this.entityStart = this.index;
  3674. this.entityDecoder.startEntity(
  3675. this.baseState === 1 || this.baseState === 32 ? DecodingMode.Legacy : DecodingMode.Attribute
  3676. );
  3677. }
  3678. }
  3679. stateInEntity() {
  3680. {
  3681. const length = this.entityDecoder.write(this.buffer, this.index);
  3682. if (length >= 0) {
  3683. this.state = this.baseState;
  3684. if (length === 0) {
  3685. this.index = this.entityStart;
  3686. }
  3687. } else {
  3688. this.index = this.buffer.length - 1;
  3689. }
  3690. }
  3691. }
  3692. /**
  3693. * Iterates through the buffer, calling the function corresponding to the current state.
  3694. *
  3695. * States that are more likely to be hit are higher up, as a performance improvement.
  3696. */
  3697. parse(input) {
  3698. this.buffer = input;
  3699. while (this.index < this.buffer.length) {
  3700. const c = this.buffer.charCodeAt(this.index);
  3701. if (c === 10 && this.state !== 33) {
  3702. this.newlines.push(this.index);
  3703. }
  3704. switch (this.state) {
  3705. case 1: {
  3706. this.stateText(c);
  3707. break;
  3708. }
  3709. case 2: {
  3710. this.stateInterpolationOpen(c);
  3711. break;
  3712. }
  3713. case 3: {
  3714. this.stateInterpolation(c);
  3715. break;
  3716. }
  3717. case 4: {
  3718. this.stateInterpolationClose(c);
  3719. break;
  3720. }
  3721. case 31: {
  3722. this.stateSpecialStartSequence(c);
  3723. break;
  3724. }
  3725. case 32: {
  3726. this.stateInRCDATA(c);
  3727. break;
  3728. }
  3729. case 26: {
  3730. this.stateCDATASequence(c);
  3731. break;
  3732. }
  3733. case 19: {
  3734. this.stateInAttrValueDoubleQuotes(c);
  3735. break;
  3736. }
  3737. case 12: {
  3738. this.stateInAttrName(c);
  3739. break;
  3740. }
  3741. case 13: {
  3742. this.stateInDirName(c);
  3743. break;
  3744. }
  3745. case 14: {
  3746. this.stateInDirArg(c);
  3747. break;
  3748. }
  3749. case 15: {
  3750. this.stateInDynamicDirArg(c);
  3751. break;
  3752. }
  3753. case 16: {
  3754. this.stateInDirModifier(c);
  3755. break;
  3756. }
  3757. case 28: {
  3758. this.stateInCommentLike(c);
  3759. break;
  3760. }
  3761. case 27: {
  3762. this.stateInSpecialComment(c);
  3763. break;
  3764. }
  3765. case 11: {
  3766. this.stateBeforeAttrName(c);
  3767. break;
  3768. }
  3769. case 6: {
  3770. this.stateInTagName(c);
  3771. break;
  3772. }
  3773. case 34: {
  3774. this.stateInSFCRootTagName(c);
  3775. break;
  3776. }
  3777. case 9: {
  3778. this.stateInClosingTagName(c);
  3779. break;
  3780. }
  3781. case 5: {
  3782. this.stateBeforeTagName(c);
  3783. break;
  3784. }
  3785. case 17: {
  3786. this.stateAfterAttrName(c);
  3787. break;
  3788. }
  3789. case 20: {
  3790. this.stateInAttrValueSingleQuotes(c);
  3791. break;
  3792. }
  3793. case 18: {
  3794. this.stateBeforeAttrValue(c);
  3795. break;
  3796. }
  3797. case 8: {
  3798. this.stateBeforeClosingTagName(c);
  3799. break;
  3800. }
  3801. case 10: {
  3802. this.stateAfterClosingTagName(c);
  3803. break;
  3804. }
  3805. case 29: {
  3806. this.stateBeforeSpecialS(c);
  3807. break;
  3808. }
  3809. case 30: {
  3810. this.stateBeforeSpecialT(c);
  3811. break;
  3812. }
  3813. case 21: {
  3814. this.stateInAttrValueNoQuotes(c);
  3815. break;
  3816. }
  3817. case 7: {
  3818. this.stateInSelfClosingTag(c);
  3819. break;
  3820. }
  3821. case 23: {
  3822. this.stateInDeclaration(c);
  3823. break;
  3824. }
  3825. case 22: {
  3826. this.stateBeforeDeclaration(c);
  3827. break;
  3828. }
  3829. case 25: {
  3830. this.stateBeforeComment(c);
  3831. break;
  3832. }
  3833. case 24: {
  3834. this.stateInProcessingInstruction(c);
  3835. break;
  3836. }
  3837. case 33: {
  3838. this.stateInEntity();
  3839. break;
  3840. }
  3841. }
  3842. this.index++;
  3843. }
  3844. this.cleanup();
  3845. this.finish();
  3846. }
  3847. /**
  3848. * Remove data that has already been consumed from the buffer.
  3849. */
  3850. cleanup() {
  3851. if (this.sectionStart !== this.index) {
  3852. if (this.state === 1 || this.state === 32 && this.sequenceIndex === 0) {
  3853. this.cbs.ontext(this.sectionStart, this.index);
  3854. this.sectionStart = this.index;
  3855. } else if (this.state === 19 || this.state === 20 || this.state === 21) {
  3856. this.cbs.onattribdata(this.sectionStart, this.index);
  3857. this.sectionStart = this.index;
  3858. }
  3859. }
  3860. }
  3861. finish() {
  3862. if (this.state === 33) {
  3863. this.entityDecoder.end();
  3864. this.state = this.baseState;
  3865. }
  3866. this.handleTrailingData();
  3867. this.cbs.onend();
  3868. }
  3869. /** Handle any trailing data. */
  3870. handleTrailingData() {
  3871. const endIndex = this.buffer.length;
  3872. if (this.sectionStart >= endIndex) {
  3873. return;
  3874. }
  3875. if (this.state === 28) {
  3876. if (this.currentSequence === Sequences.CdataEnd) {
  3877. this.cbs.oncdata(this.sectionStart, endIndex);
  3878. } else {
  3879. this.cbs.oncomment(this.sectionStart, endIndex);
  3880. }
  3881. } else if (this.state === 6 || this.state === 11 || this.state === 18 || this.state === 17 || this.state === 12 || this.state === 13 || this.state === 14 || this.state === 15 || this.state === 16 || this.state === 20 || this.state === 19 || this.state === 21 || this.state === 9) ; else {
  3882. this.cbs.ontext(this.sectionStart, endIndex);
  3883. }
  3884. }
  3885. emitCodePoint(cp, consumed) {
  3886. {
  3887. if (this.baseState !== 1 && this.baseState !== 32) {
  3888. if (this.sectionStart < this.entityStart) {
  3889. this.cbs.onattribdata(this.sectionStart, this.entityStart);
  3890. }
  3891. this.sectionStart = this.entityStart + consumed;
  3892. this.index = this.sectionStart - 1;
  3893. this.cbs.onattribentity(
  3894. fromCodePoint(cp),
  3895. this.entityStart,
  3896. this.sectionStart
  3897. );
  3898. } else {
  3899. if (this.sectionStart < this.entityStart) {
  3900. this.cbs.ontext(this.sectionStart, this.entityStart);
  3901. }
  3902. this.sectionStart = this.entityStart + consumed;
  3903. this.index = this.sectionStart - 1;
  3904. this.cbs.ontextentity(
  3905. fromCodePoint(cp),
  3906. this.entityStart,
  3907. this.sectionStart
  3908. );
  3909. }
  3910. }
  3911. }
  3912. }
  3913. const CompilerDeprecationTypes = {
  3914. "COMPILER_IS_ON_ELEMENT": "COMPILER_IS_ON_ELEMENT",
  3915. "COMPILER_V_BIND_SYNC": "COMPILER_V_BIND_SYNC",
  3916. "COMPILER_V_BIND_OBJECT_ORDER": "COMPILER_V_BIND_OBJECT_ORDER",
  3917. "COMPILER_V_ON_NATIVE": "COMPILER_V_ON_NATIVE",
  3918. "COMPILER_V_IF_V_FOR_PRECEDENCE": "COMPILER_V_IF_V_FOR_PRECEDENCE",
  3919. "COMPILER_NATIVE_TEMPLATE": "COMPILER_NATIVE_TEMPLATE",
  3920. "COMPILER_INLINE_TEMPLATE": "COMPILER_INLINE_TEMPLATE",
  3921. "COMPILER_FILTERS": "COMPILER_FILTERS"
  3922. };
  3923. const deprecationData = {
  3924. ["COMPILER_IS_ON_ELEMENT"]: {
  3925. message: `Platform-native elements with "is" prop will no longer be treated as components in Vue 3 unless the "is" value is explicitly prefixed with "vue:".`,
  3926. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  3927. },
  3928. ["COMPILER_V_BIND_SYNC"]: {
  3929. message: (key) => `.sync modifier for v-bind has been removed. Use v-model with argument instead. \`v-bind:${key}.sync\` should be changed to \`v-model:${key}\`.`,
  3930. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  3931. },
  3932. ["COMPILER_V_BIND_OBJECT_ORDER"]: {
  3933. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript object spread: it will now overwrite an existing non-mergeable attribute that appears before v-bind in the case of conflict. To retain 2.x behavior, move v-bind to make it the first attribute. You can also suppress this warning if the usage is intended.`,
  3934. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  3935. },
  3936. ["COMPILER_V_ON_NATIVE"]: {
  3937. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  3938. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  3939. },
  3940. ["COMPILER_V_IF_V_FOR_PRECEDENCE"]: {
  3941. message: `v-if / v-for precedence when used on the same element has changed in Vue 3: v-if now takes higher precedence and will no longer have access to v-for scope variables. It is best to avoid the ambiguity with <template> tags or use a computed property that filters v-for data source.`,
  3942. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  3943. },
  3944. ["COMPILER_NATIVE_TEMPLATE"]: {
  3945. message: `<template> with no special directives will render as a native template element instead of its inner content in Vue 3.`
  3946. },
  3947. ["COMPILER_INLINE_TEMPLATE"]: {
  3948. message: `"inline-template" has been removed in Vue 3.`,
  3949. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  3950. },
  3951. ["COMPILER_FILTERS"]: {
  3952. message: `filters have been removed in Vue 3. The "|" symbol will be treated as native JavaScript bitwise OR operator. Use method calls or computed properties instead.`,
  3953. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  3954. }
  3955. };
  3956. function getCompatValue(key, { compatConfig }) {
  3957. const value = compatConfig && compatConfig[key];
  3958. if (key === "MODE") {
  3959. return value || 3;
  3960. } else {
  3961. return value;
  3962. }
  3963. }
  3964. function isCompatEnabled(key, context) {
  3965. const mode = getCompatValue("MODE", context);
  3966. const value = getCompatValue(key, context);
  3967. return mode === 3 ? value === true : value !== false;
  3968. }
  3969. function checkCompatEnabled(key, context, loc, ...args) {
  3970. const enabled = isCompatEnabled(key, context);
  3971. if (enabled) {
  3972. warnDeprecation(key, context, loc, ...args);
  3973. }
  3974. return enabled;
  3975. }
  3976. function warnDeprecation(key, context, loc, ...args) {
  3977. const val = getCompatValue(key, context);
  3978. if (val === "suppress-warning") {
  3979. return;
  3980. }
  3981. const { message, link } = deprecationData[key];
  3982. const msg = `(deprecation ${key}) ${typeof message === "function" ? message(...args) : message}${link ? `
  3983. Details: ${link}` : ``}`;
  3984. const err = new SyntaxError(msg);
  3985. err.code = key;
  3986. if (loc) err.loc = loc;
  3987. context.onWarn(err);
  3988. }
  3989. function defaultOnError(error) {
  3990. throw error;
  3991. }
  3992. function defaultOnWarn(msg) {
  3993. console.warn(`[Vue warn] ${msg.message}`);
  3994. }
  3995. function createCompilerError(code, loc, messages, additionalMessage) {
  3996. const msg = (messages || errorMessages$1)[code] + (additionalMessage || ``) ;
  3997. const error = new SyntaxError(String(msg));
  3998. error.code = code;
  3999. error.loc = loc;
  4000. return error;
  4001. }
  4002. const ErrorCodes = {
  4003. "ABRUPT_CLOSING_OF_EMPTY_COMMENT": 0,
  4004. "0": "ABRUPT_CLOSING_OF_EMPTY_COMMENT",
  4005. "CDATA_IN_HTML_CONTENT": 1,
  4006. "1": "CDATA_IN_HTML_CONTENT",
  4007. "DUPLICATE_ATTRIBUTE": 2,
  4008. "2": "DUPLICATE_ATTRIBUTE",
  4009. "END_TAG_WITH_ATTRIBUTES": 3,
  4010. "3": "END_TAG_WITH_ATTRIBUTES",
  4011. "END_TAG_WITH_TRAILING_SOLIDUS": 4,
  4012. "4": "END_TAG_WITH_TRAILING_SOLIDUS",
  4013. "EOF_BEFORE_TAG_NAME": 5,
  4014. "5": "EOF_BEFORE_TAG_NAME",
  4015. "EOF_IN_CDATA": 6,
  4016. "6": "EOF_IN_CDATA",
  4017. "EOF_IN_COMMENT": 7,
  4018. "7": "EOF_IN_COMMENT",
  4019. "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT": 8,
  4020. "8": "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT",
  4021. "EOF_IN_TAG": 9,
  4022. "9": "EOF_IN_TAG",
  4023. "INCORRECTLY_CLOSED_COMMENT": 10,
  4024. "10": "INCORRECTLY_CLOSED_COMMENT",
  4025. "INCORRECTLY_OPENED_COMMENT": 11,
  4026. "11": "INCORRECTLY_OPENED_COMMENT",
  4027. "INVALID_FIRST_CHARACTER_OF_TAG_NAME": 12,
  4028. "12": "INVALID_FIRST_CHARACTER_OF_TAG_NAME",
  4029. "MISSING_ATTRIBUTE_VALUE": 13,
  4030. "13": "MISSING_ATTRIBUTE_VALUE",
  4031. "MISSING_END_TAG_NAME": 14,
  4032. "14": "MISSING_END_TAG_NAME",
  4033. "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES": 15,
  4034. "15": "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES",
  4035. "NESTED_COMMENT": 16,
  4036. "16": "NESTED_COMMENT",
  4037. "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME": 17,
  4038. "17": "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME",
  4039. "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE": 18,
  4040. "18": "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE",
  4041. "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME": 19,
  4042. "19": "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME",
  4043. "UNEXPECTED_NULL_CHARACTER": 20,
  4044. "20": "UNEXPECTED_NULL_CHARACTER",
  4045. "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME": 21,
  4046. "21": "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME",
  4047. "UNEXPECTED_SOLIDUS_IN_TAG": 22,
  4048. "22": "UNEXPECTED_SOLIDUS_IN_TAG",
  4049. "X_INVALID_END_TAG": 23,
  4050. "23": "X_INVALID_END_TAG",
  4051. "X_MISSING_END_TAG": 24,
  4052. "24": "X_MISSING_END_TAG",
  4053. "X_MISSING_INTERPOLATION_END": 25,
  4054. "25": "X_MISSING_INTERPOLATION_END",
  4055. "X_MISSING_DIRECTIVE_NAME": 26,
  4056. "26": "X_MISSING_DIRECTIVE_NAME",
  4057. "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END": 27,
  4058. "27": "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END",
  4059. "X_V_IF_NO_EXPRESSION": 28,
  4060. "28": "X_V_IF_NO_EXPRESSION",
  4061. "X_V_IF_SAME_KEY": 29,
  4062. "29": "X_V_IF_SAME_KEY",
  4063. "X_V_ELSE_NO_ADJACENT_IF": 30,
  4064. "30": "X_V_ELSE_NO_ADJACENT_IF",
  4065. "X_V_FOR_NO_EXPRESSION": 31,
  4066. "31": "X_V_FOR_NO_EXPRESSION",
  4067. "X_V_FOR_MALFORMED_EXPRESSION": 32,
  4068. "32": "X_V_FOR_MALFORMED_EXPRESSION",
  4069. "X_V_FOR_TEMPLATE_KEY_PLACEMENT": 33,
  4070. "33": "X_V_FOR_TEMPLATE_KEY_PLACEMENT",
  4071. "X_V_BIND_NO_EXPRESSION": 34,
  4072. "34": "X_V_BIND_NO_EXPRESSION",
  4073. "X_V_ON_NO_EXPRESSION": 35,
  4074. "35": "X_V_ON_NO_EXPRESSION",
  4075. "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET": 36,
  4076. "36": "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET",
  4077. "X_V_SLOT_MIXED_SLOT_USAGE": 37,
  4078. "37": "X_V_SLOT_MIXED_SLOT_USAGE",
  4079. "X_V_SLOT_DUPLICATE_SLOT_NAMES": 38,
  4080. "38": "X_V_SLOT_DUPLICATE_SLOT_NAMES",
  4081. "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN": 39,
  4082. "39": "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN",
  4083. "X_V_SLOT_MISPLACED": 40,
  4084. "40": "X_V_SLOT_MISPLACED",
  4085. "X_V_MODEL_NO_EXPRESSION": 41,
  4086. "41": "X_V_MODEL_NO_EXPRESSION",
  4087. "X_V_MODEL_MALFORMED_EXPRESSION": 42,
  4088. "42": "X_V_MODEL_MALFORMED_EXPRESSION",
  4089. "X_V_MODEL_ON_SCOPE_VARIABLE": 43,
  4090. "43": "X_V_MODEL_ON_SCOPE_VARIABLE",
  4091. "X_V_MODEL_ON_PROPS": 44,
  4092. "44": "X_V_MODEL_ON_PROPS",
  4093. "X_V_MODEL_ON_CONST": 45,
  4094. "45": "X_V_MODEL_ON_CONST",
  4095. "X_INVALID_EXPRESSION": 46,
  4096. "46": "X_INVALID_EXPRESSION",
  4097. "X_KEEP_ALIVE_INVALID_CHILDREN": 47,
  4098. "47": "X_KEEP_ALIVE_INVALID_CHILDREN",
  4099. "X_PREFIX_ID_NOT_SUPPORTED": 48,
  4100. "48": "X_PREFIX_ID_NOT_SUPPORTED",
  4101. "X_MODULE_MODE_NOT_SUPPORTED": 49,
  4102. "49": "X_MODULE_MODE_NOT_SUPPORTED",
  4103. "X_CACHE_HANDLER_NOT_SUPPORTED": 50,
  4104. "50": "X_CACHE_HANDLER_NOT_SUPPORTED",
  4105. "X_SCOPE_ID_NOT_SUPPORTED": 51,
  4106. "51": "X_SCOPE_ID_NOT_SUPPORTED",
  4107. "X_VNODE_HOOKS": 52,
  4108. "52": "X_VNODE_HOOKS",
  4109. "X_V_BIND_INVALID_SAME_NAME_ARGUMENT": 53,
  4110. "53": "X_V_BIND_INVALID_SAME_NAME_ARGUMENT",
  4111. "__EXTEND_POINT__": 54,
  4112. "54": "__EXTEND_POINT__"
  4113. };
  4114. const errorMessages$1 = {
  4115. // parse errors
  4116. [0]: "Illegal comment.",
  4117. [1]: "CDATA section is allowed only in XML context.",
  4118. [2]: "Duplicate attribute.",
  4119. [3]: "End tag cannot have attributes.",
  4120. [4]: "Illegal '/' in tags.",
  4121. [5]: "Unexpected EOF in tag.",
  4122. [6]: "Unexpected EOF in CDATA section.",
  4123. [7]: "Unexpected EOF in comment.",
  4124. [8]: "Unexpected EOF in script.",
  4125. [9]: "Unexpected EOF in tag.",
  4126. [10]: "Incorrectly closed comment.",
  4127. [11]: "Incorrectly opened comment.",
  4128. [12]: "Illegal tag name. Use '&lt;' to print '<'.",
  4129. [13]: "Attribute value was expected.",
  4130. [14]: "End tag name was expected.",
  4131. [15]: "Whitespace was expected.",
  4132. [16]: "Unexpected '<!--' in comment.",
  4133. [17]: `Attribute name cannot contain U+0022 ("), U+0027 ('), and U+003C (<).`,
  4134. [18]: "Unquoted attribute value cannot contain U+0022 (\"), U+0027 ('), U+003C (<), U+003D (=), and U+0060 (`).",
  4135. [19]: "Attribute name cannot start with '='.",
  4136. [21]: "'<?' is allowed only in XML context.",
  4137. [20]: `Unexpected null character.`,
  4138. [22]: "Illegal '/' in tags.",
  4139. // Vue-specific parse errors
  4140. [23]: "Invalid end tag.",
  4141. [24]: "Element is missing end tag.",
  4142. [25]: "Interpolation end sign was not found.",
  4143. [27]: "End bracket for dynamic directive argument was not found. Note that dynamic directive argument cannot contain spaces.",
  4144. [26]: "Legal directive name was expected.",
  4145. // transform errors
  4146. [28]: `v-if/v-else-if is missing expression.`,
  4147. [29]: `v-if/else branches must use unique keys.`,
  4148. [30]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  4149. [31]: `v-for is missing expression.`,
  4150. [32]: `v-for has invalid expression.`,
  4151. [33]: `<template v-for> key should be placed on the <template> tag.`,
  4152. [34]: `v-bind is missing expression.`,
  4153. [53]: `v-bind with same-name shorthand only allows static argument.`,
  4154. [35]: `v-on is missing expression.`,
  4155. [36]: `Unexpected custom directive on <slot> outlet.`,
  4156. [37]: `Mixed v-slot usage on both the component and nested <template>. When there are multiple named slots, all slots should use <template> syntax to avoid scope ambiguity.`,
  4157. [38]: `Duplicate slot names found. `,
  4158. [39]: `Extraneous children found when component already has explicitly named default slot. These children will be ignored.`,
  4159. [40]: `v-slot can only be used on components or <template> tags.`,
  4160. [41]: `v-model is missing expression.`,
  4161. [42]: `v-model value must be a valid JavaScript member expression.`,
  4162. [43]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  4163. [44]: `v-model cannot be used on a prop, because local prop bindings are not writable.
  4164. Use a v-bind binding combined with a v-on listener that emits update:x event instead.`,
  4165. [45]: `v-model cannot be used on a const binding because it is not writable.`,
  4166. [46]: `Error parsing JavaScript expression: `,
  4167. [47]: `<KeepAlive> expects exactly one child component.`,
  4168. [52]: `@vnode-* hooks in templates are no longer supported. Use the vue: prefix instead. For example, @vnode-mounted should be changed to @vue:mounted. @vnode-* hooks support has been removed in 3.4.`,
  4169. // generic errors
  4170. [48]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  4171. [49]: `ES module mode is not supported in this build of compiler.`,
  4172. [50]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  4173. [51]: `"scopeId" option is only supported in module mode.`,
  4174. // just to fulfill types
  4175. [54]: ``
  4176. };
  4177. function getDefaultExportFromCjs (x) {
  4178. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  4179. }
  4180. function getAugmentedNamespace(n) {
  4181. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  4182. var f = n.default;
  4183. if (typeof f == "function") {
  4184. var a = function a () {
  4185. var isInstance = false;
  4186. try {
  4187. isInstance = this instanceof a;
  4188. } catch (e) {}
  4189. if (isInstance) {
  4190. return Reflect.construct(f, arguments, this.constructor);
  4191. }
  4192. return f.apply(this, arguments);
  4193. };
  4194. a.prototype = f.prototype;
  4195. } else a = {};
  4196. Object.defineProperty(a, '__esModule', {value: true});
  4197. Object.keys(n).forEach(function (k) {
  4198. var d = Object.getOwnPropertyDescriptor(n, k);
  4199. Object.defineProperty(a, k, d.get ? d : {
  4200. enumerable: true,
  4201. get: function () {
  4202. return n[k];
  4203. }
  4204. });
  4205. });
  4206. return a;
  4207. }
  4208. var lib = {};
  4209. var hasRequiredLib;
  4210. function requireLib () {
  4211. if (hasRequiredLib) return lib;
  4212. hasRequiredLib = 1;
  4213. Object.defineProperty(lib, '__esModule', {
  4214. value: true
  4215. });
  4216. function _objectWithoutPropertiesLoose(r, e) {
  4217. if (null == r) return {};
  4218. var t = {};
  4219. for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
  4220. if (-1 !== e.indexOf(n)) continue;
  4221. t[n] = r[n];
  4222. }
  4223. return t;
  4224. }
  4225. class Position {
  4226. constructor(line, col, index) {
  4227. this.line = void 0;
  4228. this.column = void 0;
  4229. this.index = void 0;
  4230. this.line = line;
  4231. this.column = col;
  4232. this.index = index;
  4233. }
  4234. }
  4235. class SourceLocation {
  4236. constructor(start, end) {
  4237. this.start = void 0;
  4238. this.end = void 0;
  4239. this.filename = void 0;
  4240. this.identifierName = void 0;
  4241. this.start = start;
  4242. this.end = end;
  4243. }
  4244. }
  4245. function createPositionWithColumnOffset(position, columnOffset) {
  4246. const {
  4247. line,
  4248. column,
  4249. index
  4250. } = position;
  4251. return new Position(line, column + columnOffset, index + columnOffset);
  4252. }
  4253. const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";
  4254. var ModuleErrors = {
  4255. ImportMetaOutsideModule: {
  4256. message: `import.meta may appear only with 'sourceType: "module"'`,
  4257. code
  4258. },
  4259. ImportOutsideModule: {
  4260. message: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  4261. code
  4262. }
  4263. };
  4264. const NodeDescriptions = {
  4265. ArrayPattern: "array destructuring pattern",
  4266. AssignmentExpression: "assignment expression",
  4267. AssignmentPattern: "assignment expression",
  4268. ArrowFunctionExpression: "arrow function expression",
  4269. ConditionalExpression: "conditional expression",
  4270. CatchClause: "catch clause",
  4271. ForOfStatement: "for-of statement",
  4272. ForInStatement: "for-in statement",
  4273. ForStatement: "for-loop",
  4274. FormalParameters: "function parameter list",
  4275. Identifier: "identifier",
  4276. ImportSpecifier: "import specifier",
  4277. ImportDefaultSpecifier: "import default specifier",
  4278. ImportNamespaceSpecifier: "import namespace specifier",
  4279. ObjectPattern: "object destructuring pattern",
  4280. ParenthesizedExpression: "parenthesized expression",
  4281. RestElement: "rest element",
  4282. UpdateExpression: {
  4283. true: "prefix operation",
  4284. false: "postfix operation"
  4285. },
  4286. VariableDeclarator: "variable declaration",
  4287. YieldExpression: "yield expression"
  4288. };
  4289. const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type];
  4290. var StandardErrors = {
  4291. AccessorIsGenerator: ({
  4292. kind
  4293. }) => `A ${kind}ter cannot be a generator.`,
  4294. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  4295. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  4296. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  4297. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  4298. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  4299. AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.",
  4300. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  4301. BadGetterArity: "A 'get' accessor must not have any formal parameters.",
  4302. BadSetterArity: "A 'set' accessor must have exactly one formal parameter.",
  4303. BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.",
  4304. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  4305. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  4306. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  4307. ConstructorIsAsync: "Constructor can't be an async function.",
  4308. ConstructorIsGenerator: "Constructor can't be a generator.",
  4309. DeclarationMissingInitializer: ({
  4310. kind
  4311. }) => `Missing initializer in ${kind} declaration.`,
  4312. DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",
  4313. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",
  4314. DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",
  4315. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  4316. DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",
  4317. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  4318. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  4319. DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.',
  4320. DeletePrivateField: "Deleting a private field is not allowed.",
  4321. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  4322. DuplicateConstructor: "Duplicate constructor in the same class.",
  4323. DuplicateDefaultExport: "Only one default export allowed per module.",
  4324. DuplicateExport: ({
  4325. exportName
  4326. }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`,
  4327. DuplicateProto: "Redefinition of __proto__ property.",
  4328. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  4329. ElementAfterRest: "Rest element must be last element.",
  4330. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  4331. ExportBindingIsString: ({
  4332. localName,
  4333. exportName
  4334. }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,
  4335. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  4336. ForInOfLoopInitializer: ({
  4337. type
  4338. }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`,
  4339. ForInUsing: "For-in loop may not start with 'using' declaration.",
  4340. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  4341. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  4342. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  4343. IllegalBreakContinue: ({
  4344. type
  4345. }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`,
  4346. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  4347. IllegalReturn: "'return' outside of function.",
  4348. ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.",
  4349. ImportBindingIsString: ({
  4350. importName
  4351. }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`,
  4352. ImportCallArity: `\`import()\` requires exactly one or two arguments.`,
  4353. ImportCallNotNewExpression: "Cannot use new with import(...).",
  4354. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  4355. ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.",
  4356. ImportReflectionHasAssertion: "`import module x` cannot have assertions.",
  4357. ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.',
  4358. IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.",
  4359. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  4360. InvalidCodePoint: "Code point out of bounds.",
  4361. InvalidCoverDiscardElement: "'void' must be followed by an expression when not used in a binding position.",
  4362. InvalidCoverInitializedName: "Invalid shorthand property initializer.",
  4363. InvalidDecimal: "Invalid decimal.",
  4364. InvalidDigit: ({
  4365. radix
  4366. }) => `Expected number in radix ${radix}.`,
  4367. InvalidEscapeSequence: "Bad character escape sequence.",
  4368. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  4369. InvalidEscapedReservedWord: ({
  4370. reservedWord
  4371. }) => `Escape sequence in keyword ${reservedWord}.`,
  4372. InvalidIdentifier: ({
  4373. identifierName
  4374. }) => `Invalid identifier ${identifierName}.`,
  4375. InvalidLhs: ({
  4376. ancestor
  4377. }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  4378. InvalidLhsBinding: ({
  4379. ancestor
  4380. }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  4381. InvalidLhsOptionalChaining: ({
  4382. ancestor
  4383. }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`,
  4384. InvalidNumber: "Invalid number.",
  4385. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  4386. InvalidOrUnexpectedToken: ({
  4387. unexpected
  4388. }) => `Unexpected character '${unexpected}'.`,
  4389. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  4390. InvalidPrivateFieldResolution: ({
  4391. identifierName
  4392. }) => `Private name #${identifierName} is not defined.`,
  4393. InvalidPropertyBindingPattern: "Binding member expression.",
  4394. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  4395. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  4396. LabelRedeclaration: ({
  4397. labelName
  4398. }) => `Label '${labelName}' is already declared.`,
  4399. LetInLexicalBinding: "'let' is disallowed as a lexically bound name.",
  4400. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  4401. MalformedRegExpFlags: "Invalid regular expression flag.",
  4402. MissingClassName: "A class name is required.",
  4403. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  4404. MissingSemicolon: "Missing semicolon.",
  4405. MissingPlugin: ({
  4406. missingPlugin
  4407. }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  4408. MissingOneOfPlugins: ({
  4409. missingPlugin
  4410. }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  4411. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  4412. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  4413. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  4414. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  4415. ModuleAttributesWithDuplicateKeys: ({
  4416. key
  4417. }) => `Duplicate key "${key}" is not allowed in module attributes.`,
  4418. ModuleExportNameHasLoneSurrogate: ({
  4419. surrogateCharCode
  4420. }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,
  4421. ModuleExportUndefined: ({
  4422. localName
  4423. }) => `Export '${localName}' is not defined.`,
  4424. MultipleDefaultsInSwitch: "Multiple default clauses.",
  4425. NewlineAfterThrow: "Illegal newline after throw.",
  4426. NoCatchOrFinally: "Missing catch or finally clause.",
  4427. NumberIdentifier: "Identifier directly after number.",
  4428. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  4429. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  4430. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  4431. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  4432. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  4433. ParamDupe: "Argument name clash.",
  4434. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  4435. PatternHasMethod: "Object pattern can't contain methods.",
  4436. PrivateInExpectedIn: ({
  4437. identifierName
  4438. }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`,
  4439. PrivateNameRedeclaration: ({
  4440. identifierName
  4441. }) => `Duplicate private name #${identifierName}.`,
  4442. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4443. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4444. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  4445. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  4446. RestTrailingComma: "Unexpected trailing comma after rest element.",
  4447. SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.",
  4448. SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",
  4449. SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.',
  4450. StaticPrototype: "Classes may not have static property named prototype.",
  4451. SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  4452. SuperPrivateField: "Private fields can't be accessed on super.",
  4453. TrailingDecorator: "Decorators must be attached to a class element.",
  4454. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4455. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4456. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  4457. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  4458. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  4459. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  4460. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  4461. UnexpectedKeyword: ({
  4462. keyword
  4463. }) => `Unexpected keyword '${keyword}'.`,
  4464. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  4465. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  4466. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  4467. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  4468. UnexpectedPrivateField: "Unexpected private name.",
  4469. UnexpectedReservedWord: ({
  4470. reservedWord
  4471. }) => `Unexpected reserved word '${reservedWord}'.`,
  4472. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  4473. UnexpectedToken: ({
  4474. expected,
  4475. unexpected
  4476. }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`,
  4477. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  4478. UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.",
  4479. UnexpectedVoidPattern: "Unexpected void binding.",
  4480. UnsupportedBind: "Binding should be performed on object property.",
  4481. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  4482. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  4483. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  4484. UnsupportedMetaProperty: ({
  4485. target,
  4486. onlyValidPropertyName
  4487. }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,
  4488. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  4489. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  4490. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  4491. UnterminatedComment: "Unterminated comment.",
  4492. UnterminatedRegExp: "Unterminated regular expression.",
  4493. UnterminatedString: "Unterminated string constant.",
  4494. UnterminatedTemplate: "Unterminated template.",
  4495. UsingDeclarationExport: "Using declaration cannot be exported.",
  4496. UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.",
  4497. VarRedeclaration: ({
  4498. identifierName
  4499. }) => `Identifier '${identifierName}' has already been declared.`,
  4500. VoidPatternCatchClauseParam: "A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",
  4501. VoidPatternInitializer: "A void binding may not have an initializer.",
  4502. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  4503. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  4504. YieldNotInGeneratorFunction: "'yield' is only allowed within generator functions.",
  4505. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  4506. };
  4507. var StrictModeErrors = {
  4508. StrictDelete: "Deleting local variable in strict mode.",
  4509. StrictEvalArguments: ({
  4510. referenceName
  4511. }) => `Assigning to '${referenceName}' in strict mode.`,
  4512. StrictEvalArgumentsBinding: ({
  4513. bindingName
  4514. }) => `Binding '${bindingName}' in strict mode.`,
  4515. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  4516. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  4517. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  4518. StrictWith: "'with' in strict mode."
  4519. };
  4520. var ParseExpressionErrors = {
  4521. ParseExpressionEmptyInput: "Unexpected parseExpression() input: The input is empty or contains only comments.",
  4522. ParseExpressionExpectsEOF: ({
  4523. unexpected
  4524. }) => `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(unexpected)}\`.`
  4525. };
  4526. const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]);
  4527. var PipelineOperatorErrors = Object.assign({
  4528. PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  4529. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  4530. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  4531. PipeTopicUnconfiguredToken: ({
  4532. token
  4533. }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`,
  4534. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  4535. PipeUnparenthesizedBody: ({
  4536. type
  4537. }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({
  4538. type
  4539. })}; please wrap it in parentheses.`
  4540. }, {
  4541. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  4542. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  4543. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  4544. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  4545. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  4546. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'
  4547. });
  4548. const _excluded = ["message"];
  4549. function defineHidden(obj, key, value) {
  4550. Object.defineProperty(obj, key, {
  4551. enumerable: false,
  4552. configurable: true,
  4553. value
  4554. });
  4555. }
  4556. function toParseErrorConstructor({
  4557. toMessage,
  4558. code,
  4559. reasonCode,
  4560. syntaxPlugin
  4561. }) {
  4562. const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins";
  4563. const oldReasonCodes = {
  4564. AccessorCannotDeclareThisParameter: "AccesorCannotDeclareThisParameter",
  4565. AccessorCannotHaveTypeParameters: "AccesorCannotHaveTypeParameters",
  4566. ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",
  4567. SetAccessorCannotHaveOptionalParameter: "SetAccesorCannotHaveOptionalParameter",
  4568. SetAccessorCannotHaveRestParameter: "SetAccesorCannotHaveRestParameter",
  4569. SetAccessorCannotHaveReturnType: "SetAccesorCannotHaveReturnType"
  4570. };
  4571. if (oldReasonCodes[reasonCode]) {
  4572. reasonCode = oldReasonCodes[reasonCode];
  4573. }
  4574. return function constructor(loc, details) {
  4575. const error = new SyntaxError();
  4576. error.code = code;
  4577. error.reasonCode = reasonCode;
  4578. error.loc = loc;
  4579. error.pos = loc.index;
  4580. error.syntaxPlugin = syntaxPlugin;
  4581. if (hasMissingPlugin) {
  4582. error.missingPlugin = details.missingPlugin;
  4583. }
  4584. defineHidden(error, "clone", function clone(overrides = {}) {
  4585. var _overrides$loc;
  4586. const {
  4587. line,
  4588. column,
  4589. index
  4590. } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc;
  4591. return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details));
  4592. });
  4593. defineHidden(error, "details", details);
  4594. Object.defineProperty(error, "message", {
  4595. configurable: true,
  4596. get() {
  4597. const message = `${toMessage(details)} (${loc.line}:${loc.column})`;
  4598. this.message = message;
  4599. return message;
  4600. },
  4601. set(value) {
  4602. Object.defineProperty(this, "message", {
  4603. value,
  4604. writable: true
  4605. });
  4606. }
  4607. });
  4608. return error;
  4609. };
  4610. }
  4611. function ParseErrorEnum(argument, syntaxPlugin) {
  4612. if (Array.isArray(argument)) {
  4613. return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]);
  4614. }
  4615. const ParseErrorConstructors = {};
  4616. for (const reasonCode of Object.keys(argument)) {
  4617. const template = argument[reasonCode];
  4618. const _ref = typeof template === "string" ? {
  4619. message: () => template
  4620. } : typeof template === "function" ? {
  4621. message: template
  4622. } : template,
  4623. {
  4624. message
  4625. } = _ref,
  4626. rest = _objectWithoutPropertiesLoose(_ref, _excluded);
  4627. const toMessage = typeof message === "string" ? () => message : message;
  4628. ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({
  4629. code: "BABEL_PARSER_SYNTAX_ERROR",
  4630. reasonCode,
  4631. toMessage
  4632. }, syntaxPlugin ? {
  4633. syntaxPlugin
  4634. } : {}, rest));
  4635. }
  4636. return ParseErrorConstructors;
  4637. }
  4638. const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum(ParseExpressionErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors));
  4639. function createDefaultOptions() {
  4640. return {
  4641. sourceType: "script",
  4642. sourceFilename: undefined,
  4643. startIndex: 0,
  4644. startColumn: 0,
  4645. startLine: 1,
  4646. allowAwaitOutsideFunction: false,
  4647. allowReturnOutsideFunction: false,
  4648. allowNewTargetOutsideFunction: false,
  4649. allowImportExportEverywhere: false,
  4650. allowSuperOutsideMethod: false,
  4651. allowUndeclaredExports: false,
  4652. allowYieldOutsideFunction: false,
  4653. plugins: [],
  4654. strictMode: undefined,
  4655. ranges: false,
  4656. tokens: false,
  4657. createImportExpressions: false,
  4658. createParenthesizedExpressions: false,
  4659. errorRecovery: false,
  4660. attachComment: true,
  4661. annexB: true
  4662. };
  4663. }
  4664. function getOptions(opts) {
  4665. const options = createDefaultOptions();
  4666. if (opts == null) {
  4667. return options;
  4668. }
  4669. if (opts.annexB != null && opts.annexB !== false) {
  4670. throw new Error("The `annexB` option can only be set to `false`.");
  4671. }
  4672. for (const key of Object.keys(options)) {
  4673. if (opts[key] != null) options[key] = opts[key];
  4674. }
  4675. if (options.startLine === 1) {
  4676. if (opts.startIndex == null && options.startColumn > 0) {
  4677. options.startIndex = options.startColumn;
  4678. } else if (opts.startColumn == null && options.startIndex > 0) {
  4679. options.startColumn = options.startIndex;
  4680. }
  4681. } else if (opts.startColumn == null || opts.startIndex == null) {
  4682. if (opts.startIndex != null) {
  4683. throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");
  4684. }
  4685. }
  4686. if (options.sourceType === "commonjs") {
  4687. if (opts.allowAwaitOutsideFunction != null) {
  4688. throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");
  4689. }
  4690. if (opts.allowReturnOutsideFunction != null) {
  4691. throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");
  4692. }
  4693. if (opts.allowNewTargetOutsideFunction != null) {
  4694. throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.");
  4695. }
  4696. }
  4697. return options;
  4698. }
  4699. const {
  4700. defineProperty
  4701. } = Object;
  4702. const toUnenumerable = (object, key) => {
  4703. if (object) {
  4704. defineProperty(object, key, {
  4705. enumerable: false,
  4706. value: object[key]
  4707. });
  4708. }
  4709. };
  4710. function toESTreeLocation(node) {
  4711. toUnenumerable(node.loc.start, "index");
  4712. toUnenumerable(node.loc.end, "index");
  4713. return node;
  4714. }
  4715. var estree = superClass => class ESTreeParserMixin extends superClass {
  4716. parse() {
  4717. const file = toESTreeLocation(super.parse());
  4718. if (this.optionFlags & 256) {
  4719. file.tokens = file.tokens.map(toESTreeLocation);
  4720. }
  4721. return file;
  4722. }
  4723. parseRegExpLiteral({
  4724. pattern,
  4725. flags
  4726. }) {
  4727. let regex = null;
  4728. try {
  4729. regex = new RegExp(pattern, flags);
  4730. } catch (_) {}
  4731. const node = this.estreeParseLiteral(regex);
  4732. node.regex = {
  4733. pattern,
  4734. flags
  4735. };
  4736. return node;
  4737. }
  4738. parseBigIntLiteral(value) {
  4739. let bigInt;
  4740. try {
  4741. bigInt = BigInt(value);
  4742. } catch (_unused) {
  4743. bigInt = null;
  4744. }
  4745. const node = this.estreeParseLiteral(bigInt);
  4746. node.bigint = String(node.value || value);
  4747. return node;
  4748. }
  4749. parseDecimalLiteral(value) {
  4750. const decimal = null;
  4751. const node = this.estreeParseLiteral(decimal);
  4752. node.decimal = String(node.value || value);
  4753. return node;
  4754. }
  4755. estreeParseLiteral(value) {
  4756. return this.parseLiteral(value, "Literal");
  4757. }
  4758. parseStringLiteral(value) {
  4759. return this.estreeParseLiteral(value);
  4760. }
  4761. parseNumericLiteral(value) {
  4762. return this.estreeParseLiteral(value);
  4763. }
  4764. parseNullLiteral() {
  4765. return this.estreeParseLiteral(null);
  4766. }
  4767. parseBooleanLiteral(value) {
  4768. return this.estreeParseLiteral(value);
  4769. }
  4770. estreeParseChainExpression(node, endLoc) {
  4771. const chain = this.startNodeAtNode(node);
  4772. chain.expression = node;
  4773. return this.finishNodeAt(chain, "ChainExpression", endLoc);
  4774. }
  4775. directiveToStmt(directive) {
  4776. const expression = directive.value;
  4777. delete directive.value;
  4778. this.castNodeTo(expression, "Literal");
  4779. expression.raw = expression.extra.raw;
  4780. expression.value = expression.extra.expressionValue;
  4781. const stmt = this.castNodeTo(directive, "ExpressionStatement");
  4782. stmt.expression = expression;
  4783. stmt.directive = expression.extra.rawValue;
  4784. delete expression.extra;
  4785. return stmt;
  4786. }
  4787. fillOptionalPropertiesForTSESLint(node) {}
  4788. cloneEstreeStringLiteral(node) {
  4789. const {
  4790. start,
  4791. end,
  4792. loc,
  4793. range,
  4794. raw,
  4795. value
  4796. } = node;
  4797. const cloned = Object.create(node.constructor.prototype);
  4798. cloned.type = "Literal";
  4799. cloned.start = start;
  4800. cloned.end = end;
  4801. cloned.loc = loc;
  4802. cloned.range = range;
  4803. cloned.raw = raw;
  4804. cloned.value = value;
  4805. return cloned;
  4806. }
  4807. initFunction(node, isAsync) {
  4808. super.initFunction(node, isAsync);
  4809. node.expression = false;
  4810. }
  4811. checkDeclaration(node) {
  4812. if (node != null && this.isObjectProperty(node)) {
  4813. this.checkDeclaration(node.value);
  4814. } else {
  4815. super.checkDeclaration(node);
  4816. }
  4817. }
  4818. getObjectOrClassMethodParams(method) {
  4819. return method.value.params;
  4820. }
  4821. isValidDirective(stmt) {
  4822. var _stmt$expression$extr;
  4823. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  4824. }
  4825. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  4826. super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse);
  4827. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  4828. node.body = directiveStatements.concat(node.body);
  4829. delete node.directives;
  4830. }
  4831. parsePrivateName() {
  4832. const node = super.parsePrivateName();
  4833. if (!this.getPluginOption("estree", "classFeatures")) {
  4834. return node;
  4835. }
  4836. return this.convertPrivateNameToPrivateIdentifier(node);
  4837. }
  4838. convertPrivateNameToPrivateIdentifier(node) {
  4839. const name = super.getPrivateNameSV(node);
  4840. delete node.id;
  4841. node.name = name;
  4842. return this.castNodeTo(node, "PrivateIdentifier");
  4843. }
  4844. isPrivateName(node) {
  4845. if (!this.getPluginOption("estree", "classFeatures")) {
  4846. return super.isPrivateName(node);
  4847. }
  4848. return node.type === "PrivateIdentifier";
  4849. }
  4850. getPrivateNameSV(node) {
  4851. if (!this.getPluginOption("estree", "classFeatures")) {
  4852. return super.getPrivateNameSV(node);
  4853. }
  4854. return node.name;
  4855. }
  4856. parseLiteral(value, type) {
  4857. const node = super.parseLiteral(value, type);
  4858. node.raw = node.extra.raw;
  4859. delete node.extra;
  4860. return node;
  4861. }
  4862. parseFunctionBody(node, allowExpression, isMethod = false) {
  4863. super.parseFunctionBody(node, allowExpression, isMethod);
  4864. node.expression = node.body.type !== "BlockStatement";
  4865. }
  4866. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  4867. let funcNode = this.startNode();
  4868. funcNode.kind = node.kind;
  4869. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  4870. delete funcNode.kind;
  4871. const {
  4872. typeParameters
  4873. } = node;
  4874. if (typeParameters) {
  4875. delete node.typeParameters;
  4876. funcNode.typeParameters = typeParameters;
  4877. this.resetStartLocationFromNode(funcNode, typeParameters);
  4878. }
  4879. const valueNode = this.castNodeTo(funcNode, "FunctionExpression");
  4880. node.value = valueNode;
  4881. if (type === "ClassPrivateMethod") {
  4882. node.computed = false;
  4883. }
  4884. if (type === "ObjectMethod") {
  4885. if (node.kind === "method") {
  4886. node.kind = "init";
  4887. }
  4888. node.shorthand = false;
  4889. return this.finishNode(node, "Property");
  4890. } else {
  4891. return this.finishNode(node, "MethodDefinition");
  4892. }
  4893. }
  4894. nameIsConstructor(key) {
  4895. if (key.type === "Literal") return key.value === "constructor";
  4896. return super.nameIsConstructor(key);
  4897. }
  4898. parseClassProperty(...args) {
  4899. const propertyNode = super.parseClassProperty(...args);
  4900. if (!this.getPluginOption("estree", "classFeatures")) {
  4901. return propertyNode;
  4902. }
  4903. this.castNodeTo(propertyNode, "PropertyDefinition");
  4904. return propertyNode;
  4905. }
  4906. parseClassPrivateProperty(...args) {
  4907. const propertyNode = super.parseClassPrivateProperty(...args);
  4908. if (!this.getPluginOption("estree", "classFeatures")) {
  4909. return propertyNode;
  4910. }
  4911. this.castNodeTo(propertyNode, "PropertyDefinition");
  4912. propertyNode.computed = false;
  4913. return propertyNode;
  4914. }
  4915. parseClassAccessorProperty(node) {
  4916. const accessorPropertyNode = super.parseClassAccessorProperty(node);
  4917. if (!this.getPluginOption("estree", "classFeatures")) {
  4918. return accessorPropertyNode;
  4919. }
  4920. if (accessorPropertyNode.abstract && this.hasPlugin("typescript")) {
  4921. delete accessorPropertyNode.abstract;
  4922. this.castNodeTo(accessorPropertyNode, "TSAbstractAccessorProperty");
  4923. } else {
  4924. this.castNodeTo(accessorPropertyNode, "AccessorProperty");
  4925. }
  4926. return accessorPropertyNode;
  4927. }
  4928. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  4929. const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  4930. if (node) {
  4931. node.kind = "init";
  4932. this.castNodeTo(node, "Property");
  4933. }
  4934. return node;
  4935. }
  4936. finishObjectProperty(node) {
  4937. node.kind = "init";
  4938. return this.finishNode(node, "Property");
  4939. }
  4940. isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) {
  4941. return type === "Property" ? "value" : super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding);
  4942. }
  4943. isAssignable(node, isBinding) {
  4944. if (node != null && this.isObjectProperty(node)) {
  4945. return this.isAssignable(node.value, isBinding);
  4946. }
  4947. return super.isAssignable(node, isBinding);
  4948. }
  4949. toAssignable(node, isLHS = false) {
  4950. if (node != null && this.isObjectProperty(node)) {
  4951. const {
  4952. key,
  4953. value
  4954. } = node;
  4955. if (this.isPrivateName(key)) {
  4956. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  4957. }
  4958. this.toAssignable(value, isLHS);
  4959. } else {
  4960. super.toAssignable(node, isLHS);
  4961. }
  4962. }
  4963. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  4964. if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) {
  4965. this.raise(Errors.PatternHasAccessor, prop.key);
  4966. } else if (prop.type === "Property" && prop.method) {
  4967. this.raise(Errors.PatternHasMethod, prop.key);
  4968. } else {
  4969. super.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  4970. }
  4971. }
  4972. finishCallExpression(unfinished, optional) {
  4973. const node = super.finishCallExpression(unfinished, optional);
  4974. if (node.callee.type === "Import") {
  4975. var _ref, _ref2;
  4976. this.castNodeTo(node, "ImportExpression");
  4977. node.source = node.arguments[0];
  4978. node.options = (_ref = node.arguments[1]) != null ? _ref : null;
  4979. node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null;
  4980. delete node.arguments;
  4981. delete node.callee;
  4982. } else if (node.type === "OptionalCallExpression") {
  4983. this.castNodeTo(node, "CallExpression");
  4984. } else {
  4985. node.optional = false;
  4986. }
  4987. return node;
  4988. }
  4989. toReferencedArguments(node) {
  4990. if (node.type === "ImportExpression") {
  4991. return;
  4992. }
  4993. super.toReferencedArguments(node);
  4994. }
  4995. parseExport(unfinished, decorators) {
  4996. const exportStartLoc = this.state.lastTokStartLoc;
  4997. const node = super.parseExport(unfinished, decorators);
  4998. switch (node.type) {
  4999. case "ExportAllDeclaration":
  5000. node.exported = null;
  5001. break;
  5002. case "ExportNamedDeclaration":
  5003. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  5004. this.castNodeTo(node, "ExportAllDeclaration");
  5005. node.exported = node.specifiers[0].exported;
  5006. delete node.specifiers;
  5007. }
  5008. case "ExportDefaultDeclaration":
  5009. {
  5010. var _declaration$decorato;
  5011. const {
  5012. declaration
  5013. } = node;
  5014. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) {
  5015. this.resetStartLocation(node, exportStartLoc);
  5016. }
  5017. }
  5018. break;
  5019. }
  5020. return node;
  5021. }
  5022. stopParseSubscript(base, state) {
  5023. const node = super.stopParseSubscript(base, state);
  5024. if (state.optionalChainMember) {
  5025. return this.estreeParseChainExpression(node, base.loc.end);
  5026. }
  5027. return node;
  5028. }
  5029. parseMember(base, startLoc, state, computed, optional) {
  5030. const node = super.parseMember(base, startLoc, state, computed, optional);
  5031. if (node.type === "OptionalMemberExpression") {
  5032. this.castNodeTo(node, "MemberExpression");
  5033. } else {
  5034. node.optional = false;
  5035. }
  5036. return node;
  5037. }
  5038. isOptionalMemberExpression(node) {
  5039. if (node.type === "ChainExpression") {
  5040. return node.expression.type === "MemberExpression";
  5041. }
  5042. return super.isOptionalMemberExpression(node);
  5043. }
  5044. hasPropertyAsPrivateName(node) {
  5045. if (node.type === "ChainExpression") {
  5046. node = node.expression;
  5047. }
  5048. return super.hasPropertyAsPrivateName(node);
  5049. }
  5050. isObjectProperty(node) {
  5051. return node.type === "Property" && node.kind === "init" && !node.method;
  5052. }
  5053. isObjectMethod(node) {
  5054. return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set");
  5055. }
  5056. castNodeTo(node, type) {
  5057. const result = super.castNodeTo(node, type);
  5058. this.fillOptionalPropertiesForTSESLint(result);
  5059. return result;
  5060. }
  5061. cloneIdentifier(node) {
  5062. const cloned = super.cloneIdentifier(node);
  5063. this.fillOptionalPropertiesForTSESLint(cloned);
  5064. return cloned;
  5065. }
  5066. cloneStringLiteral(node) {
  5067. if (node.type === "Literal") {
  5068. return this.cloneEstreeStringLiteral(node);
  5069. }
  5070. return super.cloneStringLiteral(node);
  5071. }
  5072. finishNodeAt(node, type, endLoc) {
  5073. return toESTreeLocation(super.finishNodeAt(node, type, endLoc));
  5074. }
  5075. finishNode(node, type) {
  5076. const result = super.finishNode(node, type);
  5077. this.fillOptionalPropertiesForTSESLint(result);
  5078. return result;
  5079. }
  5080. resetStartLocation(node, startLoc) {
  5081. super.resetStartLocation(node, startLoc);
  5082. toESTreeLocation(node);
  5083. }
  5084. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  5085. super.resetEndLocation(node, endLoc);
  5086. toESTreeLocation(node);
  5087. }
  5088. };
  5089. class TokContext {
  5090. constructor(token, preserveSpace) {
  5091. this.token = void 0;
  5092. this.preserveSpace = void 0;
  5093. this.token = token;
  5094. this.preserveSpace = !!preserveSpace;
  5095. }
  5096. }
  5097. const types = {
  5098. brace: new TokContext("{"),
  5099. j_oTag: new TokContext("<tag"),
  5100. j_cTag: new TokContext("</tag"),
  5101. j_expr: new TokContext("<tag>...</tag>", true)
  5102. };
  5103. types.template = new TokContext("`", true);
  5104. const beforeExpr = true;
  5105. const startsExpr = true;
  5106. const isLoop = true;
  5107. const isAssign = true;
  5108. const prefix = true;
  5109. const postfix = true;
  5110. class ExportedTokenType {
  5111. constructor(label, conf = {}) {
  5112. this.label = void 0;
  5113. this.keyword = void 0;
  5114. this.beforeExpr = void 0;
  5115. this.startsExpr = void 0;
  5116. this.rightAssociative = void 0;
  5117. this.isLoop = void 0;
  5118. this.isAssign = void 0;
  5119. this.prefix = void 0;
  5120. this.postfix = void 0;
  5121. this.binop = void 0;
  5122. this.label = label;
  5123. this.keyword = conf.keyword;
  5124. this.beforeExpr = !!conf.beforeExpr;
  5125. this.startsExpr = !!conf.startsExpr;
  5126. this.rightAssociative = !!conf.rightAssociative;
  5127. this.isLoop = !!conf.isLoop;
  5128. this.isAssign = !!conf.isAssign;
  5129. this.prefix = !!conf.prefix;
  5130. this.postfix = !!conf.postfix;
  5131. this.binop = conf.binop != null ? conf.binop : null;
  5132. this.updateContext = null;
  5133. }
  5134. }
  5135. const keywords$1 = new Map();
  5136. function createKeyword(name, options = {}) {
  5137. options.keyword = name;
  5138. const token = createToken(name, options);
  5139. keywords$1.set(name, token);
  5140. return token;
  5141. }
  5142. function createBinop(name, binop) {
  5143. return createToken(name, {
  5144. beforeExpr,
  5145. binop
  5146. });
  5147. }
  5148. let tokenTypeCounter = -1;
  5149. const tokenTypes = [];
  5150. const tokenLabels = [];
  5151. const tokenBinops = [];
  5152. const tokenBeforeExprs = [];
  5153. const tokenStartsExprs = [];
  5154. const tokenPrefixes = [];
  5155. function createToken(name, options = {}) {
  5156. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  5157. ++tokenTypeCounter;
  5158. tokenLabels.push(name);
  5159. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  5160. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  5161. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  5162. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  5163. tokenTypes.push(new ExportedTokenType(name, options));
  5164. return tokenTypeCounter;
  5165. }
  5166. function createKeywordLike(name, options = {}) {
  5167. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  5168. ++tokenTypeCounter;
  5169. keywords$1.set(name, tokenTypeCounter);
  5170. tokenLabels.push(name);
  5171. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  5172. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  5173. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  5174. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  5175. tokenTypes.push(new ExportedTokenType("name", options));
  5176. return tokenTypeCounter;
  5177. }
  5178. const tt = {
  5179. bracketL: createToken("[", {
  5180. beforeExpr,
  5181. startsExpr
  5182. }),
  5183. bracketHashL: createToken("#[", {
  5184. beforeExpr,
  5185. startsExpr
  5186. }),
  5187. bracketBarL: createToken("[|", {
  5188. beforeExpr,
  5189. startsExpr
  5190. }),
  5191. bracketR: createToken("]"),
  5192. bracketBarR: createToken("|]"),
  5193. braceL: createToken("{", {
  5194. beforeExpr,
  5195. startsExpr
  5196. }),
  5197. braceBarL: createToken("{|", {
  5198. beforeExpr,
  5199. startsExpr
  5200. }),
  5201. braceHashL: createToken("#{", {
  5202. beforeExpr,
  5203. startsExpr
  5204. }),
  5205. braceR: createToken("}"),
  5206. braceBarR: createToken("|}"),
  5207. parenL: createToken("(", {
  5208. beforeExpr,
  5209. startsExpr
  5210. }),
  5211. parenR: createToken(")"),
  5212. comma: createToken(",", {
  5213. beforeExpr
  5214. }),
  5215. semi: createToken(";", {
  5216. beforeExpr
  5217. }),
  5218. colon: createToken(":", {
  5219. beforeExpr
  5220. }),
  5221. doubleColon: createToken("::", {
  5222. beforeExpr
  5223. }),
  5224. dot: createToken("."),
  5225. question: createToken("?", {
  5226. beforeExpr
  5227. }),
  5228. questionDot: createToken("?."),
  5229. arrow: createToken("=>", {
  5230. beforeExpr
  5231. }),
  5232. template: createToken("template"),
  5233. ellipsis: createToken("...", {
  5234. beforeExpr
  5235. }),
  5236. backQuote: createToken("`", {
  5237. startsExpr
  5238. }),
  5239. dollarBraceL: createToken("${", {
  5240. beforeExpr,
  5241. startsExpr
  5242. }),
  5243. templateTail: createToken("...`", {
  5244. startsExpr
  5245. }),
  5246. templateNonTail: createToken("...${", {
  5247. beforeExpr,
  5248. startsExpr
  5249. }),
  5250. at: createToken("@"),
  5251. hash: createToken("#", {
  5252. startsExpr
  5253. }),
  5254. interpreterDirective: createToken("#!..."),
  5255. eq: createToken("=", {
  5256. beforeExpr,
  5257. isAssign
  5258. }),
  5259. assign: createToken("_=", {
  5260. beforeExpr,
  5261. isAssign
  5262. }),
  5263. slashAssign: createToken("_=", {
  5264. beforeExpr,
  5265. isAssign
  5266. }),
  5267. xorAssign: createToken("_=", {
  5268. beforeExpr,
  5269. isAssign
  5270. }),
  5271. moduloAssign: createToken("_=", {
  5272. beforeExpr,
  5273. isAssign
  5274. }),
  5275. incDec: createToken("++/--", {
  5276. prefix,
  5277. postfix,
  5278. startsExpr
  5279. }),
  5280. bang: createToken("!", {
  5281. beforeExpr,
  5282. prefix,
  5283. startsExpr
  5284. }),
  5285. tilde: createToken("~", {
  5286. beforeExpr,
  5287. prefix,
  5288. startsExpr
  5289. }),
  5290. doubleCaret: createToken("^^", {
  5291. startsExpr
  5292. }),
  5293. doubleAt: createToken("@@", {
  5294. startsExpr
  5295. }),
  5296. pipeline: createBinop("|>", 0),
  5297. nullishCoalescing: createBinop("??", 1),
  5298. logicalOR: createBinop("||", 1),
  5299. logicalAND: createBinop("&&", 2),
  5300. bitwiseOR: createBinop("|", 3),
  5301. bitwiseXOR: createBinop("^", 4),
  5302. bitwiseAND: createBinop("&", 5),
  5303. equality: createBinop("==/!=/===/!==", 6),
  5304. lt: createBinop("</>/<=/>=", 7),
  5305. gt: createBinop("</>/<=/>=", 7),
  5306. relational: createBinop("</>/<=/>=", 7),
  5307. bitShift: createBinop("<</>>/>>>", 8),
  5308. bitShiftL: createBinop("<</>>/>>>", 8),
  5309. bitShiftR: createBinop("<</>>/>>>", 8),
  5310. plusMin: createToken("+/-", {
  5311. beforeExpr,
  5312. binop: 9,
  5313. prefix,
  5314. startsExpr
  5315. }),
  5316. modulo: createToken("%", {
  5317. binop: 10,
  5318. startsExpr
  5319. }),
  5320. star: createToken("*", {
  5321. binop: 10
  5322. }),
  5323. slash: createBinop("/", 10),
  5324. exponent: createToken("**", {
  5325. beforeExpr,
  5326. binop: 11,
  5327. rightAssociative: true
  5328. }),
  5329. _in: createKeyword("in", {
  5330. beforeExpr,
  5331. binop: 7
  5332. }),
  5333. _instanceof: createKeyword("instanceof", {
  5334. beforeExpr,
  5335. binop: 7
  5336. }),
  5337. _break: createKeyword("break"),
  5338. _case: createKeyword("case", {
  5339. beforeExpr
  5340. }),
  5341. _catch: createKeyword("catch"),
  5342. _continue: createKeyword("continue"),
  5343. _debugger: createKeyword("debugger"),
  5344. _default: createKeyword("default", {
  5345. beforeExpr
  5346. }),
  5347. _else: createKeyword("else", {
  5348. beforeExpr
  5349. }),
  5350. _finally: createKeyword("finally"),
  5351. _function: createKeyword("function", {
  5352. startsExpr
  5353. }),
  5354. _if: createKeyword("if"),
  5355. _return: createKeyword("return", {
  5356. beforeExpr
  5357. }),
  5358. _switch: createKeyword("switch"),
  5359. _throw: createKeyword("throw", {
  5360. beforeExpr,
  5361. prefix,
  5362. startsExpr
  5363. }),
  5364. _try: createKeyword("try"),
  5365. _var: createKeyword("var"),
  5366. _const: createKeyword("const"),
  5367. _with: createKeyword("with"),
  5368. _new: createKeyword("new", {
  5369. beforeExpr,
  5370. startsExpr
  5371. }),
  5372. _this: createKeyword("this", {
  5373. startsExpr
  5374. }),
  5375. _super: createKeyword("super", {
  5376. startsExpr
  5377. }),
  5378. _class: createKeyword("class", {
  5379. startsExpr
  5380. }),
  5381. _extends: createKeyword("extends", {
  5382. beforeExpr
  5383. }),
  5384. _export: createKeyword("export"),
  5385. _import: createKeyword("import", {
  5386. startsExpr
  5387. }),
  5388. _null: createKeyword("null", {
  5389. startsExpr
  5390. }),
  5391. _true: createKeyword("true", {
  5392. startsExpr
  5393. }),
  5394. _false: createKeyword("false", {
  5395. startsExpr
  5396. }),
  5397. _typeof: createKeyword("typeof", {
  5398. beforeExpr,
  5399. prefix,
  5400. startsExpr
  5401. }),
  5402. _void: createKeyword("void", {
  5403. beforeExpr,
  5404. prefix,
  5405. startsExpr
  5406. }),
  5407. _delete: createKeyword("delete", {
  5408. beforeExpr,
  5409. prefix,
  5410. startsExpr
  5411. }),
  5412. _do: createKeyword("do", {
  5413. isLoop,
  5414. beforeExpr
  5415. }),
  5416. _for: createKeyword("for", {
  5417. isLoop
  5418. }),
  5419. _while: createKeyword("while", {
  5420. isLoop
  5421. }),
  5422. _as: createKeywordLike("as", {
  5423. startsExpr
  5424. }),
  5425. _assert: createKeywordLike("assert", {
  5426. startsExpr
  5427. }),
  5428. _async: createKeywordLike("async", {
  5429. startsExpr
  5430. }),
  5431. _await: createKeywordLike("await", {
  5432. startsExpr
  5433. }),
  5434. _defer: createKeywordLike("defer", {
  5435. startsExpr
  5436. }),
  5437. _from: createKeywordLike("from", {
  5438. startsExpr
  5439. }),
  5440. _get: createKeywordLike("get", {
  5441. startsExpr
  5442. }),
  5443. _let: createKeywordLike("let", {
  5444. startsExpr
  5445. }),
  5446. _meta: createKeywordLike("meta", {
  5447. startsExpr
  5448. }),
  5449. _of: createKeywordLike("of", {
  5450. startsExpr
  5451. }),
  5452. _sent: createKeywordLike("sent", {
  5453. startsExpr
  5454. }),
  5455. _set: createKeywordLike("set", {
  5456. startsExpr
  5457. }),
  5458. _source: createKeywordLike("source", {
  5459. startsExpr
  5460. }),
  5461. _static: createKeywordLike("static", {
  5462. startsExpr
  5463. }),
  5464. _using: createKeywordLike("using", {
  5465. startsExpr
  5466. }),
  5467. _yield: createKeywordLike("yield", {
  5468. startsExpr
  5469. }),
  5470. _asserts: createKeywordLike("asserts", {
  5471. startsExpr
  5472. }),
  5473. _checks: createKeywordLike("checks", {
  5474. startsExpr
  5475. }),
  5476. _exports: createKeywordLike("exports", {
  5477. startsExpr
  5478. }),
  5479. _global: createKeywordLike("global", {
  5480. startsExpr
  5481. }),
  5482. _implements: createKeywordLike("implements", {
  5483. startsExpr
  5484. }),
  5485. _intrinsic: createKeywordLike("intrinsic", {
  5486. startsExpr
  5487. }),
  5488. _infer: createKeywordLike("infer", {
  5489. startsExpr
  5490. }),
  5491. _is: createKeywordLike("is", {
  5492. startsExpr
  5493. }),
  5494. _mixins: createKeywordLike("mixins", {
  5495. startsExpr
  5496. }),
  5497. _proto: createKeywordLike("proto", {
  5498. startsExpr
  5499. }),
  5500. _require: createKeywordLike("require", {
  5501. startsExpr
  5502. }),
  5503. _satisfies: createKeywordLike("satisfies", {
  5504. startsExpr
  5505. }),
  5506. _keyof: createKeywordLike("keyof", {
  5507. startsExpr
  5508. }),
  5509. _readonly: createKeywordLike("readonly", {
  5510. startsExpr
  5511. }),
  5512. _unique: createKeywordLike("unique", {
  5513. startsExpr
  5514. }),
  5515. _abstract: createKeywordLike("abstract", {
  5516. startsExpr
  5517. }),
  5518. _declare: createKeywordLike("declare", {
  5519. startsExpr
  5520. }),
  5521. _enum: createKeywordLike("enum", {
  5522. startsExpr
  5523. }),
  5524. _module: createKeywordLike("module", {
  5525. startsExpr
  5526. }),
  5527. _namespace: createKeywordLike("namespace", {
  5528. startsExpr
  5529. }),
  5530. _interface: createKeywordLike("interface", {
  5531. startsExpr
  5532. }),
  5533. _type: createKeywordLike("type", {
  5534. startsExpr
  5535. }),
  5536. _opaque: createKeywordLike("opaque", {
  5537. startsExpr
  5538. }),
  5539. name: createToken("name", {
  5540. startsExpr
  5541. }),
  5542. placeholder: createToken("%%", {
  5543. startsExpr
  5544. }),
  5545. string: createToken("string", {
  5546. startsExpr
  5547. }),
  5548. num: createToken("num", {
  5549. startsExpr
  5550. }),
  5551. bigint: createToken("bigint", {
  5552. startsExpr
  5553. }),
  5554. decimal: createToken("decimal", {
  5555. startsExpr
  5556. }),
  5557. regexp: createToken("regexp", {
  5558. startsExpr
  5559. }),
  5560. privateName: createToken("#name", {
  5561. startsExpr
  5562. }),
  5563. eof: createToken("eof"),
  5564. jsxName: createToken("jsxName"),
  5565. jsxText: createToken("jsxText", {
  5566. beforeExpr
  5567. }),
  5568. jsxTagStart: createToken("jsxTagStart", {
  5569. startsExpr
  5570. }),
  5571. jsxTagEnd: createToken("jsxTagEnd")
  5572. };
  5573. function tokenIsIdentifier(token) {
  5574. return token >= 93 && token <= 133;
  5575. }
  5576. function tokenKeywordOrIdentifierIsKeyword(token) {
  5577. return token <= 92;
  5578. }
  5579. function tokenIsKeywordOrIdentifier(token) {
  5580. return token >= 58 && token <= 133;
  5581. }
  5582. function tokenIsLiteralPropertyName(token) {
  5583. return token >= 58 && token <= 137;
  5584. }
  5585. function tokenComesBeforeExpression(token) {
  5586. return tokenBeforeExprs[token];
  5587. }
  5588. function tokenCanStartExpression(token) {
  5589. return tokenStartsExprs[token];
  5590. }
  5591. function tokenIsAssignment(token) {
  5592. return token >= 29 && token <= 33;
  5593. }
  5594. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  5595. return token >= 129 && token <= 131;
  5596. }
  5597. function tokenIsLoop(token) {
  5598. return token >= 90 && token <= 92;
  5599. }
  5600. function tokenIsKeyword(token) {
  5601. return token >= 58 && token <= 92;
  5602. }
  5603. function tokenIsOperator(token) {
  5604. return token >= 39 && token <= 59;
  5605. }
  5606. function tokenIsPostfix(token) {
  5607. return token === 34;
  5608. }
  5609. function tokenIsPrefix(token) {
  5610. return tokenPrefixes[token];
  5611. }
  5612. function tokenIsTSTypeOperator(token) {
  5613. return token >= 121 && token <= 123;
  5614. }
  5615. function tokenIsTSDeclarationStart(token) {
  5616. return token >= 124 && token <= 130;
  5617. }
  5618. function tokenLabelName(token) {
  5619. return tokenLabels[token];
  5620. }
  5621. function tokenOperatorPrecedence(token) {
  5622. return tokenBinops[token];
  5623. }
  5624. function tokenIsRightAssociative(token) {
  5625. return token === 57;
  5626. }
  5627. function tokenIsTemplate(token) {
  5628. return token >= 24 && token <= 25;
  5629. }
  5630. function getExportedToken(token) {
  5631. return tokenTypes[token];
  5632. }
  5633. tokenTypes[8].updateContext = context => {
  5634. context.pop();
  5635. };
  5636. tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => {
  5637. context.push(types.brace);
  5638. };
  5639. tokenTypes[22].updateContext = context => {
  5640. if (context[context.length - 1] === types.template) {
  5641. context.pop();
  5642. } else {
  5643. context.push(types.template);
  5644. }
  5645. };
  5646. tokenTypes[143].updateContext = context => {
  5647. context.push(types.j_expr, types.j_oTag);
  5648. };
  5649. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088f\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5c\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdc-\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7dc\ua7f1-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  5650. let nonASCIIidentifierChars = "\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1add\u1ae0-\u1aeb\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65";
  5651. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  5652. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  5653. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  5654. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];
  5655. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  5656. function isInAstralSet(code, set) {
  5657. let pos = 0x10000;
  5658. for (let i = 0, length = set.length; i < length; i += 2) {
  5659. pos += set[i];
  5660. if (pos > code) return false;
  5661. pos += set[i + 1];
  5662. if (pos >= code) return true;
  5663. }
  5664. return false;
  5665. }
  5666. function isIdentifierStart(code) {
  5667. if (code < 65) return code === 36;
  5668. if (code <= 90) return true;
  5669. if (code < 97) return code === 95;
  5670. if (code <= 122) return true;
  5671. if (code <= 0xffff) {
  5672. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  5673. }
  5674. return isInAstralSet(code, astralIdentifierStartCodes);
  5675. }
  5676. function isIdentifierChar(code) {
  5677. if (code < 48) return code === 36;
  5678. if (code < 58) return true;
  5679. if (code < 65) return false;
  5680. if (code <= 90) return true;
  5681. if (code < 97) return code === 95;
  5682. if (code <= 122) return true;
  5683. if (code <= 0xffff) {
  5684. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  5685. }
  5686. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  5687. }
  5688. const reservedWords = {
  5689. keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
  5690. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  5691. strictBind: ["eval", "arguments"]
  5692. };
  5693. const keywords = new Set(reservedWords.keyword);
  5694. const reservedWordsStrictSet = new Set(reservedWords.strict);
  5695. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  5696. function isReservedWord(word, inModule) {
  5697. return inModule && word === "await" || word === "enum";
  5698. }
  5699. function isStrictReservedWord(word, inModule) {
  5700. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  5701. }
  5702. function isStrictBindOnlyReservedWord(word) {
  5703. return reservedWordsStrictBindSet.has(word);
  5704. }
  5705. function isStrictBindReservedWord(word, inModule) {
  5706. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  5707. }
  5708. function isKeyword(word) {
  5709. return keywords.has(word);
  5710. }
  5711. function isIteratorStart(current, next, next2) {
  5712. return current === 64 && next === 64 && isIdentifierStart(next2);
  5713. }
  5714. const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]);
  5715. function canBeReservedWord(word) {
  5716. return reservedWordLikeSet.has(word);
  5717. }
  5718. class Scope {
  5719. constructor(flags) {
  5720. this.flags = 0;
  5721. this.names = new Map();
  5722. this.firstLexicalName = "";
  5723. this.flags = flags;
  5724. }
  5725. }
  5726. class ScopeHandler {
  5727. constructor(parser, inModule) {
  5728. this.parser = void 0;
  5729. this.scopeStack = [];
  5730. this.inModule = void 0;
  5731. this.undefinedExports = new Map();
  5732. this.parser = parser;
  5733. this.inModule = inModule;
  5734. }
  5735. get inTopLevel() {
  5736. return (this.currentScope().flags & 1) > 0;
  5737. }
  5738. get inFunction() {
  5739. return (this.currentVarScopeFlags() & 2) > 0;
  5740. }
  5741. get allowSuper() {
  5742. return (this.currentThisScopeFlags() & 16) > 0;
  5743. }
  5744. get allowDirectSuper() {
  5745. return (this.currentThisScopeFlags() & 32) > 0;
  5746. }
  5747. get allowNewTarget() {
  5748. return (this.currentThisScopeFlags() & 512) > 0;
  5749. }
  5750. get inClass() {
  5751. return (this.currentThisScopeFlags() & 64) > 0;
  5752. }
  5753. get inClassAndNotInNonArrowFunction() {
  5754. const flags = this.currentThisScopeFlags();
  5755. return (flags & 64) > 0 && (flags & 2) === 0;
  5756. }
  5757. get inStaticBlock() {
  5758. for (let i = this.scopeStack.length - 1;; i--) {
  5759. const {
  5760. flags
  5761. } = this.scopeStack[i];
  5762. if (flags & 128) {
  5763. return true;
  5764. }
  5765. if (flags & (1667 | 64)) {
  5766. return false;
  5767. }
  5768. }
  5769. }
  5770. get inNonArrowFunction() {
  5771. return (this.currentThisScopeFlags() & 2) > 0;
  5772. }
  5773. get inBareCaseStatement() {
  5774. return (this.currentScope().flags & 256) > 0;
  5775. }
  5776. get treatFunctionsAsVar() {
  5777. return this.treatFunctionsAsVarInScope(this.currentScope());
  5778. }
  5779. createScope(flags) {
  5780. return new Scope(flags);
  5781. }
  5782. enter(flags) {
  5783. this.scopeStack.push(this.createScope(flags));
  5784. }
  5785. exit() {
  5786. const scope = this.scopeStack.pop();
  5787. return scope.flags;
  5788. }
  5789. treatFunctionsAsVarInScope(scope) {
  5790. return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1);
  5791. }
  5792. declareName(name, bindingType, loc) {
  5793. let scope = this.currentScope();
  5794. if (bindingType & 8 || bindingType & 16) {
  5795. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  5796. let type = scope.names.get(name) || 0;
  5797. if (bindingType & 16) {
  5798. type = type | 4;
  5799. } else {
  5800. if (!scope.firstLexicalName) {
  5801. scope.firstLexicalName = name;
  5802. }
  5803. type = type | 2;
  5804. }
  5805. scope.names.set(name, type);
  5806. if (bindingType & 8) {
  5807. this.maybeExportDefined(scope, name);
  5808. }
  5809. } else if (bindingType & 4) {
  5810. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  5811. scope = this.scopeStack[i];
  5812. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  5813. scope.names.set(name, (scope.names.get(name) || 0) | 1);
  5814. this.maybeExportDefined(scope, name);
  5815. if (scope.flags & 1667) break;
  5816. }
  5817. }
  5818. if (this.parser.inModule && scope.flags & 1) {
  5819. this.undefinedExports.delete(name);
  5820. }
  5821. }
  5822. maybeExportDefined(scope, name) {
  5823. if (this.parser.inModule && scope.flags & 1) {
  5824. this.undefinedExports.delete(name);
  5825. }
  5826. }
  5827. checkRedeclarationInScope(scope, name, bindingType, loc) {
  5828. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  5829. this.parser.raise(Errors.VarRedeclaration, loc, {
  5830. identifierName: name
  5831. });
  5832. }
  5833. }
  5834. isRedeclaredInScope(scope, name, bindingType) {
  5835. if (!(bindingType & 1)) return false;
  5836. if (bindingType & 8) {
  5837. return scope.names.has(name);
  5838. }
  5839. const type = scope.names.get(name) || 0;
  5840. if (bindingType & 16) {
  5841. return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0;
  5842. }
  5843. return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0;
  5844. }
  5845. checkLocalExport(id) {
  5846. const {
  5847. name
  5848. } = id;
  5849. const topLevelScope = this.scopeStack[0];
  5850. if (!topLevelScope.names.has(name)) {
  5851. this.undefinedExports.set(name, id.loc.start);
  5852. }
  5853. }
  5854. currentScope() {
  5855. return this.scopeStack[this.scopeStack.length - 1];
  5856. }
  5857. currentVarScopeFlags() {
  5858. for (let i = this.scopeStack.length - 1;; i--) {
  5859. const {
  5860. flags
  5861. } = this.scopeStack[i];
  5862. if (flags & 1667) {
  5863. return flags;
  5864. }
  5865. }
  5866. }
  5867. currentThisScopeFlags() {
  5868. for (let i = this.scopeStack.length - 1;; i--) {
  5869. const {
  5870. flags
  5871. } = this.scopeStack[i];
  5872. if (flags & (1667 | 64) && !(flags & 4)) {
  5873. return flags;
  5874. }
  5875. }
  5876. }
  5877. }
  5878. class FlowScope extends Scope {
  5879. constructor(...args) {
  5880. super(...args);
  5881. this.declareFunctions = new Set();
  5882. }
  5883. }
  5884. class FlowScopeHandler extends ScopeHandler {
  5885. createScope(flags) {
  5886. return new FlowScope(flags);
  5887. }
  5888. declareName(name, bindingType, loc) {
  5889. const scope = this.currentScope();
  5890. if (bindingType & 2048) {
  5891. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  5892. this.maybeExportDefined(scope, name);
  5893. scope.declareFunctions.add(name);
  5894. return;
  5895. }
  5896. super.declareName(name, bindingType, loc);
  5897. }
  5898. isRedeclaredInScope(scope, name, bindingType) {
  5899. if (super.isRedeclaredInScope(scope, name, bindingType)) return true;
  5900. if (bindingType & 2048 && !scope.declareFunctions.has(name)) {
  5901. const type = scope.names.get(name);
  5902. return (type & 4) > 0 || (type & 2) > 0;
  5903. }
  5904. return false;
  5905. }
  5906. checkLocalExport(id) {
  5907. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  5908. super.checkLocalExport(id);
  5909. }
  5910. }
  5911. }
  5912. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  5913. const FlowErrors = ParseErrorEnum`flow`({
  5914. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  5915. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",
  5916. AssignReservedType: ({
  5917. reservedType
  5918. }) => `Cannot overwrite reserved type ${reservedType}.`,
  5919. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  5920. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  5921. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  5922. EnumBooleanMemberNotInitialized: ({
  5923. memberName,
  5924. enumName
  5925. }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`,
  5926. EnumDuplicateMemberName: ({
  5927. memberName,
  5928. enumName
  5929. }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`,
  5930. EnumInconsistentMemberValues: ({
  5931. enumName
  5932. }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,
  5933. EnumInvalidExplicitType: ({
  5934. invalidEnumType,
  5935. enumName
  5936. }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  5937. EnumInvalidExplicitTypeUnknownSupplied: ({
  5938. enumName
  5939. }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  5940. EnumInvalidMemberInitializerPrimaryType: ({
  5941. enumName,
  5942. memberName,
  5943. explicitType
  5944. }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`,
  5945. EnumInvalidMemberInitializerSymbolType: ({
  5946. enumName,
  5947. memberName
  5948. }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`,
  5949. EnumInvalidMemberInitializerUnknownType: ({
  5950. enumName,
  5951. memberName
  5952. }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`,
  5953. EnumInvalidMemberName: ({
  5954. enumName,
  5955. memberName,
  5956. suggestion
  5957. }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`,
  5958. EnumNumberMemberNotInitialized: ({
  5959. enumName,
  5960. memberName
  5961. }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`,
  5962. EnumStringMemberInconsistentlyInitialized: ({
  5963. enumName
  5964. }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`,
  5965. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  5966. ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.",
  5967. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",
  5968. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  5969. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  5970. InexactVariance: "Explicit inexact syntax cannot have variance.",
  5971. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  5972. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  5973. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  5974. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  5975. PatternIsOptional: Object.assign({
  5976. message: "A binding pattern parameter cannot be optional in an implementation signature."
  5977. }, {
  5978. reasonCode: "OptionalBindingPattern"
  5979. }),
  5980. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  5981. SpreadVariance: "Spread properties cannot have variance.",
  5982. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  5983. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  5984. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  5985. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  5986. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  5987. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  5988. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  5989. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  5990. UnexpectedReservedType: ({
  5991. reservedType
  5992. }) => `Unexpected reserved type ${reservedType}.`,
  5993. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  5994. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  5995. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  5996. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  5997. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  5998. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  5999. UnsupportedDeclareExportKind: ({
  6000. unsupportedExportKind,
  6001. suggestion
  6002. }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`,
  6003. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  6004. UnterminatedFlowComment: "Unterminated flow-comment."
  6005. });
  6006. function isEsModuleType(bodyElement) {
  6007. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  6008. }
  6009. function hasTypeImportKind(node) {
  6010. return node.importKind === "type" || node.importKind === "typeof";
  6011. }
  6012. const exportSuggestions = {
  6013. const: "declare export var",
  6014. let: "declare export var",
  6015. type: "export type",
  6016. interface: "export interface"
  6017. };
  6018. function partition(list, test) {
  6019. const list1 = [];
  6020. const list2 = [];
  6021. for (let i = 0; i < list.length; i++) {
  6022. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  6023. }
  6024. return [list1, list2];
  6025. }
  6026. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  6027. var flow = superClass => class FlowParserMixin extends superClass {
  6028. constructor(...args) {
  6029. super(...args);
  6030. this.flowPragma = undefined;
  6031. }
  6032. getScopeHandler() {
  6033. return FlowScopeHandler;
  6034. }
  6035. shouldParseTypes() {
  6036. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  6037. }
  6038. finishToken(type, val) {
  6039. if (type !== 134 && type !== 13 && type !== 28) {
  6040. if (this.flowPragma === undefined) {
  6041. this.flowPragma = null;
  6042. }
  6043. }
  6044. super.finishToken(type, val);
  6045. }
  6046. addComment(comment) {
  6047. if (this.flowPragma === undefined) {
  6048. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  6049. if (!matches) ;else if (matches[1] === "flow") {
  6050. this.flowPragma = "flow";
  6051. } else if (matches[1] === "noflow") {
  6052. this.flowPragma = "noflow";
  6053. } else {
  6054. throw new Error("Unexpected flow pragma");
  6055. }
  6056. }
  6057. super.addComment(comment);
  6058. }
  6059. flowParseTypeInitialiser(tok) {
  6060. const oldInType = this.state.inType;
  6061. this.state.inType = true;
  6062. this.expect(tok || 14);
  6063. const type = this.flowParseType();
  6064. this.state.inType = oldInType;
  6065. return type;
  6066. }
  6067. flowParsePredicate() {
  6068. const node = this.startNode();
  6069. const moduloLoc = this.state.startLoc;
  6070. this.next();
  6071. this.expectContextual(110);
  6072. if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) {
  6073. this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc);
  6074. }
  6075. if (this.eat(10)) {
  6076. node.value = super.parseExpression();
  6077. this.expect(11);
  6078. return this.finishNode(node, "DeclaredPredicate");
  6079. } else {
  6080. return this.finishNode(node, "InferredPredicate");
  6081. }
  6082. }
  6083. flowParseTypeAndPredicateInitialiser() {
  6084. const oldInType = this.state.inType;
  6085. this.state.inType = true;
  6086. this.expect(14);
  6087. let type = null;
  6088. let predicate = null;
  6089. if (this.match(54)) {
  6090. this.state.inType = oldInType;
  6091. predicate = this.flowParsePredicate();
  6092. } else {
  6093. type = this.flowParseType();
  6094. this.state.inType = oldInType;
  6095. if (this.match(54)) {
  6096. predicate = this.flowParsePredicate();
  6097. }
  6098. }
  6099. return [type, predicate];
  6100. }
  6101. flowParseDeclareClass(node) {
  6102. this.next();
  6103. this.flowParseInterfaceish(node, true);
  6104. return this.finishNode(node, "DeclareClass");
  6105. }
  6106. flowParseDeclareFunction(node) {
  6107. this.next();
  6108. const id = node.id = this.parseIdentifier();
  6109. const typeNode = this.startNode();
  6110. const typeContainer = this.startNode();
  6111. if (this.match(47)) {
  6112. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  6113. } else {
  6114. typeNode.typeParameters = null;
  6115. }
  6116. this.expect(10);
  6117. const tmp = this.flowParseFunctionTypeParams();
  6118. typeNode.params = tmp.params;
  6119. typeNode.rest = tmp.rest;
  6120. typeNode.this = tmp._this;
  6121. this.expect(11);
  6122. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  6123. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  6124. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  6125. this.resetEndLocation(id);
  6126. this.semicolon();
  6127. this.scope.declareName(node.id.name, 2048, node.id.loc.start);
  6128. return this.finishNode(node, "DeclareFunction");
  6129. }
  6130. flowParseDeclare(node, insideModule) {
  6131. if (this.match(80)) {
  6132. return this.flowParseDeclareClass(node);
  6133. } else if (this.match(68)) {
  6134. return this.flowParseDeclareFunction(node);
  6135. } else if (this.match(74)) {
  6136. return this.flowParseDeclareVariable(node);
  6137. } else if (this.eatContextual(127)) {
  6138. if (this.match(16)) {
  6139. return this.flowParseDeclareModuleExports(node);
  6140. } else {
  6141. if (insideModule) {
  6142. this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc);
  6143. }
  6144. return this.flowParseDeclareModule(node);
  6145. }
  6146. } else if (this.isContextual(130)) {
  6147. return this.flowParseDeclareTypeAlias(node);
  6148. } else if (this.isContextual(131)) {
  6149. return this.flowParseDeclareOpaqueType(node);
  6150. } else if (this.isContextual(129)) {
  6151. return this.flowParseDeclareInterface(node);
  6152. } else if (this.match(82)) {
  6153. return this.flowParseDeclareExportDeclaration(node, insideModule);
  6154. }
  6155. throw this.unexpected();
  6156. }
  6157. flowParseDeclareVariable(node) {
  6158. this.next();
  6159. node.id = this.flowParseTypeAnnotatableIdentifier();
  6160. this.scope.declareName(node.id.name, 5, node.id.loc.start);
  6161. this.semicolon();
  6162. return this.finishNode(node, "DeclareVariable");
  6163. }
  6164. flowParseDeclareModule(node) {
  6165. this.scope.enter(0);
  6166. if (this.match(134)) {
  6167. node.id = super.parseExprAtom();
  6168. } else {
  6169. node.id = this.parseIdentifier();
  6170. }
  6171. const bodyNode = node.body = this.startNode();
  6172. const body = bodyNode.body = [];
  6173. this.expect(5);
  6174. while (!this.match(8)) {
  6175. const bodyNode = this.startNode();
  6176. if (this.match(83)) {
  6177. this.next();
  6178. if (!this.isContextual(130) && !this.match(87)) {
  6179. this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc);
  6180. }
  6181. body.push(super.parseImport(bodyNode));
  6182. } else {
  6183. this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule);
  6184. body.push(this.flowParseDeclare(bodyNode, true));
  6185. }
  6186. }
  6187. this.scope.exit();
  6188. this.expect(8);
  6189. this.finishNode(bodyNode, "BlockStatement");
  6190. let kind = null;
  6191. let hasModuleExport = false;
  6192. body.forEach(bodyElement => {
  6193. if (isEsModuleType(bodyElement)) {
  6194. if (kind === "CommonJS") {
  6195. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  6196. }
  6197. kind = "ES";
  6198. } else if (bodyElement.type === "DeclareModuleExports") {
  6199. if (hasModuleExport) {
  6200. this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement);
  6201. }
  6202. if (kind === "ES") {
  6203. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  6204. }
  6205. kind = "CommonJS";
  6206. hasModuleExport = true;
  6207. }
  6208. });
  6209. node.kind = kind || "CommonJS";
  6210. return this.finishNode(node, "DeclareModule");
  6211. }
  6212. flowParseDeclareExportDeclaration(node, insideModule) {
  6213. this.expect(82);
  6214. if (this.eat(65)) {
  6215. if (this.match(68) || this.match(80)) {
  6216. node.declaration = this.flowParseDeclare(this.startNode());
  6217. } else {
  6218. node.declaration = this.flowParseType();
  6219. this.semicolon();
  6220. }
  6221. node.default = true;
  6222. return this.finishNode(node, "DeclareExportDeclaration");
  6223. } else {
  6224. if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) {
  6225. const label = this.state.value;
  6226. throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, {
  6227. unsupportedExportKind: label,
  6228. suggestion: exportSuggestions[label]
  6229. });
  6230. }
  6231. if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) {
  6232. node.declaration = this.flowParseDeclare(this.startNode());
  6233. node.default = false;
  6234. return this.finishNode(node, "DeclareExportDeclaration");
  6235. } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) {
  6236. node = this.parseExport(node, null);
  6237. if (node.type === "ExportNamedDeclaration") {
  6238. node.default = false;
  6239. delete node.exportKind;
  6240. return this.castNodeTo(node, "DeclareExportDeclaration");
  6241. } else {
  6242. return this.castNodeTo(node, "DeclareExportAllDeclaration");
  6243. }
  6244. }
  6245. }
  6246. throw this.unexpected();
  6247. }
  6248. flowParseDeclareModuleExports(node) {
  6249. this.next();
  6250. this.expectContextual(111);
  6251. node.typeAnnotation = this.flowParseTypeAnnotation();
  6252. this.semicolon();
  6253. return this.finishNode(node, "DeclareModuleExports");
  6254. }
  6255. flowParseDeclareTypeAlias(node) {
  6256. this.next();
  6257. const finished = this.flowParseTypeAlias(node);
  6258. this.castNodeTo(finished, "DeclareTypeAlias");
  6259. return finished;
  6260. }
  6261. flowParseDeclareOpaqueType(node) {
  6262. this.next();
  6263. const finished = this.flowParseOpaqueType(node, true);
  6264. this.castNodeTo(finished, "DeclareOpaqueType");
  6265. return finished;
  6266. }
  6267. flowParseDeclareInterface(node) {
  6268. this.next();
  6269. this.flowParseInterfaceish(node, false);
  6270. return this.finishNode(node, "DeclareInterface");
  6271. }
  6272. flowParseInterfaceish(node, isClass) {
  6273. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  6274. this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start);
  6275. if (this.match(47)) {
  6276. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6277. } else {
  6278. node.typeParameters = null;
  6279. }
  6280. node.extends = [];
  6281. if (this.eat(81)) {
  6282. do {
  6283. node.extends.push(this.flowParseInterfaceExtends());
  6284. } while (!isClass && this.eat(12));
  6285. }
  6286. if (isClass) {
  6287. node.implements = [];
  6288. node.mixins = [];
  6289. if (this.eatContextual(117)) {
  6290. do {
  6291. node.mixins.push(this.flowParseInterfaceExtends());
  6292. } while (this.eat(12));
  6293. }
  6294. if (this.eatContextual(113)) {
  6295. do {
  6296. node.implements.push(this.flowParseInterfaceExtends());
  6297. } while (this.eat(12));
  6298. }
  6299. }
  6300. node.body = this.flowParseObjectType({
  6301. allowStatic: isClass,
  6302. allowExact: false,
  6303. allowSpread: false,
  6304. allowProto: isClass,
  6305. allowInexact: false
  6306. });
  6307. }
  6308. flowParseInterfaceExtends() {
  6309. const node = this.startNode();
  6310. node.id = this.flowParseQualifiedTypeIdentifier();
  6311. if (this.match(47)) {
  6312. node.typeParameters = this.flowParseTypeParameterInstantiation();
  6313. } else {
  6314. node.typeParameters = null;
  6315. }
  6316. return this.finishNode(node, "InterfaceExtends");
  6317. }
  6318. flowParseInterface(node) {
  6319. this.flowParseInterfaceish(node, false);
  6320. return this.finishNode(node, "InterfaceDeclaration");
  6321. }
  6322. checkNotUnderscore(word) {
  6323. if (word === "_") {
  6324. this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc);
  6325. }
  6326. }
  6327. checkReservedType(word, startLoc, declaration) {
  6328. if (!reservedTypes.has(word)) return;
  6329. this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, {
  6330. reservedType: word
  6331. });
  6332. }
  6333. flowParseRestrictedIdentifierName(liberal, declaration) {
  6334. this.checkReservedType(this.state.value, this.state.startLoc, declaration);
  6335. return this.parseIdentifierName(liberal);
  6336. }
  6337. flowParseRestrictedIdentifier(liberal, declaration) {
  6338. const node = this.startNode();
  6339. const name = this.flowParseRestrictedIdentifierName(liberal, declaration);
  6340. return this.createIdentifier(node, name);
  6341. }
  6342. flowParseTypeAlias(node) {
  6343. node.id = this.flowParseRestrictedIdentifier(false, true);
  6344. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  6345. if (this.match(47)) {
  6346. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6347. } else {
  6348. node.typeParameters = null;
  6349. }
  6350. node.right = this.flowParseTypeInitialiser(29);
  6351. this.semicolon();
  6352. return this.finishNode(node, "TypeAlias");
  6353. }
  6354. flowParseOpaqueType(node, declare) {
  6355. this.expectContextual(130);
  6356. node.id = this.flowParseRestrictedIdentifier(true, true);
  6357. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  6358. if (this.match(47)) {
  6359. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6360. } else {
  6361. node.typeParameters = null;
  6362. }
  6363. node.supertype = null;
  6364. if (this.match(14)) {
  6365. node.supertype = this.flowParseTypeInitialiser(14);
  6366. }
  6367. node.impltype = null;
  6368. if (!declare) {
  6369. node.impltype = this.flowParseTypeInitialiser(29);
  6370. }
  6371. this.semicolon();
  6372. return this.finishNode(node, "OpaqueType");
  6373. }
  6374. flowParseTypeParameterBound() {
  6375. if (this.match(14) || this.isContextual(81)) {
  6376. const node = this.startNode();
  6377. this.next();
  6378. node.typeAnnotation = this.flowParseType();
  6379. return this.finishNode(node, "TypeAnnotation");
  6380. }
  6381. }
  6382. flowParseTypeParameter(requireDefault = false) {
  6383. const nodeStartLoc = this.state.startLoc;
  6384. const node = this.startNode();
  6385. const variance = this.flowParseVariance();
  6386. node.name = this.flowParseRestrictedIdentifierName();
  6387. node.variance = variance;
  6388. node.bound = this.flowParseTypeParameterBound();
  6389. if (this.match(29)) {
  6390. this.eat(29);
  6391. node.default = this.flowParseType();
  6392. } else {
  6393. if (requireDefault) {
  6394. this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc);
  6395. }
  6396. }
  6397. return this.finishNode(node, "TypeParameter");
  6398. }
  6399. flowParseTypeParameterDeclaration() {
  6400. const oldInType = this.state.inType;
  6401. const node = this.startNode();
  6402. node.params = [];
  6403. this.state.inType = true;
  6404. if (this.match(47) || this.match(143)) {
  6405. this.next();
  6406. } else {
  6407. this.unexpected();
  6408. }
  6409. let defaultRequired = false;
  6410. do {
  6411. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  6412. node.params.push(typeParameter);
  6413. if (typeParameter.default) {
  6414. defaultRequired = true;
  6415. }
  6416. if (!this.match(48)) {
  6417. this.expect(12);
  6418. }
  6419. } while (!this.match(48));
  6420. this.expect(48);
  6421. this.state.inType = oldInType;
  6422. return this.finishNode(node, "TypeParameterDeclaration");
  6423. }
  6424. flowInTopLevelContext(cb) {
  6425. if (this.curContext() !== types.brace) {
  6426. const oldContext = this.state.context;
  6427. this.state.context = [oldContext[0]];
  6428. try {
  6429. return cb();
  6430. } finally {
  6431. this.state.context = oldContext;
  6432. }
  6433. } else {
  6434. return cb();
  6435. }
  6436. }
  6437. flowParseTypeParameterInstantiationInExpression() {
  6438. if (this.reScan_lt() !== 47) return;
  6439. return this.flowParseTypeParameterInstantiation();
  6440. }
  6441. flowParseTypeParameterInstantiation() {
  6442. const node = this.startNode();
  6443. const oldInType = this.state.inType;
  6444. this.state.inType = true;
  6445. node.params = [];
  6446. this.flowInTopLevelContext(() => {
  6447. this.expect(47);
  6448. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  6449. this.state.noAnonFunctionType = false;
  6450. while (!this.match(48)) {
  6451. node.params.push(this.flowParseType());
  6452. if (!this.match(48)) {
  6453. this.expect(12);
  6454. }
  6455. }
  6456. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  6457. });
  6458. this.state.inType = oldInType;
  6459. if (!this.state.inType && this.curContext() === types.brace) {
  6460. this.reScan_lt_gt();
  6461. }
  6462. this.expect(48);
  6463. return this.finishNode(node, "TypeParameterInstantiation");
  6464. }
  6465. flowParseTypeParameterInstantiationCallOrNew() {
  6466. if (this.reScan_lt() !== 47) return null;
  6467. const node = this.startNode();
  6468. const oldInType = this.state.inType;
  6469. node.params = [];
  6470. this.state.inType = true;
  6471. this.expect(47);
  6472. while (!this.match(48)) {
  6473. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  6474. if (!this.match(48)) {
  6475. this.expect(12);
  6476. }
  6477. }
  6478. this.expect(48);
  6479. this.state.inType = oldInType;
  6480. return this.finishNode(node, "TypeParameterInstantiation");
  6481. }
  6482. flowParseInterfaceType() {
  6483. const node = this.startNode();
  6484. this.expectContextual(129);
  6485. node.extends = [];
  6486. if (this.eat(81)) {
  6487. do {
  6488. node.extends.push(this.flowParseInterfaceExtends());
  6489. } while (this.eat(12));
  6490. }
  6491. node.body = this.flowParseObjectType({
  6492. allowStatic: false,
  6493. allowExact: false,
  6494. allowSpread: false,
  6495. allowProto: false,
  6496. allowInexact: false
  6497. });
  6498. return this.finishNode(node, "InterfaceTypeAnnotation");
  6499. }
  6500. flowParseObjectPropertyKey() {
  6501. return this.match(135) || this.match(134) ? super.parseExprAtom() : this.parseIdentifier(true);
  6502. }
  6503. flowParseObjectTypeIndexer(node, isStatic, variance) {
  6504. node.static = isStatic;
  6505. if (this.lookahead().type === 14) {
  6506. node.id = this.flowParseObjectPropertyKey();
  6507. node.key = this.flowParseTypeInitialiser();
  6508. } else {
  6509. node.id = null;
  6510. node.key = this.flowParseType();
  6511. }
  6512. this.expect(3);
  6513. node.value = this.flowParseTypeInitialiser();
  6514. node.variance = variance;
  6515. return this.finishNode(node, "ObjectTypeIndexer");
  6516. }
  6517. flowParseObjectTypeInternalSlot(node, isStatic) {
  6518. node.static = isStatic;
  6519. node.id = this.flowParseObjectPropertyKey();
  6520. this.expect(3);
  6521. this.expect(3);
  6522. if (this.match(47) || this.match(10)) {
  6523. node.method = true;
  6524. node.optional = false;
  6525. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  6526. } else {
  6527. node.method = false;
  6528. if (this.eat(17)) {
  6529. node.optional = true;
  6530. }
  6531. node.value = this.flowParseTypeInitialiser();
  6532. }
  6533. return this.finishNode(node, "ObjectTypeInternalSlot");
  6534. }
  6535. flowParseObjectTypeMethodish(node) {
  6536. node.params = [];
  6537. node.rest = null;
  6538. node.typeParameters = null;
  6539. node.this = null;
  6540. if (this.match(47)) {
  6541. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6542. }
  6543. this.expect(10);
  6544. if (this.match(78)) {
  6545. node.this = this.flowParseFunctionTypeParam(true);
  6546. node.this.name = null;
  6547. if (!this.match(11)) {
  6548. this.expect(12);
  6549. }
  6550. }
  6551. while (!this.match(11) && !this.match(21)) {
  6552. node.params.push(this.flowParseFunctionTypeParam(false));
  6553. if (!this.match(11)) {
  6554. this.expect(12);
  6555. }
  6556. }
  6557. if (this.eat(21)) {
  6558. node.rest = this.flowParseFunctionTypeParam(false);
  6559. }
  6560. this.expect(11);
  6561. node.returnType = this.flowParseTypeInitialiser();
  6562. return this.finishNode(node, "FunctionTypeAnnotation");
  6563. }
  6564. flowParseObjectTypeCallProperty(node, isStatic) {
  6565. const valueNode = this.startNode();
  6566. node.static = isStatic;
  6567. node.value = this.flowParseObjectTypeMethodish(valueNode);
  6568. return this.finishNode(node, "ObjectTypeCallProperty");
  6569. }
  6570. flowParseObjectType({
  6571. allowStatic,
  6572. allowExact,
  6573. allowSpread,
  6574. allowProto,
  6575. allowInexact
  6576. }) {
  6577. const oldInType = this.state.inType;
  6578. this.state.inType = true;
  6579. const nodeStart = this.startNode();
  6580. nodeStart.callProperties = [];
  6581. nodeStart.properties = [];
  6582. nodeStart.indexers = [];
  6583. nodeStart.internalSlots = [];
  6584. let endDelim;
  6585. let exact;
  6586. let inexact = false;
  6587. if (allowExact && this.match(6)) {
  6588. this.expect(6);
  6589. endDelim = 9;
  6590. exact = true;
  6591. } else {
  6592. this.expect(5);
  6593. endDelim = 8;
  6594. exact = false;
  6595. }
  6596. nodeStart.exact = exact;
  6597. while (!this.match(endDelim)) {
  6598. let isStatic = false;
  6599. let protoStartLoc = null;
  6600. let inexactStartLoc = null;
  6601. const node = this.startNode();
  6602. if (allowProto && this.isContextual(118)) {
  6603. const lookahead = this.lookahead();
  6604. if (lookahead.type !== 14 && lookahead.type !== 17) {
  6605. this.next();
  6606. protoStartLoc = this.state.startLoc;
  6607. allowStatic = false;
  6608. }
  6609. }
  6610. if (allowStatic && this.isContextual(106)) {
  6611. const lookahead = this.lookahead();
  6612. if (lookahead.type !== 14 && lookahead.type !== 17) {
  6613. this.next();
  6614. isStatic = true;
  6615. }
  6616. }
  6617. const variance = this.flowParseVariance();
  6618. if (this.eat(0)) {
  6619. if (protoStartLoc != null) {
  6620. this.unexpected(protoStartLoc);
  6621. }
  6622. if (this.eat(0)) {
  6623. if (variance) {
  6624. this.unexpected(variance.loc.start);
  6625. }
  6626. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  6627. } else {
  6628. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  6629. }
  6630. } else if (this.match(10) || this.match(47)) {
  6631. if (protoStartLoc != null) {
  6632. this.unexpected(protoStartLoc);
  6633. }
  6634. if (variance) {
  6635. this.unexpected(variance.loc.start);
  6636. }
  6637. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  6638. } else {
  6639. let kind = "init";
  6640. if (this.isContextual(99) || this.isContextual(104)) {
  6641. const lookahead = this.lookahead();
  6642. if (tokenIsLiteralPropertyName(lookahead.type)) {
  6643. kind = this.state.value;
  6644. this.next();
  6645. }
  6646. }
  6647. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  6648. if (propOrInexact === null) {
  6649. inexact = true;
  6650. inexactStartLoc = this.state.lastTokStartLoc;
  6651. } else {
  6652. nodeStart.properties.push(propOrInexact);
  6653. }
  6654. }
  6655. this.flowObjectTypeSemicolon();
  6656. if (inexactStartLoc && !this.match(8) && !this.match(9)) {
  6657. this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc);
  6658. }
  6659. }
  6660. this.expect(endDelim);
  6661. if (allowSpread) {
  6662. nodeStart.inexact = inexact;
  6663. }
  6664. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  6665. this.state.inType = oldInType;
  6666. return out;
  6667. }
  6668. flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) {
  6669. if (this.eat(21)) {
  6670. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  6671. if (isInexactToken) {
  6672. if (!allowSpread) {
  6673. this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc);
  6674. } else if (!allowInexact) {
  6675. this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc);
  6676. }
  6677. if (variance) {
  6678. this.raise(FlowErrors.InexactVariance, variance);
  6679. }
  6680. return null;
  6681. }
  6682. if (!allowSpread) {
  6683. this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc);
  6684. }
  6685. if (protoStartLoc != null) {
  6686. this.unexpected(protoStartLoc);
  6687. }
  6688. if (variance) {
  6689. this.raise(FlowErrors.SpreadVariance, variance);
  6690. }
  6691. node.argument = this.flowParseType();
  6692. return this.finishNode(node, "ObjectTypeSpreadProperty");
  6693. } else {
  6694. node.key = this.flowParseObjectPropertyKey();
  6695. node.static = isStatic;
  6696. node.proto = protoStartLoc != null;
  6697. node.kind = kind;
  6698. let optional = false;
  6699. if (this.match(47) || this.match(10)) {
  6700. node.method = true;
  6701. if (protoStartLoc != null) {
  6702. this.unexpected(protoStartLoc);
  6703. }
  6704. if (variance) {
  6705. this.unexpected(variance.loc.start);
  6706. }
  6707. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  6708. if (kind === "get" || kind === "set") {
  6709. this.flowCheckGetterSetterParams(node);
  6710. }
  6711. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  6712. this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this);
  6713. }
  6714. } else {
  6715. if (kind !== "init") this.unexpected();
  6716. node.method = false;
  6717. if (this.eat(17)) {
  6718. optional = true;
  6719. }
  6720. node.value = this.flowParseTypeInitialiser();
  6721. node.variance = variance;
  6722. }
  6723. node.optional = optional;
  6724. return this.finishNode(node, "ObjectTypeProperty");
  6725. }
  6726. }
  6727. flowCheckGetterSetterParams(property) {
  6728. const paramCount = property.kind === "get" ? 0 : 1;
  6729. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  6730. if (property.value.this) {
  6731. this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this);
  6732. }
  6733. if (length !== paramCount) {
  6734. this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property);
  6735. }
  6736. if (property.kind === "set" && property.value.rest) {
  6737. this.raise(Errors.BadSetterRestParameter, property);
  6738. }
  6739. }
  6740. flowObjectTypeSemicolon() {
  6741. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  6742. this.unexpected();
  6743. }
  6744. }
  6745. flowParseQualifiedTypeIdentifier(startLoc, id) {
  6746. startLoc != null ? startLoc : startLoc = this.state.startLoc;
  6747. let node = id || this.flowParseRestrictedIdentifier(true);
  6748. while (this.eat(16)) {
  6749. const node2 = this.startNodeAt(startLoc);
  6750. node2.qualification = node;
  6751. node2.id = this.flowParseRestrictedIdentifier(true);
  6752. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  6753. }
  6754. return node;
  6755. }
  6756. flowParseGenericType(startLoc, id) {
  6757. const node = this.startNodeAt(startLoc);
  6758. node.typeParameters = null;
  6759. node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);
  6760. if (this.match(47)) {
  6761. node.typeParameters = this.flowParseTypeParameterInstantiation();
  6762. }
  6763. return this.finishNode(node, "GenericTypeAnnotation");
  6764. }
  6765. flowParseTypeofType() {
  6766. const node = this.startNode();
  6767. this.expect(87);
  6768. node.argument = this.flowParsePrimaryType();
  6769. return this.finishNode(node, "TypeofTypeAnnotation");
  6770. }
  6771. flowParseTupleType() {
  6772. const node = this.startNode();
  6773. node.types = [];
  6774. this.expect(0);
  6775. while (this.state.pos < this.length && !this.match(3)) {
  6776. node.types.push(this.flowParseType());
  6777. if (this.match(3)) break;
  6778. this.expect(12);
  6779. }
  6780. this.expect(3);
  6781. return this.finishNode(node, "TupleTypeAnnotation");
  6782. }
  6783. flowParseFunctionTypeParam(first) {
  6784. let name = null;
  6785. let optional = false;
  6786. let typeAnnotation = null;
  6787. const node = this.startNode();
  6788. const lh = this.lookahead();
  6789. const isThis = this.state.type === 78;
  6790. if (lh.type === 14 || lh.type === 17) {
  6791. if (isThis && !first) {
  6792. this.raise(FlowErrors.ThisParamMustBeFirst, node);
  6793. }
  6794. name = this.parseIdentifier(isThis);
  6795. if (this.eat(17)) {
  6796. optional = true;
  6797. if (isThis) {
  6798. this.raise(FlowErrors.ThisParamMayNotBeOptional, node);
  6799. }
  6800. }
  6801. typeAnnotation = this.flowParseTypeInitialiser();
  6802. } else {
  6803. typeAnnotation = this.flowParseType();
  6804. }
  6805. node.name = name;
  6806. node.optional = optional;
  6807. node.typeAnnotation = typeAnnotation;
  6808. return this.finishNode(node, "FunctionTypeParam");
  6809. }
  6810. reinterpretTypeAsFunctionTypeParam(type) {
  6811. const node = this.startNodeAt(type.loc.start);
  6812. node.name = null;
  6813. node.optional = false;
  6814. node.typeAnnotation = type;
  6815. return this.finishNode(node, "FunctionTypeParam");
  6816. }
  6817. flowParseFunctionTypeParams(params = []) {
  6818. let rest = null;
  6819. let _this = null;
  6820. if (this.match(78)) {
  6821. _this = this.flowParseFunctionTypeParam(true);
  6822. _this.name = null;
  6823. if (!this.match(11)) {
  6824. this.expect(12);
  6825. }
  6826. }
  6827. while (!this.match(11) && !this.match(21)) {
  6828. params.push(this.flowParseFunctionTypeParam(false));
  6829. if (!this.match(11)) {
  6830. this.expect(12);
  6831. }
  6832. }
  6833. if (this.eat(21)) {
  6834. rest = this.flowParseFunctionTypeParam(false);
  6835. }
  6836. return {
  6837. params,
  6838. rest,
  6839. _this
  6840. };
  6841. }
  6842. flowIdentToTypeAnnotation(startLoc, node, id) {
  6843. switch (id.name) {
  6844. case "any":
  6845. return this.finishNode(node, "AnyTypeAnnotation");
  6846. case "bool":
  6847. case "boolean":
  6848. return this.finishNode(node, "BooleanTypeAnnotation");
  6849. case "mixed":
  6850. return this.finishNode(node, "MixedTypeAnnotation");
  6851. case "empty":
  6852. return this.finishNode(node, "EmptyTypeAnnotation");
  6853. case "number":
  6854. return this.finishNode(node, "NumberTypeAnnotation");
  6855. case "string":
  6856. return this.finishNode(node, "StringTypeAnnotation");
  6857. case "symbol":
  6858. return this.finishNode(node, "SymbolTypeAnnotation");
  6859. default:
  6860. this.checkNotUnderscore(id.name);
  6861. return this.flowParseGenericType(startLoc, id);
  6862. }
  6863. }
  6864. flowParsePrimaryType() {
  6865. const startLoc = this.state.startLoc;
  6866. const node = this.startNode();
  6867. let tmp;
  6868. let type;
  6869. let isGroupedType = false;
  6870. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  6871. switch (this.state.type) {
  6872. case 5:
  6873. return this.flowParseObjectType({
  6874. allowStatic: false,
  6875. allowExact: false,
  6876. allowSpread: true,
  6877. allowProto: false,
  6878. allowInexact: true
  6879. });
  6880. case 6:
  6881. return this.flowParseObjectType({
  6882. allowStatic: false,
  6883. allowExact: true,
  6884. allowSpread: true,
  6885. allowProto: false,
  6886. allowInexact: false
  6887. });
  6888. case 0:
  6889. this.state.noAnonFunctionType = false;
  6890. type = this.flowParseTupleType();
  6891. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  6892. return type;
  6893. case 47:
  6894. {
  6895. const node = this.startNode();
  6896. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6897. this.expect(10);
  6898. tmp = this.flowParseFunctionTypeParams();
  6899. node.params = tmp.params;
  6900. node.rest = tmp.rest;
  6901. node.this = tmp._this;
  6902. this.expect(11);
  6903. this.expect(19);
  6904. node.returnType = this.flowParseType();
  6905. return this.finishNode(node, "FunctionTypeAnnotation");
  6906. }
  6907. case 10:
  6908. {
  6909. const node = this.startNode();
  6910. this.next();
  6911. if (!this.match(11) && !this.match(21)) {
  6912. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  6913. const token = this.lookahead().type;
  6914. isGroupedType = token !== 17 && token !== 14;
  6915. } else {
  6916. isGroupedType = true;
  6917. }
  6918. }
  6919. if (isGroupedType) {
  6920. this.state.noAnonFunctionType = false;
  6921. type = this.flowParseType();
  6922. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  6923. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  6924. this.expect(11);
  6925. return type;
  6926. } else {
  6927. this.eat(12);
  6928. }
  6929. }
  6930. if (type) {
  6931. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  6932. } else {
  6933. tmp = this.flowParseFunctionTypeParams();
  6934. }
  6935. node.params = tmp.params;
  6936. node.rest = tmp.rest;
  6937. node.this = tmp._this;
  6938. this.expect(11);
  6939. this.expect(19);
  6940. node.returnType = this.flowParseType();
  6941. node.typeParameters = null;
  6942. return this.finishNode(node, "FunctionTypeAnnotation");
  6943. }
  6944. case 134:
  6945. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  6946. case 85:
  6947. case 86:
  6948. node.value = this.match(85);
  6949. this.next();
  6950. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  6951. case 53:
  6952. if (this.state.value === "-") {
  6953. this.next();
  6954. if (this.match(135)) {
  6955. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  6956. }
  6957. if (this.match(136)) {
  6958. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  6959. }
  6960. throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc);
  6961. }
  6962. throw this.unexpected();
  6963. case 135:
  6964. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  6965. case 136:
  6966. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  6967. case 88:
  6968. this.next();
  6969. return this.finishNode(node, "VoidTypeAnnotation");
  6970. case 84:
  6971. this.next();
  6972. return this.finishNode(node, "NullLiteralTypeAnnotation");
  6973. case 78:
  6974. this.next();
  6975. return this.finishNode(node, "ThisTypeAnnotation");
  6976. case 55:
  6977. this.next();
  6978. return this.finishNode(node, "ExistsTypeAnnotation");
  6979. case 87:
  6980. return this.flowParseTypeofType();
  6981. default:
  6982. if (tokenIsKeyword(this.state.type)) {
  6983. const label = tokenLabelName(this.state.type);
  6984. this.next();
  6985. return super.createIdentifier(node, label);
  6986. } else if (tokenIsIdentifier(this.state.type)) {
  6987. if (this.isContextual(129)) {
  6988. return this.flowParseInterfaceType();
  6989. }
  6990. return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier());
  6991. }
  6992. }
  6993. throw this.unexpected();
  6994. }
  6995. flowParsePostfixType() {
  6996. const startLoc = this.state.startLoc;
  6997. let type = this.flowParsePrimaryType();
  6998. let seenOptionalIndexedAccess = false;
  6999. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  7000. const node = this.startNodeAt(startLoc);
  7001. const optional = this.eat(18);
  7002. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  7003. this.expect(0);
  7004. if (!optional && this.match(3)) {
  7005. node.elementType = type;
  7006. this.next();
  7007. type = this.finishNode(node, "ArrayTypeAnnotation");
  7008. } else {
  7009. node.objectType = type;
  7010. node.indexType = this.flowParseType();
  7011. this.expect(3);
  7012. if (seenOptionalIndexedAccess) {
  7013. node.optional = optional;
  7014. type = this.finishNode(node, "OptionalIndexedAccessType");
  7015. } else {
  7016. type = this.finishNode(node, "IndexedAccessType");
  7017. }
  7018. }
  7019. }
  7020. return type;
  7021. }
  7022. flowParsePrefixType() {
  7023. const node = this.startNode();
  7024. if (this.eat(17)) {
  7025. node.typeAnnotation = this.flowParsePrefixType();
  7026. return this.finishNode(node, "NullableTypeAnnotation");
  7027. } else {
  7028. return this.flowParsePostfixType();
  7029. }
  7030. }
  7031. flowParseAnonFunctionWithoutParens() {
  7032. const param = this.flowParsePrefixType();
  7033. if (!this.state.noAnonFunctionType && this.eat(19)) {
  7034. const node = this.startNodeAt(param.loc.start);
  7035. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  7036. node.rest = null;
  7037. node.this = null;
  7038. node.returnType = this.flowParseType();
  7039. node.typeParameters = null;
  7040. return this.finishNode(node, "FunctionTypeAnnotation");
  7041. }
  7042. return param;
  7043. }
  7044. flowParseIntersectionType() {
  7045. const node = this.startNode();
  7046. this.eat(45);
  7047. const type = this.flowParseAnonFunctionWithoutParens();
  7048. node.types = [type];
  7049. while (this.eat(45)) {
  7050. node.types.push(this.flowParseAnonFunctionWithoutParens());
  7051. }
  7052. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  7053. }
  7054. flowParseUnionType() {
  7055. const node = this.startNode();
  7056. this.eat(43);
  7057. const type = this.flowParseIntersectionType();
  7058. node.types = [type];
  7059. while (this.eat(43)) {
  7060. node.types.push(this.flowParseIntersectionType());
  7061. }
  7062. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  7063. }
  7064. flowParseType() {
  7065. const oldInType = this.state.inType;
  7066. this.state.inType = true;
  7067. const type = this.flowParseUnionType();
  7068. this.state.inType = oldInType;
  7069. return type;
  7070. }
  7071. flowParseTypeOrImplicitInstantiation() {
  7072. if (this.state.type === 132 && this.state.value === "_") {
  7073. const startLoc = this.state.startLoc;
  7074. const node = this.parseIdentifier();
  7075. return this.flowParseGenericType(startLoc, node);
  7076. } else {
  7077. return this.flowParseType();
  7078. }
  7079. }
  7080. flowParseTypeAnnotation() {
  7081. const node = this.startNode();
  7082. node.typeAnnotation = this.flowParseTypeInitialiser();
  7083. return this.finishNode(node, "TypeAnnotation");
  7084. }
  7085. flowParseTypeAnnotatableIdentifier() {
  7086. const node = this.startNode();
  7087. const name = this.parseIdentifierName();
  7088. if (this.match(14)) {
  7089. node.typeAnnotation = this.flowParseTypeAnnotation();
  7090. }
  7091. return this.createIdentifier(node, name);
  7092. }
  7093. typeCastToParameter(node) {
  7094. node.expression.typeAnnotation = node.typeAnnotation;
  7095. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  7096. return node.expression;
  7097. }
  7098. flowParseVariance() {
  7099. let variance = null;
  7100. if (this.match(53)) {
  7101. variance = this.startNode();
  7102. if (this.state.value === "+") {
  7103. variance.kind = "plus";
  7104. } else {
  7105. variance.kind = "minus";
  7106. }
  7107. this.next();
  7108. return this.finishNode(variance, "Variance");
  7109. }
  7110. return variance;
  7111. }
  7112. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  7113. if (allowExpressionBody) {
  7114. this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  7115. return;
  7116. }
  7117. super.parseFunctionBody(node, false, isMethod);
  7118. }
  7119. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  7120. if (this.match(14)) {
  7121. const typeNode = this.startNode();
  7122. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  7123. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  7124. }
  7125. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  7126. }
  7127. parseStatementLike(flags) {
  7128. if (this.state.strict && this.isContextual(129)) {
  7129. const lookahead = this.lookahead();
  7130. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  7131. const node = this.startNode();
  7132. this.next();
  7133. return this.flowParseInterface(node);
  7134. }
  7135. } else if (this.isContextual(126)) {
  7136. const node = this.startNode();
  7137. this.next();
  7138. return this.flowParseEnumDeclaration(node);
  7139. }
  7140. const stmt = super.parseStatementLike(flags);
  7141. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  7142. this.flowPragma = null;
  7143. }
  7144. return stmt;
  7145. }
  7146. parseExpressionStatement(node, expr, decorators) {
  7147. if (expr.type === "Identifier") {
  7148. if (expr.name === "declare") {
  7149. if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) {
  7150. return this.flowParseDeclare(node);
  7151. }
  7152. } else if (tokenIsIdentifier(this.state.type)) {
  7153. if (expr.name === "interface") {
  7154. return this.flowParseInterface(node);
  7155. } else if (expr.name === "type") {
  7156. return this.flowParseTypeAlias(node);
  7157. } else if (expr.name === "opaque") {
  7158. return this.flowParseOpaqueType(node, false);
  7159. }
  7160. }
  7161. }
  7162. return super.parseExpressionStatement(node, expr, decorators);
  7163. }
  7164. shouldParseExportDeclaration() {
  7165. const {
  7166. type
  7167. } = this.state;
  7168. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  7169. return !this.state.containsEsc;
  7170. }
  7171. return super.shouldParseExportDeclaration();
  7172. }
  7173. isExportDefaultSpecifier() {
  7174. const {
  7175. type
  7176. } = this.state;
  7177. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  7178. return this.state.containsEsc;
  7179. }
  7180. return super.isExportDefaultSpecifier();
  7181. }
  7182. parseExportDefaultExpression() {
  7183. if (this.isContextual(126)) {
  7184. const node = this.startNode();
  7185. this.next();
  7186. return this.flowParseEnumDeclaration(node);
  7187. }
  7188. return super.parseExportDefaultExpression();
  7189. }
  7190. parseConditional(expr, startLoc, refExpressionErrors) {
  7191. if (!this.match(17)) return expr;
  7192. if (this.state.maybeInArrowParameters) {
  7193. const nextCh = this.lookaheadCharCode();
  7194. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  7195. this.setOptionalParametersError(refExpressionErrors);
  7196. return expr;
  7197. }
  7198. }
  7199. this.expect(17);
  7200. const state = this.state.clone();
  7201. const originalNoArrowAt = this.state.noArrowAt;
  7202. const node = this.startNodeAt(startLoc);
  7203. let {
  7204. consequent,
  7205. failed
  7206. } = this.tryParseConditionalConsequent();
  7207. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  7208. if (failed || invalid.length > 0) {
  7209. const noArrowAt = [...originalNoArrowAt];
  7210. if (invalid.length > 0) {
  7211. this.state = state;
  7212. this.state.noArrowAt = noArrowAt;
  7213. for (let i = 0; i < invalid.length; i++) {
  7214. noArrowAt.push(invalid[i].start);
  7215. }
  7216. ({
  7217. consequent,
  7218. failed
  7219. } = this.tryParseConditionalConsequent());
  7220. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  7221. }
  7222. if (failed && valid.length > 1) {
  7223. this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc);
  7224. }
  7225. if (failed && valid.length === 1) {
  7226. this.state = state;
  7227. noArrowAt.push(valid[0].start);
  7228. this.state.noArrowAt = noArrowAt;
  7229. ({
  7230. consequent,
  7231. failed
  7232. } = this.tryParseConditionalConsequent());
  7233. }
  7234. }
  7235. this.getArrowLikeExpressions(consequent, true);
  7236. this.state.noArrowAt = originalNoArrowAt;
  7237. this.expect(14);
  7238. node.test = expr;
  7239. node.consequent = consequent;
  7240. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  7241. return this.finishNode(node, "ConditionalExpression");
  7242. }
  7243. tryParseConditionalConsequent() {
  7244. this.state.noArrowParamsConversionAt.push(this.state.start);
  7245. const consequent = this.parseMaybeAssignAllowIn();
  7246. const failed = !this.match(14);
  7247. this.state.noArrowParamsConversionAt.pop();
  7248. return {
  7249. consequent,
  7250. failed
  7251. };
  7252. }
  7253. getArrowLikeExpressions(node, disallowInvalid) {
  7254. const stack = [node];
  7255. const arrows = [];
  7256. while (stack.length !== 0) {
  7257. const node = stack.pop();
  7258. if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
  7259. if (node.typeParameters || !node.returnType) {
  7260. this.finishArrowValidation(node);
  7261. } else {
  7262. arrows.push(node);
  7263. }
  7264. stack.push(node.body);
  7265. } else if (node.type === "ConditionalExpression") {
  7266. stack.push(node.consequent);
  7267. stack.push(node.alternate);
  7268. }
  7269. }
  7270. if (disallowInvalid) {
  7271. arrows.forEach(node => this.finishArrowValidation(node));
  7272. return [arrows, []];
  7273. }
  7274. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  7275. }
  7276. finishArrowValidation(node) {
  7277. var _node$extra;
  7278. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
  7279. this.scope.enter(514 | 4);
  7280. super.checkParams(node, false, true);
  7281. this.scope.exit();
  7282. }
  7283. forwardNoArrowParamsConversionAt(node, parse) {
  7284. let result;
  7285. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  7286. this.state.noArrowParamsConversionAt.push(this.state.start);
  7287. result = parse();
  7288. this.state.noArrowParamsConversionAt.pop();
  7289. } else {
  7290. result = parse();
  7291. }
  7292. return result;
  7293. }
  7294. parseParenItem(node, startLoc) {
  7295. const newNode = super.parseParenItem(node, startLoc);
  7296. if (this.eat(17)) {
  7297. newNode.optional = true;
  7298. this.resetEndLocation(node);
  7299. }
  7300. if (this.match(14)) {
  7301. const typeCastNode = this.startNodeAt(startLoc);
  7302. typeCastNode.expression = newNode;
  7303. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  7304. return this.finishNode(typeCastNode, "TypeCastExpression");
  7305. }
  7306. return newNode;
  7307. }
  7308. assertModuleNodeAllowed(node) {
  7309. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  7310. return;
  7311. }
  7312. super.assertModuleNodeAllowed(node);
  7313. }
  7314. parseExportDeclaration(node) {
  7315. if (this.isContextual(130)) {
  7316. node.exportKind = "type";
  7317. const declarationNode = this.startNode();
  7318. this.next();
  7319. if (this.match(5)) {
  7320. node.specifiers = this.parseExportSpecifiers(true);
  7321. super.parseExportFrom(node);
  7322. return null;
  7323. } else {
  7324. return this.flowParseTypeAlias(declarationNode);
  7325. }
  7326. } else if (this.isContextual(131)) {
  7327. node.exportKind = "type";
  7328. const declarationNode = this.startNode();
  7329. this.next();
  7330. return this.flowParseOpaqueType(declarationNode, false);
  7331. } else if (this.isContextual(129)) {
  7332. node.exportKind = "type";
  7333. const declarationNode = this.startNode();
  7334. this.next();
  7335. return this.flowParseInterface(declarationNode);
  7336. } else if (this.isContextual(126)) {
  7337. node.exportKind = "value";
  7338. const declarationNode = this.startNode();
  7339. this.next();
  7340. return this.flowParseEnumDeclaration(declarationNode);
  7341. } else {
  7342. return super.parseExportDeclaration(node);
  7343. }
  7344. }
  7345. eatExportStar(node) {
  7346. if (super.eatExportStar(node)) return true;
  7347. if (this.isContextual(130) && this.lookahead().type === 55) {
  7348. node.exportKind = "type";
  7349. this.next();
  7350. this.next();
  7351. return true;
  7352. }
  7353. return false;
  7354. }
  7355. maybeParseExportNamespaceSpecifier(node) {
  7356. const {
  7357. startLoc
  7358. } = this.state;
  7359. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  7360. if (hasNamespace && node.exportKind === "type") {
  7361. this.unexpected(startLoc);
  7362. }
  7363. return hasNamespace;
  7364. }
  7365. parseClassId(node, isStatement, optionalId) {
  7366. super.parseClassId(node, isStatement, optionalId);
  7367. if (this.match(47)) {
  7368. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7369. }
  7370. }
  7371. parseClassMember(classBody, member, state) {
  7372. const {
  7373. startLoc
  7374. } = this.state;
  7375. if (this.isContextual(125)) {
  7376. if (super.parseClassMemberFromModifier(classBody, member)) {
  7377. return;
  7378. }
  7379. member.declare = true;
  7380. }
  7381. super.parseClassMember(classBody, member, state);
  7382. if (member.declare) {
  7383. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  7384. this.raise(FlowErrors.DeclareClassElement, startLoc);
  7385. } else if (member.value) {
  7386. this.raise(FlowErrors.DeclareClassFieldInitializer, member.value);
  7387. }
  7388. }
  7389. }
  7390. isIterator(word) {
  7391. return word === "iterator" || word === "asyncIterator";
  7392. }
  7393. readIterator() {
  7394. const word = super.readWord1();
  7395. const fullWord = "@@" + word;
  7396. if (!this.isIterator(word) || !this.state.inType) {
  7397. this.raise(Errors.InvalidIdentifier, this.state.curPosition(), {
  7398. identifierName: fullWord
  7399. });
  7400. }
  7401. this.finishToken(132, fullWord);
  7402. }
  7403. getTokenFromCode(code) {
  7404. const next = this.input.charCodeAt(this.state.pos + 1);
  7405. if (code === 123 && next === 124) {
  7406. this.finishOp(6, 2);
  7407. } else if (this.state.inType && (code === 62 || code === 60)) {
  7408. this.finishOp(code === 62 ? 48 : 47, 1);
  7409. } else if (this.state.inType && code === 63) {
  7410. if (next === 46) {
  7411. this.finishOp(18, 2);
  7412. } else {
  7413. this.finishOp(17, 1);
  7414. }
  7415. } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) {
  7416. this.state.pos += 2;
  7417. this.readIterator();
  7418. } else {
  7419. super.getTokenFromCode(code);
  7420. }
  7421. }
  7422. isAssignable(node, isBinding) {
  7423. if (node.type === "TypeCastExpression") {
  7424. return this.isAssignable(node.expression, isBinding);
  7425. } else {
  7426. return super.isAssignable(node, isBinding);
  7427. }
  7428. }
  7429. toAssignable(node, isLHS = false) {
  7430. if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") {
  7431. node.left = this.typeCastToParameter(node.left);
  7432. }
  7433. super.toAssignable(node, isLHS);
  7434. }
  7435. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  7436. for (let i = 0; i < exprList.length; i++) {
  7437. const expr = exprList[i];
  7438. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  7439. exprList[i] = this.typeCastToParameter(expr);
  7440. }
  7441. }
  7442. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  7443. }
  7444. toReferencedList(exprList, isParenthesizedExpr) {
  7445. for (let i = 0; i < exprList.length; i++) {
  7446. var _expr$extra;
  7447. const expr = exprList[i];
  7448. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  7449. this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation);
  7450. }
  7451. }
  7452. return exprList;
  7453. }
  7454. parseArrayLike(close, isTuple, refExpressionErrors) {
  7455. const node = super.parseArrayLike(close, isTuple, refExpressionErrors);
  7456. if (refExpressionErrors != null && !this.state.maybeInArrowParameters) {
  7457. this.toReferencedList(node.elements);
  7458. }
  7459. return node;
  7460. }
  7461. isValidLVal(type, disallowCallExpression, isParenthesized, binding) {
  7462. return type === "TypeCastExpression" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding);
  7463. }
  7464. parseClassProperty(node) {
  7465. if (this.match(14)) {
  7466. node.typeAnnotation = this.flowParseTypeAnnotation();
  7467. }
  7468. return super.parseClassProperty(node);
  7469. }
  7470. parseClassPrivateProperty(node) {
  7471. if (this.match(14)) {
  7472. node.typeAnnotation = this.flowParseTypeAnnotation();
  7473. }
  7474. return super.parseClassPrivateProperty(node);
  7475. }
  7476. isClassMethod() {
  7477. return this.match(47) || super.isClassMethod();
  7478. }
  7479. isClassProperty() {
  7480. return this.match(14) || super.isClassProperty();
  7481. }
  7482. isNonstaticConstructor(method) {
  7483. return !this.match(14) && super.isNonstaticConstructor(method);
  7484. }
  7485. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  7486. if (method.variance) {
  7487. this.unexpected(method.variance.loc.start);
  7488. }
  7489. delete method.variance;
  7490. if (this.match(47)) {
  7491. method.typeParameters = this.flowParseTypeParameterDeclaration();
  7492. }
  7493. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  7494. if (method.params && isConstructor) {
  7495. const params = method.params;
  7496. if (params.length > 0 && this.isThisParam(params[0])) {
  7497. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  7498. }
  7499. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  7500. const params = method.value.params;
  7501. if (params.length > 0 && this.isThisParam(params[0])) {
  7502. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  7503. }
  7504. }
  7505. }
  7506. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  7507. if (method.variance) {
  7508. this.unexpected(method.variance.loc.start);
  7509. }
  7510. delete method.variance;
  7511. if (this.match(47)) {
  7512. method.typeParameters = this.flowParseTypeParameterDeclaration();
  7513. }
  7514. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  7515. }
  7516. parseClassSuper(node) {
  7517. super.parseClassSuper(node);
  7518. if (node.superClass && (this.match(47) || this.match(51))) {
  7519. node.superTypeParameters = this.flowParseTypeParameterInstantiationInExpression();
  7520. }
  7521. if (this.isContextual(113)) {
  7522. this.next();
  7523. const implemented = node.implements = [];
  7524. do {
  7525. const node = this.startNode();
  7526. node.id = this.flowParseRestrictedIdentifier(true);
  7527. if (this.match(47)) {
  7528. node.typeParameters = this.flowParseTypeParameterInstantiation();
  7529. } else {
  7530. node.typeParameters = null;
  7531. }
  7532. implemented.push(this.finishNode(node, "ClassImplements"));
  7533. } while (this.eat(12));
  7534. }
  7535. }
  7536. checkGetterSetterParams(method) {
  7537. super.checkGetterSetterParams(method);
  7538. const params = this.getObjectOrClassMethodParams(method);
  7539. if (params.length > 0) {
  7540. const param = params[0];
  7541. if (this.isThisParam(param) && method.kind === "get") {
  7542. this.raise(FlowErrors.GetterMayNotHaveThisParam, param);
  7543. } else if (this.isThisParam(param)) {
  7544. this.raise(FlowErrors.SetterMayNotHaveThisParam, param);
  7545. }
  7546. }
  7547. }
  7548. parsePropertyNamePrefixOperator(node) {
  7549. node.variance = this.flowParseVariance();
  7550. }
  7551. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  7552. if (prop.variance) {
  7553. this.unexpected(prop.variance.loc.start);
  7554. }
  7555. delete prop.variance;
  7556. let typeParameters;
  7557. if (this.match(47) && !isAccessor) {
  7558. typeParameters = this.flowParseTypeParameterDeclaration();
  7559. if (!this.match(10)) this.unexpected();
  7560. }
  7561. const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  7562. if (typeParameters) {
  7563. (result.value || result).typeParameters = typeParameters;
  7564. }
  7565. return result;
  7566. }
  7567. parseFunctionParamType(param) {
  7568. if (this.eat(17)) {
  7569. if (param.type !== "Identifier") {
  7570. this.raise(FlowErrors.PatternIsOptional, param);
  7571. }
  7572. if (this.isThisParam(param)) {
  7573. this.raise(FlowErrors.ThisParamMayNotBeOptional, param);
  7574. }
  7575. param.optional = true;
  7576. }
  7577. if (this.match(14)) {
  7578. param.typeAnnotation = this.flowParseTypeAnnotation();
  7579. } else if (this.isThisParam(param)) {
  7580. this.raise(FlowErrors.ThisParamAnnotationRequired, param);
  7581. }
  7582. if (this.match(29) && this.isThisParam(param)) {
  7583. this.raise(FlowErrors.ThisParamNoDefault, param);
  7584. }
  7585. this.resetEndLocation(param);
  7586. return param;
  7587. }
  7588. parseMaybeDefault(startLoc, left) {
  7589. const node = super.parseMaybeDefault(startLoc, left);
  7590. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  7591. this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation);
  7592. }
  7593. return node;
  7594. }
  7595. checkImportReflection(node) {
  7596. super.checkImportReflection(node);
  7597. if (node.module && node.importKind !== "value") {
  7598. this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  7599. }
  7600. }
  7601. parseImportSpecifierLocal(node, specifier, type) {
  7602. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  7603. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  7604. }
  7605. isPotentialImportPhase(isExport) {
  7606. if (super.isPotentialImportPhase(isExport)) return true;
  7607. if (this.isContextual(130)) {
  7608. if (!isExport) return true;
  7609. const ch = this.lookaheadCharCode();
  7610. return ch === 123 || ch === 42;
  7611. }
  7612. return !isExport && this.isContextual(87);
  7613. }
  7614. applyImportPhase(node, isExport, phase, loc) {
  7615. super.applyImportPhase(node, isExport, phase, loc);
  7616. if (isExport) {
  7617. if (!phase && this.match(65)) {
  7618. return;
  7619. }
  7620. node.exportKind = phase === "type" ? phase : "value";
  7621. } else {
  7622. if (phase === "type" && this.match(55)) this.unexpected();
  7623. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  7624. }
  7625. }
  7626. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  7627. const firstIdent = specifier.imported;
  7628. let specifierTypeKind = null;
  7629. if (firstIdent.type === "Identifier") {
  7630. if (firstIdent.name === "type") {
  7631. specifierTypeKind = "type";
  7632. } else if (firstIdent.name === "typeof") {
  7633. specifierTypeKind = "typeof";
  7634. }
  7635. }
  7636. let isBinding = false;
  7637. if (this.isContextual(93) && !this.isLookaheadContextual("as")) {
  7638. const as_ident = this.parseIdentifier(true);
  7639. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  7640. specifier.imported = as_ident;
  7641. specifier.importKind = specifierTypeKind;
  7642. specifier.local = this.cloneIdentifier(as_ident);
  7643. } else {
  7644. specifier.imported = firstIdent;
  7645. specifier.importKind = null;
  7646. specifier.local = this.parseIdentifier();
  7647. }
  7648. } else {
  7649. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  7650. specifier.imported = this.parseIdentifier(true);
  7651. specifier.importKind = specifierTypeKind;
  7652. } else {
  7653. if (importedIsString) {
  7654. throw this.raise(Errors.ImportBindingIsString, specifier, {
  7655. importName: firstIdent.value
  7656. });
  7657. }
  7658. specifier.imported = firstIdent;
  7659. specifier.importKind = null;
  7660. }
  7661. if (this.eatContextual(93)) {
  7662. specifier.local = this.parseIdentifier();
  7663. } else {
  7664. isBinding = true;
  7665. specifier.local = this.cloneIdentifier(specifier.imported);
  7666. }
  7667. }
  7668. const specifierIsTypeImport = hasTypeImportKind(specifier);
  7669. if (isInTypeOnlyImport && specifierIsTypeImport) {
  7670. this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier);
  7671. }
  7672. if (isInTypeOnlyImport || specifierIsTypeImport) {
  7673. this.checkReservedType(specifier.local.name, specifier.local.loc.start, true);
  7674. }
  7675. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  7676. this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true);
  7677. }
  7678. return this.finishImportSpecifier(specifier, "ImportSpecifier");
  7679. }
  7680. parseBindingAtom() {
  7681. switch (this.state.type) {
  7682. case 78:
  7683. return this.parseIdentifier(true);
  7684. default:
  7685. return super.parseBindingAtom();
  7686. }
  7687. }
  7688. parseFunctionParams(node, isConstructor) {
  7689. const kind = node.kind;
  7690. if (kind !== "get" && kind !== "set" && this.match(47)) {
  7691. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7692. }
  7693. super.parseFunctionParams(node, isConstructor);
  7694. }
  7695. parseVarId(decl, kind) {
  7696. super.parseVarId(decl, kind);
  7697. if (this.match(14)) {
  7698. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  7699. this.resetEndLocation(decl.id);
  7700. }
  7701. }
  7702. parseAsyncArrowFromCallExpression(node, call) {
  7703. if (this.match(14)) {
  7704. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7705. this.state.noAnonFunctionType = true;
  7706. node.returnType = this.flowParseTypeAnnotation();
  7707. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7708. }
  7709. return super.parseAsyncArrowFromCallExpression(node, call);
  7710. }
  7711. shouldParseAsyncArrow() {
  7712. return this.match(14) || super.shouldParseAsyncArrow();
  7713. }
  7714. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  7715. var _jsx;
  7716. let state = null;
  7717. let jsx;
  7718. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  7719. state = this.state.clone();
  7720. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  7721. if (!jsx.error) return jsx.node;
  7722. const {
  7723. context
  7724. } = this.state;
  7725. const currentContext = context[context.length - 1];
  7726. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  7727. context.pop();
  7728. }
  7729. }
  7730. if ((_jsx = jsx) != null && _jsx.error || this.match(47)) {
  7731. var _jsx2, _jsx3;
  7732. state = state || this.state.clone();
  7733. let typeParameters;
  7734. const arrow = this.tryParse(abort => {
  7735. var _arrowExpression$extr;
  7736. typeParameters = this.flowParseTypeParameterDeclaration();
  7737. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  7738. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  7739. this.resetStartLocationFromNode(result, typeParameters);
  7740. return result;
  7741. });
  7742. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  7743. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  7744. if (expr.type !== "ArrowFunctionExpression") abort();
  7745. expr.typeParameters = typeParameters;
  7746. this.resetStartLocationFromNode(expr, typeParameters);
  7747. return arrowExpression;
  7748. }, state);
  7749. let arrowExpression = null;
  7750. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  7751. if (!arrow.error && !arrow.aborted) {
  7752. if (arrow.node.async) {
  7753. this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters);
  7754. }
  7755. return arrow.node;
  7756. }
  7757. arrowExpression = arrow.node;
  7758. }
  7759. if ((_jsx2 = jsx) != null && _jsx2.node) {
  7760. this.state = jsx.failState;
  7761. return jsx.node;
  7762. }
  7763. if (arrowExpression) {
  7764. this.state = arrow.failState;
  7765. return arrowExpression;
  7766. }
  7767. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  7768. if (arrow.thrown) throw arrow.error;
  7769. throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters);
  7770. }
  7771. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  7772. }
  7773. parseArrow(node) {
  7774. if (this.match(14)) {
  7775. const result = this.tryParse(() => {
  7776. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7777. this.state.noAnonFunctionType = true;
  7778. const typeNode = this.startNode();
  7779. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  7780. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7781. if (this.canInsertSemicolon()) this.unexpected();
  7782. if (!this.match(19)) this.unexpected();
  7783. return typeNode;
  7784. });
  7785. if (result.thrown) return null;
  7786. if (result.error) this.state = result.failState;
  7787. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  7788. }
  7789. return super.parseArrow(node);
  7790. }
  7791. shouldParseArrow(params) {
  7792. return this.match(14) || super.shouldParseArrow(params);
  7793. }
  7794. setArrowFunctionParameters(node, params) {
  7795. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  7796. node.params = params;
  7797. } else {
  7798. super.setArrowFunctionParameters(node, params);
  7799. }
  7800. }
  7801. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  7802. if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  7803. return;
  7804. }
  7805. for (let i = 0; i < node.params.length; i++) {
  7806. if (this.isThisParam(node.params[i]) && i > 0) {
  7807. this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]);
  7808. }
  7809. }
  7810. super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged);
  7811. }
  7812. parseParenAndDistinguishExpression(canBeArrow) {
  7813. return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)));
  7814. }
  7815. parseSubscripts(base, startLoc, noCalls) {
  7816. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) {
  7817. this.next();
  7818. const node = this.startNodeAt(startLoc);
  7819. node.callee = base;
  7820. node.arguments = super.parseCallExpressionArguments();
  7821. base = this.finishNode(node, "CallExpression");
  7822. } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) {
  7823. const state = this.state.clone();
  7824. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state);
  7825. if (!arrow.error && !arrow.aborted) return arrow.node;
  7826. const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state);
  7827. if (result.node && !result.error) return result.node;
  7828. if (arrow.node) {
  7829. this.state = arrow.failState;
  7830. return arrow.node;
  7831. }
  7832. if (result.node) {
  7833. this.state = result.failState;
  7834. return result.node;
  7835. }
  7836. throw arrow.error || result.error;
  7837. }
  7838. return super.parseSubscripts(base, startLoc, noCalls);
  7839. }
  7840. parseSubscript(base, startLoc, noCalls, subscriptState) {
  7841. if (this.match(18) && this.isLookaheadToken_lt()) {
  7842. subscriptState.optionalChainMember = true;
  7843. if (noCalls) {
  7844. subscriptState.stop = true;
  7845. return base;
  7846. }
  7847. this.next();
  7848. const node = this.startNodeAt(startLoc);
  7849. node.callee = base;
  7850. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  7851. this.expect(10);
  7852. node.arguments = this.parseCallExpressionArguments();
  7853. node.optional = true;
  7854. return this.finishCallExpression(node, true);
  7855. } else if (!noCalls && this.shouldParseTypes() && (this.match(47) || this.match(51))) {
  7856. const node = this.startNodeAt(startLoc);
  7857. node.callee = base;
  7858. const result = this.tryParse(() => {
  7859. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  7860. this.expect(10);
  7861. node.arguments = super.parseCallExpressionArguments();
  7862. if (subscriptState.optionalChainMember) {
  7863. node.optional = false;
  7864. }
  7865. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  7866. });
  7867. if (result.node) {
  7868. if (result.error) this.state = result.failState;
  7869. return result.node;
  7870. }
  7871. }
  7872. return super.parseSubscript(base, startLoc, noCalls, subscriptState);
  7873. }
  7874. parseNewCallee(node) {
  7875. super.parseNewCallee(node);
  7876. let targs = null;
  7877. if (this.shouldParseTypes() && this.match(47)) {
  7878. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  7879. }
  7880. node.typeArguments = targs;
  7881. }
  7882. parseAsyncArrowWithTypeParameters(startLoc) {
  7883. const node = this.startNodeAt(startLoc);
  7884. this.parseFunctionParams(node, false);
  7885. if (!this.parseArrow(node)) return;
  7886. return super.parseArrowExpression(node, undefined, true);
  7887. }
  7888. readToken_mult_modulo(code) {
  7889. const next = this.input.charCodeAt(this.state.pos + 1);
  7890. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  7891. this.state.hasFlowComment = false;
  7892. this.state.pos += 2;
  7893. this.nextToken();
  7894. return;
  7895. }
  7896. super.readToken_mult_modulo(code);
  7897. }
  7898. readToken_pipe_amp(code) {
  7899. const next = this.input.charCodeAt(this.state.pos + 1);
  7900. if (code === 124 && next === 125) {
  7901. this.finishOp(9, 2);
  7902. return;
  7903. }
  7904. super.readToken_pipe_amp(code);
  7905. }
  7906. parseTopLevel(file, program) {
  7907. const fileNode = super.parseTopLevel(file, program);
  7908. if (this.state.hasFlowComment) {
  7909. this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition());
  7910. }
  7911. return fileNode;
  7912. }
  7913. skipBlockComment() {
  7914. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  7915. if (this.state.hasFlowComment) {
  7916. throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc);
  7917. }
  7918. this.hasFlowCommentCompletion();
  7919. const commentSkip = this.skipFlowComment();
  7920. if (commentSkip) {
  7921. this.state.pos += commentSkip;
  7922. this.state.hasFlowComment = true;
  7923. }
  7924. return;
  7925. }
  7926. return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/");
  7927. }
  7928. skipFlowComment() {
  7929. const {
  7930. pos
  7931. } = this.state;
  7932. let shiftToFirstNonWhiteSpace = 2;
  7933. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  7934. shiftToFirstNonWhiteSpace++;
  7935. }
  7936. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  7937. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  7938. if (ch2 === 58 && ch3 === 58) {
  7939. return shiftToFirstNonWhiteSpace + 2;
  7940. }
  7941. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  7942. return shiftToFirstNonWhiteSpace + 12;
  7943. }
  7944. if (ch2 === 58 && ch3 !== 58) {
  7945. return shiftToFirstNonWhiteSpace;
  7946. }
  7947. return false;
  7948. }
  7949. hasFlowCommentCompletion() {
  7950. const end = this.input.indexOf("*/", this.state.pos);
  7951. if (end === -1) {
  7952. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  7953. }
  7954. }
  7955. flowEnumErrorBooleanMemberNotInitialized(loc, {
  7956. enumName,
  7957. memberName
  7958. }) {
  7959. this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, {
  7960. memberName,
  7961. enumName
  7962. });
  7963. }
  7964. flowEnumErrorInvalidMemberInitializer(loc, enumContext) {
  7965. return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext);
  7966. }
  7967. flowEnumErrorNumberMemberNotInitialized(loc, details) {
  7968. this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details);
  7969. }
  7970. flowEnumErrorStringMemberInconsistentlyInitialized(node, details) {
  7971. this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details);
  7972. }
  7973. flowEnumMemberInit() {
  7974. const startLoc = this.state.startLoc;
  7975. const endOfInit = () => this.match(12) || this.match(8);
  7976. switch (this.state.type) {
  7977. case 135:
  7978. {
  7979. const literal = this.parseNumericLiteral(this.state.value);
  7980. if (endOfInit()) {
  7981. return {
  7982. type: "number",
  7983. loc: literal.loc.start,
  7984. value: literal
  7985. };
  7986. }
  7987. return {
  7988. type: "invalid",
  7989. loc: startLoc
  7990. };
  7991. }
  7992. case 134:
  7993. {
  7994. const literal = this.parseStringLiteral(this.state.value);
  7995. if (endOfInit()) {
  7996. return {
  7997. type: "string",
  7998. loc: literal.loc.start,
  7999. value: literal
  8000. };
  8001. }
  8002. return {
  8003. type: "invalid",
  8004. loc: startLoc
  8005. };
  8006. }
  8007. case 85:
  8008. case 86:
  8009. {
  8010. const literal = this.parseBooleanLiteral(this.match(85));
  8011. if (endOfInit()) {
  8012. return {
  8013. type: "boolean",
  8014. loc: literal.loc.start,
  8015. value: literal
  8016. };
  8017. }
  8018. return {
  8019. type: "invalid",
  8020. loc: startLoc
  8021. };
  8022. }
  8023. default:
  8024. return {
  8025. type: "invalid",
  8026. loc: startLoc
  8027. };
  8028. }
  8029. }
  8030. flowEnumMemberRaw() {
  8031. const loc = this.state.startLoc;
  8032. const id = this.parseIdentifier(true);
  8033. const init = this.eat(29) ? this.flowEnumMemberInit() : {
  8034. type: "none",
  8035. loc
  8036. };
  8037. return {
  8038. id,
  8039. init
  8040. };
  8041. }
  8042. flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) {
  8043. const {
  8044. explicitType
  8045. } = context;
  8046. if (explicitType === null) {
  8047. return;
  8048. }
  8049. if (explicitType !== expectedType) {
  8050. this.flowEnumErrorInvalidMemberInitializer(loc, context);
  8051. }
  8052. }
  8053. flowEnumMembers({
  8054. enumName,
  8055. explicitType
  8056. }) {
  8057. const seenNames = new Set();
  8058. const members = {
  8059. booleanMembers: [],
  8060. numberMembers: [],
  8061. stringMembers: [],
  8062. defaultedMembers: []
  8063. };
  8064. let hasUnknownMembers = false;
  8065. while (!this.match(8)) {
  8066. if (this.eat(21)) {
  8067. hasUnknownMembers = true;
  8068. break;
  8069. }
  8070. const memberNode = this.startNode();
  8071. const {
  8072. id,
  8073. init
  8074. } = this.flowEnumMemberRaw();
  8075. const memberName = id.name;
  8076. if (memberName === "") {
  8077. continue;
  8078. }
  8079. if (/^[a-z]/.test(memberName)) {
  8080. this.raise(FlowErrors.EnumInvalidMemberName, id, {
  8081. memberName,
  8082. suggestion: memberName[0].toUpperCase() + memberName.slice(1),
  8083. enumName
  8084. });
  8085. }
  8086. if (seenNames.has(memberName)) {
  8087. this.raise(FlowErrors.EnumDuplicateMemberName, id, {
  8088. memberName,
  8089. enumName
  8090. });
  8091. }
  8092. seenNames.add(memberName);
  8093. const context = {
  8094. enumName,
  8095. explicitType,
  8096. memberName
  8097. };
  8098. memberNode.id = id;
  8099. switch (init.type) {
  8100. case "boolean":
  8101. {
  8102. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean");
  8103. memberNode.init = init.value;
  8104. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  8105. break;
  8106. }
  8107. case "number":
  8108. {
  8109. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number");
  8110. memberNode.init = init.value;
  8111. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  8112. break;
  8113. }
  8114. case "string":
  8115. {
  8116. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string");
  8117. memberNode.init = init.value;
  8118. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  8119. break;
  8120. }
  8121. case "invalid":
  8122. {
  8123. throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);
  8124. }
  8125. case "none":
  8126. {
  8127. switch (explicitType) {
  8128. case "boolean":
  8129. this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context);
  8130. break;
  8131. case "number":
  8132. this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);
  8133. break;
  8134. default:
  8135. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  8136. }
  8137. }
  8138. }
  8139. if (!this.match(8)) {
  8140. this.expect(12);
  8141. }
  8142. }
  8143. return {
  8144. members,
  8145. hasUnknownMembers
  8146. };
  8147. }
  8148. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  8149. enumName
  8150. }) {
  8151. if (initializedMembers.length === 0) {
  8152. return defaultedMembers;
  8153. } else if (defaultedMembers.length === 0) {
  8154. return initializedMembers;
  8155. } else if (defaultedMembers.length > initializedMembers.length) {
  8156. for (const member of initializedMembers) {
  8157. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  8158. enumName
  8159. });
  8160. }
  8161. return defaultedMembers;
  8162. } else {
  8163. for (const member of defaultedMembers) {
  8164. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  8165. enumName
  8166. });
  8167. }
  8168. return initializedMembers;
  8169. }
  8170. }
  8171. flowEnumParseExplicitType({
  8172. enumName
  8173. }) {
  8174. if (!this.eatContextual(102)) return null;
  8175. if (!tokenIsIdentifier(this.state.type)) {
  8176. throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, {
  8177. enumName
  8178. });
  8179. }
  8180. const {
  8181. value
  8182. } = this.state;
  8183. this.next();
  8184. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  8185. this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, {
  8186. enumName,
  8187. invalidEnumType: value
  8188. });
  8189. }
  8190. return value;
  8191. }
  8192. flowEnumBody(node, id) {
  8193. const enumName = id.name;
  8194. const nameLoc = id.loc.start;
  8195. const explicitType = this.flowEnumParseExplicitType({
  8196. enumName
  8197. });
  8198. this.expect(5);
  8199. const {
  8200. members,
  8201. hasUnknownMembers
  8202. } = this.flowEnumMembers({
  8203. enumName,
  8204. explicitType
  8205. });
  8206. node.hasUnknownMembers = hasUnknownMembers;
  8207. switch (explicitType) {
  8208. case "boolean":
  8209. node.explicitType = true;
  8210. node.members = members.booleanMembers;
  8211. this.expect(8);
  8212. return this.finishNode(node, "EnumBooleanBody");
  8213. case "number":
  8214. node.explicitType = true;
  8215. node.members = members.numberMembers;
  8216. this.expect(8);
  8217. return this.finishNode(node, "EnumNumberBody");
  8218. case "string":
  8219. node.explicitType = true;
  8220. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  8221. enumName
  8222. });
  8223. this.expect(8);
  8224. return this.finishNode(node, "EnumStringBody");
  8225. case "symbol":
  8226. node.members = members.defaultedMembers;
  8227. this.expect(8);
  8228. return this.finishNode(node, "EnumSymbolBody");
  8229. default:
  8230. {
  8231. const empty = () => {
  8232. node.members = [];
  8233. this.expect(8);
  8234. return this.finishNode(node, "EnumStringBody");
  8235. };
  8236. node.explicitType = false;
  8237. const boolsLen = members.booleanMembers.length;
  8238. const numsLen = members.numberMembers.length;
  8239. const strsLen = members.stringMembers.length;
  8240. const defaultedLen = members.defaultedMembers.length;
  8241. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  8242. return empty();
  8243. } else if (!boolsLen && !numsLen) {
  8244. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  8245. enumName
  8246. });
  8247. this.expect(8);
  8248. return this.finishNode(node, "EnumStringBody");
  8249. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  8250. for (const member of members.defaultedMembers) {
  8251. this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {
  8252. enumName,
  8253. memberName: member.id.name
  8254. });
  8255. }
  8256. node.members = members.booleanMembers;
  8257. this.expect(8);
  8258. return this.finishNode(node, "EnumBooleanBody");
  8259. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  8260. for (const member of members.defaultedMembers) {
  8261. this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {
  8262. enumName,
  8263. memberName: member.id.name
  8264. });
  8265. }
  8266. node.members = members.numberMembers;
  8267. this.expect(8);
  8268. return this.finishNode(node, "EnumNumberBody");
  8269. } else {
  8270. this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, {
  8271. enumName
  8272. });
  8273. return empty();
  8274. }
  8275. }
  8276. }
  8277. }
  8278. flowParseEnumDeclaration(node) {
  8279. const id = this.parseIdentifier();
  8280. node.id = id;
  8281. node.body = this.flowEnumBody(this.startNode(), id);
  8282. return this.finishNode(node, "EnumDeclaration");
  8283. }
  8284. jsxParseOpeningElementAfterName(node) {
  8285. if (this.shouldParseTypes()) {
  8286. if (this.match(47) || this.match(51)) {
  8287. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  8288. }
  8289. }
  8290. return super.jsxParseOpeningElementAfterName(node);
  8291. }
  8292. isLookaheadToken_lt() {
  8293. const next = this.nextTokenStart();
  8294. if (this.input.charCodeAt(next) === 60) {
  8295. const afterNext = this.input.charCodeAt(next + 1);
  8296. return afterNext !== 60 && afterNext !== 61;
  8297. }
  8298. return false;
  8299. }
  8300. reScan_lt_gt() {
  8301. const {
  8302. type
  8303. } = this.state;
  8304. if (type === 47) {
  8305. this.state.pos -= 1;
  8306. this.readToken_lt();
  8307. } else if (type === 48) {
  8308. this.state.pos -= 1;
  8309. this.readToken_gt();
  8310. }
  8311. }
  8312. reScan_lt() {
  8313. const {
  8314. type
  8315. } = this.state;
  8316. if (type === 51) {
  8317. this.state.pos -= 2;
  8318. this.finishOp(47, 1);
  8319. return 47;
  8320. }
  8321. return type;
  8322. }
  8323. maybeUnwrapTypeCastExpression(node) {
  8324. return node.type === "TypeCastExpression" ? node.expression : node;
  8325. }
  8326. };
  8327. const entities = {
  8328. __proto__: null,
  8329. quot: "\u0022",
  8330. amp: "&",
  8331. apos: "\u0027",
  8332. lt: "<",
  8333. gt: ">",
  8334. nbsp: "\u00A0",
  8335. iexcl: "\u00A1",
  8336. cent: "\u00A2",
  8337. pound: "\u00A3",
  8338. curren: "\u00A4",
  8339. yen: "\u00A5",
  8340. brvbar: "\u00A6",
  8341. sect: "\u00A7",
  8342. uml: "\u00A8",
  8343. copy: "\u00A9",
  8344. ordf: "\u00AA",
  8345. laquo: "\u00AB",
  8346. not: "\u00AC",
  8347. shy: "\u00AD",
  8348. reg: "\u00AE",
  8349. macr: "\u00AF",
  8350. deg: "\u00B0",
  8351. plusmn: "\u00B1",
  8352. sup2: "\u00B2",
  8353. sup3: "\u00B3",
  8354. acute: "\u00B4",
  8355. micro: "\u00B5",
  8356. para: "\u00B6",
  8357. middot: "\u00B7",
  8358. cedil: "\u00B8",
  8359. sup1: "\u00B9",
  8360. ordm: "\u00BA",
  8361. raquo: "\u00BB",
  8362. frac14: "\u00BC",
  8363. frac12: "\u00BD",
  8364. frac34: "\u00BE",
  8365. iquest: "\u00BF",
  8366. Agrave: "\u00C0",
  8367. Aacute: "\u00C1",
  8368. Acirc: "\u00C2",
  8369. Atilde: "\u00C3",
  8370. Auml: "\u00C4",
  8371. Aring: "\u00C5",
  8372. AElig: "\u00C6",
  8373. Ccedil: "\u00C7",
  8374. Egrave: "\u00C8",
  8375. Eacute: "\u00C9",
  8376. Ecirc: "\u00CA",
  8377. Euml: "\u00CB",
  8378. Igrave: "\u00CC",
  8379. Iacute: "\u00CD",
  8380. Icirc: "\u00CE",
  8381. Iuml: "\u00CF",
  8382. ETH: "\u00D0",
  8383. Ntilde: "\u00D1",
  8384. Ograve: "\u00D2",
  8385. Oacute: "\u00D3",
  8386. Ocirc: "\u00D4",
  8387. Otilde: "\u00D5",
  8388. Ouml: "\u00D6",
  8389. times: "\u00D7",
  8390. Oslash: "\u00D8",
  8391. Ugrave: "\u00D9",
  8392. Uacute: "\u00DA",
  8393. Ucirc: "\u00DB",
  8394. Uuml: "\u00DC",
  8395. Yacute: "\u00DD",
  8396. THORN: "\u00DE",
  8397. szlig: "\u00DF",
  8398. agrave: "\u00E0",
  8399. aacute: "\u00E1",
  8400. acirc: "\u00E2",
  8401. atilde: "\u00E3",
  8402. auml: "\u00E4",
  8403. aring: "\u00E5",
  8404. aelig: "\u00E6",
  8405. ccedil: "\u00E7",
  8406. egrave: "\u00E8",
  8407. eacute: "\u00E9",
  8408. ecirc: "\u00EA",
  8409. euml: "\u00EB",
  8410. igrave: "\u00EC",
  8411. iacute: "\u00ED",
  8412. icirc: "\u00EE",
  8413. iuml: "\u00EF",
  8414. eth: "\u00F0",
  8415. ntilde: "\u00F1",
  8416. ograve: "\u00F2",
  8417. oacute: "\u00F3",
  8418. ocirc: "\u00F4",
  8419. otilde: "\u00F5",
  8420. ouml: "\u00F6",
  8421. divide: "\u00F7",
  8422. oslash: "\u00F8",
  8423. ugrave: "\u00F9",
  8424. uacute: "\u00FA",
  8425. ucirc: "\u00FB",
  8426. uuml: "\u00FC",
  8427. yacute: "\u00FD",
  8428. thorn: "\u00FE",
  8429. yuml: "\u00FF",
  8430. OElig: "\u0152",
  8431. oelig: "\u0153",
  8432. Scaron: "\u0160",
  8433. scaron: "\u0161",
  8434. Yuml: "\u0178",
  8435. fnof: "\u0192",
  8436. circ: "\u02C6",
  8437. tilde: "\u02DC",
  8438. Alpha: "\u0391",
  8439. Beta: "\u0392",
  8440. Gamma: "\u0393",
  8441. Delta: "\u0394",
  8442. Epsilon: "\u0395",
  8443. Zeta: "\u0396",
  8444. Eta: "\u0397",
  8445. Theta: "\u0398",
  8446. Iota: "\u0399",
  8447. Kappa: "\u039A",
  8448. Lambda: "\u039B",
  8449. Mu: "\u039C",
  8450. Nu: "\u039D",
  8451. Xi: "\u039E",
  8452. Omicron: "\u039F",
  8453. Pi: "\u03A0",
  8454. Rho: "\u03A1",
  8455. Sigma: "\u03A3",
  8456. Tau: "\u03A4",
  8457. Upsilon: "\u03A5",
  8458. Phi: "\u03A6",
  8459. Chi: "\u03A7",
  8460. Psi: "\u03A8",
  8461. Omega: "\u03A9",
  8462. alpha: "\u03B1",
  8463. beta: "\u03B2",
  8464. gamma: "\u03B3",
  8465. delta: "\u03B4",
  8466. epsilon: "\u03B5",
  8467. zeta: "\u03B6",
  8468. eta: "\u03B7",
  8469. theta: "\u03B8",
  8470. iota: "\u03B9",
  8471. kappa: "\u03BA",
  8472. lambda: "\u03BB",
  8473. mu: "\u03BC",
  8474. nu: "\u03BD",
  8475. xi: "\u03BE",
  8476. omicron: "\u03BF",
  8477. pi: "\u03C0",
  8478. rho: "\u03C1",
  8479. sigmaf: "\u03C2",
  8480. sigma: "\u03C3",
  8481. tau: "\u03C4",
  8482. upsilon: "\u03C5",
  8483. phi: "\u03C6",
  8484. chi: "\u03C7",
  8485. psi: "\u03C8",
  8486. omega: "\u03C9",
  8487. thetasym: "\u03D1",
  8488. upsih: "\u03D2",
  8489. piv: "\u03D6",
  8490. ensp: "\u2002",
  8491. emsp: "\u2003",
  8492. thinsp: "\u2009",
  8493. zwnj: "\u200C",
  8494. zwj: "\u200D",
  8495. lrm: "\u200E",
  8496. rlm: "\u200F",
  8497. ndash: "\u2013",
  8498. mdash: "\u2014",
  8499. lsquo: "\u2018",
  8500. rsquo: "\u2019",
  8501. sbquo: "\u201A",
  8502. ldquo: "\u201C",
  8503. rdquo: "\u201D",
  8504. bdquo: "\u201E",
  8505. dagger: "\u2020",
  8506. Dagger: "\u2021",
  8507. bull: "\u2022",
  8508. hellip: "\u2026",
  8509. permil: "\u2030",
  8510. prime: "\u2032",
  8511. Prime: "\u2033",
  8512. lsaquo: "\u2039",
  8513. rsaquo: "\u203A",
  8514. oline: "\u203E",
  8515. frasl: "\u2044",
  8516. euro: "\u20AC",
  8517. image: "\u2111",
  8518. weierp: "\u2118",
  8519. real: "\u211C",
  8520. trade: "\u2122",
  8521. alefsym: "\u2135",
  8522. larr: "\u2190",
  8523. uarr: "\u2191",
  8524. rarr: "\u2192",
  8525. darr: "\u2193",
  8526. harr: "\u2194",
  8527. crarr: "\u21B5",
  8528. lArr: "\u21D0",
  8529. uArr: "\u21D1",
  8530. rArr: "\u21D2",
  8531. dArr: "\u21D3",
  8532. hArr: "\u21D4",
  8533. forall: "\u2200",
  8534. part: "\u2202",
  8535. exist: "\u2203",
  8536. empty: "\u2205",
  8537. nabla: "\u2207",
  8538. isin: "\u2208",
  8539. notin: "\u2209",
  8540. ni: "\u220B",
  8541. prod: "\u220F",
  8542. sum: "\u2211",
  8543. minus: "\u2212",
  8544. lowast: "\u2217",
  8545. radic: "\u221A",
  8546. prop: "\u221D",
  8547. infin: "\u221E",
  8548. ang: "\u2220",
  8549. and: "\u2227",
  8550. or: "\u2228",
  8551. cap: "\u2229",
  8552. cup: "\u222A",
  8553. int: "\u222B",
  8554. there4: "\u2234",
  8555. sim: "\u223C",
  8556. cong: "\u2245",
  8557. asymp: "\u2248",
  8558. ne: "\u2260",
  8559. equiv: "\u2261",
  8560. le: "\u2264",
  8561. ge: "\u2265",
  8562. sub: "\u2282",
  8563. sup: "\u2283",
  8564. nsub: "\u2284",
  8565. sube: "\u2286",
  8566. supe: "\u2287",
  8567. oplus: "\u2295",
  8568. otimes: "\u2297",
  8569. perp: "\u22A5",
  8570. sdot: "\u22C5",
  8571. lceil: "\u2308",
  8572. rceil: "\u2309",
  8573. lfloor: "\u230A",
  8574. rfloor: "\u230B",
  8575. lang: "\u2329",
  8576. rang: "\u232A",
  8577. loz: "\u25CA",
  8578. spades: "\u2660",
  8579. clubs: "\u2663",
  8580. hearts: "\u2665",
  8581. diams: "\u2666"
  8582. };
  8583. const lineBreak = /\r\n|[\r\n\u2028\u2029]/;
  8584. const lineBreakG = new RegExp(lineBreak.source, "g");
  8585. function isNewLine(code) {
  8586. switch (code) {
  8587. case 10:
  8588. case 13:
  8589. case 8232:
  8590. case 8233:
  8591. return true;
  8592. default:
  8593. return false;
  8594. }
  8595. }
  8596. function hasNewLine(input, start, end) {
  8597. for (let i = start; i < end; i++) {
  8598. if (isNewLine(input.charCodeAt(i))) {
  8599. return true;
  8600. }
  8601. }
  8602. return false;
  8603. }
  8604. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  8605. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;
  8606. function isWhitespace(code) {
  8607. switch (code) {
  8608. case 0x0009:
  8609. case 0x000b:
  8610. case 0x000c:
  8611. case 32:
  8612. case 160:
  8613. case 5760:
  8614. case 0x2000:
  8615. case 0x2001:
  8616. case 0x2002:
  8617. case 0x2003:
  8618. case 0x2004:
  8619. case 0x2005:
  8620. case 0x2006:
  8621. case 0x2007:
  8622. case 0x2008:
  8623. case 0x2009:
  8624. case 0x200a:
  8625. case 0x202f:
  8626. case 0x205f:
  8627. case 0x3000:
  8628. case 0xfeff:
  8629. return true;
  8630. default:
  8631. return false;
  8632. }
  8633. }
  8634. const JsxErrors = ParseErrorEnum`jsx`({
  8635. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  8636. MissingClosingTagElement: ({
  8637. openingTagName
  8638. }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`,
  8639. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  8640. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  8641. UnexpectedToken: ({
  8642. unexpected,
  8643. HTMLEntity
  8644. }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`,
  8645. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  8646. UnterminatedJsxContent: "Unterminated JSX contents.",
  8647. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  8648. });
  8649. function isFragment(object) {
  8650. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  8651. }
  8652. function getQualifiedJSXName(object) {
  8653. if (object.type === "JSXIdentifier") {
  8654. return object.name;
  8655. }
  8656. if (object.type === "JSXNamespacedName") {
  8657. return object.namespace.name + ":" + object.name.name;
  8658. }
  8659. if (object.type === "JSXMemberExpression") {
  8660. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  8661. }
  8662. throw new Error("Node had unexpected type: " + object.type);
  8663. }
  8664. var jsx = superClass => class JSXParserMixin extends superClass {
  8665. jsxReadToken() {
  8666. let out = "";
  8667. let chunkStart = this.state.pos;
  8668. for (;;) {
  8669. if (this.state.pos >= this.length) {
  8670. throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc);
  8671. }
  8672. const ch = this.input.charCodeAt(this.state.pos);
  8673. switch (ch) {
  8674. case 60:
  8675. case 123:
  8676. if (this.state.pos === this.state.start) {
  8677. if (ch === 60 && this.state.canStartJSXElement) {
  8678. ++this.state.pos;
  8679. this.finishToken(143);
  8680. } else {
  8681. super.getTokenFromCode(ch);
  8682. }
  8683. return;
  8684. }
  8685. out += this.input.slice(chunkStart, this.state.pos);
  8686. this.finishToken(142, out);
  8687. return;
  8688. case 38:
  8689. out += this.input.slice(chunkStart, this.state.pos);
  8690. out += this.jsxReadEntity();
  8691. chunkStart = this.state.pos;
  8692. break;
  8693. case 62:
  8694. case 125:
  8695. default:
  8696. if (isNewLine(ch)) {
  8697. out += this.input.slice(chunkStart, this.state.pos);
  8698. out += this.jsxReadNewLine(true);
  8699. chunkStart = this.state.pos;
  8700. } else {
  8701. ++this.state.pos;
  8702. }
  8703. }
  8704. }
  8705. }
  8706. jsxReadNewLine(normalizeCRLF) {
  8707. const ch = this.input.charCodeAt(this.state.pos);
  8708. let out;
  8709. ++this.state.pos;
  8710. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  8711. ++this.state.pos;
  8712. out = normalizeCRLF ? "\n" : "\r\n";
  8713. } else {
  8714. out = String.fromCharCode(ch);
  8715. }
  8716. ++this.state.curLine;
  8717. this.state.lineStart = this.state.pos;
  8718. return out;
  8719. }
  8720. jsxReadString(quote) {
  8721. let out = "";
  8722. let chunkStart = ++this.state.pos;
  8723. for (;;) {
  8724. if (this.state.pos >= this.length) {
  8725. throw this.raise(Errors.UnterminatedString, this.state.startLoc);
  8726. }
  8727. const ch = this.input.charCodeAt(this.state.pos);
  8728. if (ch === quote) break;
  8729. if (ch === 38) {
  8730. out += this.input.slice(chunkStart, this.state.pos);
  8731. out += this.jsxReadEntity();
  8732. chunkStart = this.state.pos;
  8733. } else if (isNewLine(ch)) {
  8734. out += this.input.slice(chunkStart, this.state.pos);
  8735. out += this.jsxReadNewLine(false);
  8736. chunkStart = this.state.pos;
  8737. } else {
  8738. ++this.state.pos;
  8739. }
  8740. }
  8741. out += this.input.slice(chunkStart, this.state.pos++);
  8742. this.finishToken(134, out);
  8743. }
  8744. jsxReadEntity() {
  8745. const startPos = ++this.state.pos;
  8746. if (this.codePointAtPos(this.state.pos) === 35) {
  8747. ++this.state.pos;
  8748. let radix = 10;
  8749. if (this.codePointAtPos(this.state.pos) === 120) {
  8750. radix = 16;
  8751. ++this.state.pos;
  8752. }
  8753. const codePoint = this.readInt(radix, undefined, false, "bail");
  8754. if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) {
  8755. ++this.state.pos;
  8756. return String.fromCodePoint(codePoint);
  8757. }
  8758. } else {
  8759. let count = 0;
  8760. let semi = false;
  8761. while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) === 59)) {
  8762. ++this.state.pos;
  8763. }
  8764. if (semi) {
  8765. const desc = this.input.slice(startPos, this.state.pos);
  8766. const entity = entities[desc];
  8767. ++this.state.pos;
  8768. if (entity) {
  8769. return entity;
  8770. }
  8771. }
  8772. }
  8773. this.state.pos = startPos;
  8774. return "&";
  8775. }
  8776. jsxReadWord() {
  8777. let ch;
  8778. const start = this.state.pos;
  8779. do {
  8780. ch = this.input.charCodeAt(++this.state.pos);
  8781. } while (isIdentifierChar(ch) || ch === 45);
  8782. this.finishToken(141, this.input.slice(start, this.state.pos));
  8783. }
  8784. jsxParseIdentifier() {
  8785. const node = this.startNode();
  8786. if (this.match(141)) {
  8787. node.name = this.state.value;
  8788. } else if (tokenIsKeyword(this.state.type)) {
  8789. node.name = tokenLabelName(this.state.type);
  8790. } else {
  8791. this.unexpected();
  8792. }
  8793. this.next();
  8794. return this.finishNode(node, "JSXIdentifier");
  8795. }
  8796. jsxParseNamespacedName() {
  8797. const startLoc = this.state.startLoc;
  8798. const name = this.jsxParseIdentifier();
  8799. if (!this.eat(14)) return name;
  8800. const node = this.startNodeAt(startLoc);
  8801. node.namespace = name;
  8802. node.name = this.jsxParseIdentifier();
  8803. return this.finishNode(node, "JSXNamespacedName");
  8804. }
  8805. jsxParseElementName() {
  8806. const startLoc = this.state.startLoc;
  8807. let node = this.jsxParseNamespacedName();
  8808. if (node.type === "JSXNamespacedName") {
  8809. return node;
  8810. }
  8811. while (this.eat(16)) {
  8812. const newNode = this.startNodeAt(startLoc);
  8813. newNode.object = node;
  8814. newNode.property = this.jsxParseIdentifier();
  8815. node = this.finishNode(newNode, "JSXMemberExpression");
  8816. }
  8817. return node;
  8818. }
  8819. jsxParseAttributeValue() {
  8820. let node;
  8821. switch (this.state.type) {
  8822. case 5:
  8823. node = this.startNode();
  8824. this.setContext(types.brace);
  8825. this.next();
  8826. node = this.jsxParseExpressionContainer(node, types.j_oTag);
  8827. if (node.expression.type === "JSXEmptyExpression") {
  8828. this.raise(JsxErrors.AttributeIsEmpty, node);
  8829. }
  8830. return node;
  8831. case 143:
  8832. case 134:
  8833. return this.parseExprAtom();
  8834. default:
  8835. throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc);
  8836. }
  8837. }
  8838. jsxParseEmptyExpression() {
  8839. const node = this.startNodeAt(this.state.lastTokEndLoc);
  8840. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc);
  8841. }
  8842. jsxParseSpreadChild(node) {
  8843. this.next();
  8844. node.expression = this.parseExpression();
  8845. this.setContext(types.j_expr);
  8846. this.state.canStartJSXElement = true;
  8847. this.expect(8);
  8848. return this.finishNode(node, "JSXSpreadChild");
  8849. }
  8850. jsxParseExpressionContainer(node, previousContext) {
  8851. if (this.match(8)) {
  8852. node.expression = this.jsxParseEmptyExpression();
  8853. } else {
  8854. const expression = this.parseExpression();
  8855. node.expression = expression;
  8856. }
  8857. this.setContext(previousContext);
  8858. this.state.canStartJSXElement = true;
  8859. this.expect(8);
  8860. return this.finishNode(node, "JSXExpressionContainer");
  8861. }
  8862. jsxParseAttribute() {
  8863. const node = this.startNode();
  8864. if (this.match(5)) {
  8865. this.setContext(types.brace);
  8866. this.next();
  8867. this.expect(21);
  8868. node.argument = this.parseMaybeAssignAllowIn();
  8869. this.setContext(types.j_oTag);
  8870. this.state.canStartJSXElement = true;
  8871. this.expect(8);
  8872. return this.finishNode(node, "JSXSpreadAttribute");
  8873. }
  8874. node.name = this.jsxParseNamespacedName();
  8875. node.value = this.eat(29) ? this.jsxParseAttributeValue() : null;
  8876. return this.finishNode(node, "JSXAttribute");
  8877. }
  8878. jsxParseOpeningElementAt(startLoc) {
  8879. const node = this.startNodeAt(startLoc);
  8880. if (this.eat(144)) {
  8881. return this.finishNode(node, "JSXOpeningFragment");
  8882. }
  8883. node.name = this.jsxParseElementName();
  8884. return this.jsxParseOpeningElementAfterName(node);
  8885. }
  8886. jsxParseOpeningElementAfterName(node) {
  8887. const attributes = [];
  8888. while (!this.match(56) && !this.match(144)) {
  8889. attributes.push(this.jsxParseAttribute());
  8890. }
  8891. node.attributes = attributes;
  8892. node.selfClosing = this.eat(56);
  8893. this.expect(144);
  8894. return this.finishNode(node, "JSXOpeningElement");
  8895. }
  8896. jsxParseClosingElementAt(startLoc) {
  8897. const node = this.startNodeAt(startLoc);
  8898. if (this.eat(144)) {
  8899. return this.finishNode(node, "JSXClosingFragment");
  8900. }
  8901. node.name = this.jsxParseElementName();
  8902. this.expect(144);
  8903. return this.finishNode(node, "JSXClosingElement");
  8904. }
  8905. jsxParseElementAt(startLoc) {
  8906. const node = this.startNodeAt(startLoc);
  8907. const children = [];
  8908. const openingElement = this.jsxParseOpeningElementAt(startLoc);
  8909. let closingElement = null;
  8910. if (!openingElement.selfClosing) {
  8911. contents: for (;;) {
  8912. switch (this.state.type) {
  8913. case 143:
  8914. startLoc = this.state.startLoc;
  8915. this.next();
  8916. if (this.eat(56)) {
  8917. closingElement = this.jsxParseClosingElementAt(startLoc);
  8918. break contents;
  8919. }
  8920. children.push(this.jsxParseElementAt(startLoc));
  8921. break;
  8922. case 142:
  8923. children.push(this.parseLiteral(this.state.value, "JSXText"));
  8924. break;
  8925. case 5:
  8926. {
  8927. const node = this.startNode();
  8928. this.setContext(types.brace);
  8929. this.next();
  8930. if (this.match(21)) {
  8931. children.push(this.jsxParseSpreadChild(node));
  8932. } else {
  8933. children.push(this.jsxParseExpressionContainer(node, types.j_expr));
  8934. }
  8935. break;
  8936. }
  8937. default:
  8938. this.unexpected();
  8939. }
  8940. }
  8941. if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) {
  8942. this.raise(JsxErrors.MissingClosingTagFragment, closingElement);
  8943. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  8944. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  8945. openingTagName: getQualifiedJSXName(openingElement.name)
  8946. });
  8947. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  8948. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  8949. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  8950. openingTagName: getQualifiedJSXName(openingElement.name)
  8951. });
  8952. }
  8953. }
  8954. }
  8955. if (isFragment(openingElement)) {
  8956. node.openingFragment = openingElement;
  8957. node.closingFragment = closingElement;
  8958. } else {
  8959. node.openingElement = openingElement;
  8960. node.closingElement = closingElement;
  8961. }
  8962. node.children = children;
  8963. if (this.match(47)) {
  8964. throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc);
  8965. }
  8966. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  8967. }
  8968. jsxParseElement() {
  8969. const startLoc = this.state.startLoc;
  8970. this.next();
  8971. return this.jsxParseElementAt(startLoc);
  8972. }
  8973. setContext(newContext) {
  8974. const {
  8975. context
  8976. } = this.state;
  8977. context[context.length - 1] = newContext;
  8978. }
  8979. parseExprAtom(refExpressionErrors) {
  8980. if (this.match(143)) {
  8981. return this.jsxParseElement();
  8982. } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) {
  8983. this.replaceToken(143);
  8984. return this.jsxParseElement();
  8985. } else {
  8986. return super.parseExprAtom(refExpressionErrors);
  8987. }
  8988. }
  8989. skipSpace() {
  8990. const curContext = this.curContext();
  8991. if (!curContext.preserveSpace) super.skipSpace();
  8992. }
  8993. getTokenFromCode(code) {
  8994. const context = this.curContext();
  8995. if (context === types.j_expr) {
  8996. this.jsxReadToken();
  8997. return;
  8998. }
  8999. if (context === types.j_oTag || context === types.j_cTag) {
  9000. if (isIdentifierStart(code)) {
  9001. this.jsxReadWord();
  9002. return;
  9003. }
  9004. if (code === 62) {
  9005. ++this.state.pos;
  9006. this.finishToken(144);
  9007. return;
  9008. }
  9009. if ((code === 34 || code === 39) && context === types.j_oTag) {
  9010. this.jsxReadString(code);
  9011. return;
  9012. }
  9013. }
  9014. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  9015. ++this.state.pos;
  9016. this.finishToken(143);
  9017. return;
  9018. }
  9019. super.getTokenFromCode(code);
  9020. }
  9021. updateContext(prevType) {
  9022. const {
  9023. context,
  9024. type
  9025. } = this.state;
  9026. if (type === 56 && prevType === 143) {
  9027. context.splice(-2, 2, types.j_cTag);
  9028. this.state.canStartJSXElement = false;
  9029. } else if (type === 143) {
  9030. context.push(types.j_oTag);
  9031. } else if (type === 144) {
  9032. const out = context[context.length - 1];
  9033. if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) {
  9034. context.pop();
  9035. this.state.canStartJSXElement = context[context.length - 1] === types.j_expr;
  9036. } else {
  9037. this.setContext(types.j_expr);
  9038. this.state.canStartJSXElement = true;
  9039. }
  9040. } else {
  9041. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  9042. }
  9043. }
  9044. };
  9045. class TypeScriptScope extends Scope {
  9046. constructor(...args) {
  9047. super(...args);
  9048. this.tsNames = new Map();
  9049. }
  9050. }
  9051. class TypeScriptScopeHandler extends ScopeHandler {
  9052. constructor(...args) {
  9053. super(...args);
  9054. this.importsStack = [];
  9055. }
  9056. createScope(flags) {
  9057. this.importsStack.push(new Set());
  9058. return new TypeScriptScope(flags);
  9059. }
  9060. enter(flags) {
  9061. if (flags === 1024) {
  9062. this.importsStack.push(new Set());
  9063. }
  9064. super.enter(flags);
  9065. }
  9066. exit() {
  9067. const flags = super.exit();
  9068. if (flags === 1024) {
  9069. this.importsStack.pop();
  9070. }
  9071. return flags;
  9072. }
  9073. hasImport(name, allowShadow) {
  9074. const len = this.importsStack.length;
  9075. if (this.importsStack[len - 1].has(name)) {
  9076. return true;
  9077. }
  9078. if (!allowShadow && len > 1) {
  9079. for (let i = 0; i < len - 1; i++) {
  9080. if (this.importsStack[i].has(name)) return true;
  9081. }
  9082. }
  9083. return false;
  9084. }
  9085. declareName(name, bindingType, loc) {
  9086. if (bindingType & 4096) {
  9087. if (this.hasImport(name, true)) {
  9088. this.parser.raise(Errors.VarRedeclaration, loc, {
  9089. identifierName: name
  9090. });
  9091. }
  9092. this.importsStack[this.importsStack.length - 1].add(name);
  9093. return;
  9094. }
  9095. const scope = this.currentScope();
  9096. let type = scope.tsNames.get(name) || 0;
  9097. if (bindingType & 1024) {
  9098. this.maybeExportDefined(scope, name);
  9099. scope.tsNames.set(name, type | 16);
  9100. return;
  9101. }
  9102. super.declareName(name, bindingType, loc);
  9103. if (bindingType & 2) {
  9104. if (!(bindingType & 1)) {
  9105. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  9106. this.maybeExportDefined(scope, name);
  9107. }
  9108. type = type | 1;
  9109. }
  9110. if (bindingType & 256) {
  9111. type = type | 2;
  9112. }
  9113. if (bindingType & 512) {
  9114. type = type | 4;
  9115. }
  9116. if (bindingType & 128) {
  9117. type = type | 8;
  9118. }
  9119. if (type) scope.tsNames.set(name, type);
  9120. }
  9121. isRedeclaredInScope(scope, name, bindingType) {
  9122. const type = scope.tsNames.get(name);
  9123. if ((type & 2) > 0) {
  9124. if (bindingType & 256) {
  9125. const isConst = !!(bindingType & 512);
  9126. const wasConst = (type & 4) > 0;
  9127. return isConst !== wasConst;
  9128. }
  9129. return true;
  9130. }
  9131. if (bindingType & 128 && (type & 8) > 0) {
  9132. if (scope.names.get(name) & 2) {
  9133. return !!(bindingType & 1);
  9134. } else {
  9135. return false;
  9136. }
  9137. }
  9138. if (bindingType & 2 && (type & 1) > 0) {
  9139. return true;
  9140. }
  9141. return super.isRedeclaredInScope(scope, name, bindingType);
  9142. }
  9143. checkLocalExport(id) {
  9144. const {
  9145. name
  9146. } = id;
  9147. if (this.hasImport(name)) return;
  9148. const len = this.scopeStack.length;
  9149. for (let i = len - 1; i >= 0; i--) {
  9150. const scope = this.scopeStack[i];
  9151. const type = scope.tsNames.get(name);
  9152. if ((type & 1) > 0 || (type & 16) > 0) {
  9153. return;
  9154. }
  9155. }
  9156. super.checkLocalExport(id);
  9157. }
  9158. }
  9159. class ProductionParameterHandler {
  9160. constructor() {
  9161. this.stacks = [];
  9162. }
  9163. enter(flags) {
  9164. this.stacks.push(flags);
  9165. }
  9166. exit() {
  9167. this.stacks.pop();
  9168. }
  9169. currentFlags() {
  9170. return this.stacks[this.stacks.length - 1];
  9171. }
  9172. get hasAwait() {
  9173. return (this.currentFlags() & 2) > 0;
  9174. }
  9175. get hasYield() {
  9176. return (this.currentFlags() & 1) > 0;
  9177. }
  9178. get hasReturn() {
  9179. return (this.currentFlags() & 4) > 0;
  9180. }
  9181. get hasIn() {
  9182. return (this.currentFlags() & 8) > 0;
  9183. }
  9184. }
  9185. function functionFlags(isAsync, isGenerator) {
  9186. return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0);
  9187. }
  9188. class BaseParser {
  9189. constructor() {
  9190. this.sawUnambiguousESM = false;
  9191. this.ambiguousScriptDifferentAst = false;
  9192. }
  9193. sourceToOffsetPos(sourcePos) {
  9194. return sourcePos + this.startIndex;
  9195. }
  9196. offsetToSourcePos(offsetPos) {
  9197. return offsetPos - this.startIndex;
  9198. }
  9199. hasPlugin(pluginConfig) {
  9200. if (typeof pluginConfig === "string") {
  9201. return this.plugins.has(pluginConfig);
  9202. } else {
  9203. const [pluginName, pluginOptions] = pluginConfig;
  9204. if (!this.hasPlugin(pluginName)) {
  9205. return false;
  9206. }
  9207. const actualOptions = this.plugins.get(pluginName);
  9208. for (const key of Object.keys(pluginOptions)) {
  9209. if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) {
  9210. return false;
  9211. }
  9212. }
  9213. return true;
  9214. }
  9215. }
  9216. getPluginOption(plugin, name) {
  9217. var _this$plugins$get;
  9218. return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name];
  9219. }
  9220. }
  9221. function setTrailingComments(node, comments) {
  9222. if (node.trailingComments === undefined) {
  9223. node.trailingComments = comments;
  9224. } else {
  9225. node.trailingComments.unshift(...comments);
  9226. }
  9227. }
  9228. function setLeadingComments(node, comments) {
  9229. if (node.leadingComments === undefined) {
  9230. node.leadingComments = comments;
  9231. } else {
  9232. node.leadingComments.unshift(...comments);
  9233. }
  9234. }
  9235. function setInnerComments(node, comments) {
  9236. if (node.innerComments === undefined) {
  9237. node.innerComments = comments;
  9238. } else {
  9239. node.innerComments.unshift(...comments);
  9240. }
  9241. }
  9242. function adjustInnerComments(node, elements, commentWS) {
  9243. let lastElement = null;
  9244. let i = elements.length;
  9245. while (lastElement === null && i > 0) {
  9246. lastElement = elements[--i];
  9247. }
  9248. if (lastElement === null || lastElement.start > commentWS.start) {
  9249. setInnerComments(node, commentWS.comments);
  9250. } else {
  9251. setTrailingComments(lastElement, commentWS.comments);
  9252. }
  9253. }
  9254. class CommentsParser extends BaseParser {
  9255. addComment(comment) {
  9256. if (this.filename) comment.loc.filename = this.filename;
  9257. const {
  9258. commentsLen
  9259. } = this.state;
  9260. if (this.comments.length !== commentsLen) {
  9261. this.comments.length = commentsLen;
  9262. }
  9263. this.comments.push(comment);
  9264. this.state.commentsLen++;
  9265. }
  9266. processComment(node) {
  9267. const {
  9268. commentStack
  9269. } = this.state;
  9270. const commentStackLength = commentStack.length;
  9271. if (commentStackLength === 0) return;
  9272. let i = commentStackLength - 1;
  9273. const lastCommentWS = commentStack[i];
  9274. if (lastCommentWS.start === node.end) {
  9275. lastCommentWS.leadingNode = node;
  9276. i--;
  9277. }
  9278. const {
  9279. start: nodeStart
  9280. } = node;
  9281. for (; i >= 0; i--) {
  9282. const commentWS = commentStack[i];
  9283. const commentEnd = commentWS.end;
  9284. if (commentEnd > nodeStart) {
  9285. commentWS.containingNode = node;
  9286. this.finalizeComment(commentWS);
  9287. commentStack.splice(i, 1);
  9288. } else {
  9289. if (commentEnd === nodeStart) {
  9290. commentWS.trailingNode = node;
  9291. }
  9292. break;
  9293. }
  9294. }
  9295. }
  9296. finalizeComment(commentWS) {
  9297. var _node$options;
  9298. const {
  9299. comments
  9300. } = commentWS;
  9301. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  9302. if (commentWS.leadingNode !== null) {
  9303. setTrailingComments(commentWS.leadingNode, comments);
  9304. }
  9305. if (commentWS.trailingNode !== null) {
  9306. setLeadingComments(commentWS.trailingNode, comments);
  9307. }
  9308. } else {
  9309. const node = commentWS.containingNode;
  9310. const commentStart = commentWS.start;
  9311. if (this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) === 44) {
  9312. switch (node.type) {
  9313. case "ObjectExpression":
  9314. case "ObjectPattern":
  9315. adjustInnerComments(node, node.properties, commentWS);
  9316. break;
  9317. case "CallExpression":
  9318. case "NewExpression":
  9319. case "OptionalCallExpression":
  9320. adjustInnerComments(node, node.arguments, commentWS);
  9321. break;
  9322. case "ImportExpression":
  9323. adjustInnerComments(node, [node.source, (_node$options = node.options) != null ? _node$options : null], commentWS);
  9324. break;
  9325. case "FunctionDeclaration":
  9326. case "FunctionExpression":
  9327. case "ArrowFunctionExpression":
  9328. case "ObjectMethod":
  9329. case "ClassMethod":
  9330. case "ClassPrivateMethod":
  9331. case "TSTypeParameterDeclaration":
  9332. adjustInnerComments(node, node.params, commentWS);
  9333. break;
  9334. case "ArrayExpression":
  9335. case "ArrayPattern":
  9336. adjustInnerComments(node, node.elements, commentWS);
  9337. break;
  9338. case "ExportNamedDeclaration":
  9339. case "ImportDeclaration":
  9340. adjustInnerComments(node, node.specifiers, commentWS);
  9341. break;
  9342. case "TSEnumDeclaration":
  9343. adjustInnerComments(node, node.members, commentWS);
  9344. break;
  9345. case "TSEnumBody":
  9346. adjustInnerComments(node, node.members, commentWS);
  9347. break;
  9348. case "TSInterfaceBody":
  9349. adjustInnerComments(node, node.body, commentWS);
  9350. break;
  9351. default:
  9352. {
  9353. if (node.type === "RecordExpression") {
  9354. adjustInnerComments(node, node.properties, commentWS);
  9355. break;
  9356. }
  9357. if (node.type === "TupleExpression") {
  9358. adjustInnerComments(node, node.elements, commentWS);
  9359. break;
  9360. }
  9361. setInnerComments(node, comments);
  9362. }
  9363. }
  9364. } else {
  9365. setInnerComments(node, comments);
  9366. }
  9367. }
  9368. }
  9369. finalizeRemainingComments() {
  9370. const {
  9371. commentStack
  9372. } = this.state;
  9373. for (let i = commentStack.length - 1; i >= 0; i--) {
  9374. this.finalizeComment(commentStack[i]);
  9375. }
  9376. this.state.commentStack = [];
  9377. }
  9378. resetPreviousNodeTrailingComments(node) {
  9379. const {
  9380. commentStack
  9381. } = this.state;
  9382. const {
  9383. length
  9384. } = commentStack;
  9385. if (length === 0) return;
  9386. const commentWS = commentStack[length - 1];
  9387. if (commentWS.leadingNode === node) {
  9388. commentWS.leadingNode = null;
  9389. }
  9390. }
  9391. takeSurroundingComments(node, start, end) {
  9392. const {
  9393. commentStack
  9394. } = this.state;
  9395. const commentStackLength = commentStack.length;
  9396. if (commentStackLength === 0) return;
  9397. let i = commentStackLength - 1;
  9398. for (; i >= 0; i--) {
  9399. const commentWS = commentStack[i];
  9400. const commentEnd = commentWS.end;
  9401. const commentStart = commentWS.start;
  9402. if (commentStart === end) {
  9403. commentWS.leadingNode = node;
  9404. } else if (commentEnd === start) {
  9405. commentWS.trailingNode = node;
  9406. } else if (commentEnd < start) {
  9407. break;
  9408. }
  9409. }
  9410. }
  9411. }
  9412. class State {
  9413. constructor() {
  9414. this.flags = 1024;
  9415. this.startIndex = void 0;
  9416. this.curLine = void 0;
  9417. this.lineStart = void 0;
  9418. this.startLoc = void 0;
  9419. this.endLoc = void 0;
  9420. this.errors = [];
  9421. this.potentialArrowAt = -1;
  9422. this.noArrowAt = [];
  9423. this.noArrowParamsConversionAt = [];
  9424. this.topicContext = {
  9425. maxNumOfResolvableTopics: 0,
  9426. maxTopicIndex: null
  9427. };
  9428. this.labels = [];
  9429. this.commentsLen = 0;
  9430. this.commentStack = [];
  9431. this.pos = 0;
  9432. this.type = 140;
  9433. this.value = null;
  9434. this.start = 0;
  9435. this.end = 0;
  9436. this.lastTokEndLoc = null;
  9437. this.lastTokStartLoc = null;
  9438. this.context = [types.brace];
  9439. this.firstInvalidTemplateEscapePos = null;
  9440. this.strictErrors = new Map();
  9441. this.tokensLength = 0;
  9442. }
  9443. get strict() {
  9444. return (this.flags & 1) > 0;
  9445. }
  9446. set strict(v) {
  9447. if (v) this.flags |= 1;else this.flags &= -2;
  9448. }
  9449. init({
  9450. strictMode,
  9451. sourceType,
  9452. startIndex,
  9453. startLine,
  9454. startColumn
  9455. }) {
  9456. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  9457. this.startIndex = startIndex;
  9458. this.curLine = startLine;
  9459. this.lineStart = -startColumn;
  9460. this.startLoc = this.endLoc = new Position(startLine, startColumn, startIndex);
  9461. }
  9462. get maybeInArrowParameters() {
  9463. return (this.flags & 2) > 0;
  9464. }
  9465. set maybeInArrowParameters(v) {
  9466. if (v) this.flags |= 2;else this.flags &= -3;
  9467. }
  9468. get inType() {
  9469. return (this.flags & 4) > 0;
  9470. }
  9471. set inType(v) {
  9472. if (v) this.flags |= 4;else this.flags &= -5;
  9473. }
  9474. get noAnonFunctionType() {
  9475. return (this.flags & 8) > 0;
  9476. }
  9477. set noAnonFunctionType(v) {
  9478. if (v) this.flags |= 8;else this.flags &= -9;
  9479. }
  9480. get hasFlowComment() {
  9481. return (this.flags & 16) > 0;
  9482. }
  9483. set hasFlowComment(v) {
  9484. if (v) this.flags |= 16;else this.flags &= -17;
  9485. }
  9486. get isAmbientContext() {
  9487. return (this.flags & 32) > 0;
  9488. }
  9489. set isAmbientContext(v) {
  9490. if (v) this.flags |= 32;else this.flags &= -33;
  9491. }
  9492. get inAbstractClass() {
  9493. return (this.flags & 64) > 0;
  9494. }
  9495. set inAbstractClass(v) {
  9496. if (v) this.flags |= 64;else this.flags &= -65;
  9497. }
  9498. get inDisallowConditionalTypesContext() {
  9499. return (this.flags & 128) > 0;
  9500. }
  9501. set inDisallowConditionalTypesContext(v) {
  9502. if (v) this.flags |= 128;else this.flags &= -129;
  9503. }
  9504. get soloAwait() {
  9505. return (this.flags & 256) > 0;
  9506. }
  9507. set soloAwait(v) {
  9508. if (v) this.flags |= 256;else this.flags &= -257;
  9509. }
  9510. get inFSharpPipelineDirectBody() {
  9511. return (this.flags & 512) > 0;
  9512. }
  9513. set inFSharpPipelineDirectBody(v) {
  9514. if (v) this.flags |= 512;else this.flags &= -513;
  9515. }
  9516. get canStartJSXElement() {
  9517. return (this.flags & 1024) > 0;
  9518. }
  9519. set canStartJSXElement(v) {
  9520. if (v) this.flags |= 1024;else this.flags &= -1025;
  9521. }
  9522. get containsEsc() {
  9523. return (this.flags & 2048) > 0;
  9524. }
  9525. set containsEsc(v) {
  9526. if (v) this.flags |= 2048;else this.flags &= -2049;
  9527. }
  9528. get hasTopLevelAwait() {
  9529. return (this.flags & 4096) > 0;
  9530. }
  9531. set hasTopLevelAwait(v) {
  9532. if (v) this.flags |= 4096;else this.flags &= -4097;
  9533. }
  9534. curPosition() {
  9535. return new Position(this.curLine, this.pos - this.lineStart, this.pos + this.startIndex);
  9536. }
  9537. clone() {
  9538. const state = new State();
  9539. state.flags = this.flags;
  9540. state.startIndex = this.startIndex;
  9541. state.curLine = this.curLine;
  9542. state.lineStart = this.lineStart;
  9543. state.startLoc = this.startLoc;
  9544. state.endLoc = this.endLoc;
  9545. state.errors = this.errors.slice();
  9546. state.potentialArrowAt = this.potentialArrowAt;
  9547. state.noArrowAt = this.noArrowAt.slice();
  9548. state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();
  9549. state.topicContext = this.topicContext;
  9550. state.labels = this.labels.slice();
  9551. state.commentsLen = this.commentsLen;
  9552. state.commentStack = this.commentStack.slice();
  9553. state.pos = this.pos;
  9554. state.type = this.type;
  9555. state.value = this.value;
  9556. state.start = this.start;
  9557. state.end = this.end;
  9558. state.lastTokEndLoc = this.lastTokEndLoc;
  9559. state.lastTokStartLoc = this.lastTokStartLoc;
  9560. state.context = this.context.slice();
  9561. state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;
  9562. state.strictErrors = this.strictErrors;
  9563. state.tokensLength = this.tokensLength;
  9564. return state;
  9565. }
  9566. }
  9567. var _isDigit = function isDigit(code) {
  9568. return code >= 48 && code <= 57;
  9569. };
  9570. const forbiddenNumericSeparatorSiblings = {
  9571. decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]),
  9572. hex: new Set([46, 88, 95, 120])
  9573. };
  9574. const isAllowedNumericSeparatorSibling = {
  9575. bin: ch => ch === 48 || ch === 49,
  9576. oct: ch => ch >= 48 && ch <= 55,
  9577. dec: ch => ch >= 48 && ch <= 57,
  9578. hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102
  9579. };
  9580. function readStringContents(type, input, pos, lineStart, curLine, errors) {
  9581. const initialPos = pos;
  9582. const initialLineStart = lineStart;
  9583. const initialCurLine = curLine;
  9584. let out = "";
  9585. let firstInvalidLoc = null;
  9586. let chunkStart = pos;
  9587. const {
  9588. length
  9589. } = input;
  9590. for (;;) {
  9591. if (pos >= length) {
  9592. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  9593. out += input.slice(chunkStart, pos);
  9594. break;
  9595. }
  9596. const ch = input.charCodeAt(pos);
  9597. if (isStringEnd(type, ch, input, pos)) {
  9598. out += input.slice(chunkStart, pos);
  9599. break;
  9600. }
  9601. if (ch === 92) {
  9602. out += input.slice(chunkStart, pos);
  9603. const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors);
  9604. if (res.ch === null && !firstInvalidLoc) {
  9605. firstInvalidLoc = {
  9606. pos,
  9607. lineStart,
  9608. curLine
  9609. };
  9610. } else {
  9611. out += res.ch;
  9612. }
  9613. ({
  9614. pos,
  9615. lineStart,
  9616. curLine
  9617. } = res);
  9618. chunkStart = pos;
  9619. } else if (ch === 8232 || ch === 8233) {
  9620. ++pos;
  9621. ++curLine;
  9622. lineStart = pos;
  9623. } else if (ch === 10 || ch === 13) {
  9624. if (type === "template") {
  9625. out += input.slice(chunkStart, pos) + "\n";
  9626. ++pos;
  9627. if (ch === 13 && input.charCodeAt(pos) === 10) {
  9628. ++pos;
  9629. }
  9630. ++curLine;
  9631. chunkStart = lineStart = pos;
  9632. } else {
  9633. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  9634. }
  9635. } else {
  9636. ++pos;
  9637. }
  9638. }
  9639. return {
  9640. pos,
  9641. str: out,
  9642. firstInvalidLoc,
  9643. lineStart,
  9644. curLine,
  9645. containsInvalid: !!firstInvalidLoc
  9646. };
  9647. }
  9648. function isStringEnd(type, ch, input, pos) {
  9649. if (type === "template") {
  9650. return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123;
  9651. }
  9652. return ch === (type === "double" ? 34 : 39);
  9653. }
  9654. function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) {
  9655. const throwOnInvalid = !inTemplate;
  9656. pos++;
  9657. const res = ch => ({
  9658. pos,
  9659. ch,
  9660. lineStart,
  9661. curLine
  9662. });
  9663. const ch = input.charCodeAt(pos++);
  9664. switch (ch) {
  9665. case 110:
  9666. return res("\n");
  9667. case 114:
  9668. return res("\r");
  9669. case 120:
  9670. {
  9671. let code;
  9672. ({
  9673. code,
  9674. pos
  9675. } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors));
  9676. return res(code === null ? null : String.fromCharCode(code));
  9677. }
  9678. case 117:
  9679. {
  9680. let code;
  9681. ({
  9682. code,
  9683. pos
  9684. } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors));
  9685. return res(code === null ? null : String.fromCodePoint(code));
  9686. }
  9687. case 116:
  9688. return res("\t");
  9689. case 98:
  9690. return res("\b");
  9691. case 118:
  9692. return res("\u000b");
  9693. case 102:
  9694. return res("\f");
  9695. case 13:
  9696. if (input.charCodeAt(pos) === 10) {
  9697. ++pos;
  9698. }
  9699. case 10:
  9700. lineStart = pos;
  9701. ++curLine;
  9702. case 8232:
  9703. case 8233:
  9704. return res("");
  9705. case 56:
  9706. case 57:
  9707. if (inTemplate) {
  9708. return res(null);
  9709. } else {
  9710. errors.strictNumericEscape(pos - 1, lineStart, curLine);
  9711. }
  9712. default:
  9713. if (ch >= 48 && ch <= 55) {
  9714. const startPos = pos - 1;
  9715. const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));
  9716. let octalStr = match[0];
  9717. let octal = parseInt(octalStr, 8);
  9718. if (octal > 255) {
  9719. octalStr = octalStr.slice(0, -1);
  9720. octal = parseInt(octalStr, 8);
  9721. }
  9722. pos += octalStr.length - 1;
  9723. const next = input.charCodeAt(pos);
  9724. if (octalStr !== "0" || next === 56 || next === 57) {
  9725. if (inTemplate) {
  9726. return res(null);
  9727. } else {
  9728. errors.strictNumericEscape(startPos, lineStart, curLine);
  9729. }
  9730. }
  9731. return res(String.fromCharCode(octal));
  9732. }
  9733. return res(String.fromCharCode(ch));
  9734. }
  9735. }
  9736. function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) {
  9737. const initialPos = pos;
  9738. let n;
  9739. ({
  9740. n,
  9741. pos
  9742. } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid));
  9743. if (n === null) {
  9744. if (throwOnInvalid) {
  9745. errors.invalidEscapeSequence(initialPos, lineStart, curLine);
  9746. } else {
  9747. pos = initialPos - 1;
  9748. }
  9749. }
  9750. return {
  9751. code: n,
  9752. pos
  9753. };
  9754. }
  9755. function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) {
  9756. const start = pos;
  9757. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  9758. const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin;
  9759. let invalid = false;
  9760. let total = 0;
  9761. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  9762. const code = input.charCodeAt(pos);
  9763. let val;
  9764. if (code === 95 && allowNumSeparator !== "bail") {
  9765. const prev = input.charCodeAt(pos - 1);
  9766. const next = input.charCodeAt(pos + 1);
  9767. if (!allowNumSeparator) {
  9768. if (bailOnError) return {
  9769. n: null,
  9770. pos
  9771. };
  9772. errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);
  9773. } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) {
  9774. if (bailOnError) return {
  9775. n: null,
  9776. pos
  9777. };
  9778. errors.unexpectedNumericSeparator(pos, lineStart, curLine);
  9779. }
  9780. ++pos;
  9781. continue;
  9782. }
  9783. if (code >= 97) {
  9784. val = code - 97 + 10;
  9785. } else if (code >= 65) {
  9786. val = code - 65 + 10;
  9787. } else if (_isDigit(code)) {
  9788. val = code - 48;
  9789. } else {
  9790. val = Infinity;
  9791. }
  9792. if (val >= radix) {
  9793. if (val <= 9 && bailOnError) {
  9794. return {
  9795. n: null,
  9796. pos
  9797. };
  9798. } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) {
  9799. val = 0;
  9800. } else if (forceLen) {
  9801. val = 0;
  9802. invalid = true;
  9803. } else {
  9804. break;
  9805. }
  9806. }
  9807. ++pos;
  9808. total = total * radix + val;
  9809. }
  9810. if (pos === start || len != null && pos - start !== len || invalid) {
  9811. return {
  9812. n: null,
  9813. pos
  9814. };
  9815. }
  9816. return {
  9817. n: total,
  9818. pos
  9819. };
  9820. }
  9821. function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) {
  9822. const ch = input.charCodeAt(pos);
  9823. let code;
  9824. if (ch === 123) {
  9825. ++pos;
  9826. ({
  9827. code,
  9828. pos
  9829. } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors));
  9830. ++pos;
  9831. if (code !== null && code > 0x10ffff) {
  9832. if (throwOnInvalid) {
  9833. errors.invalidCodePoint(pos, lineStart, curLine);
  9834. } else {
  9835. return {
  9836. code: null,
  9837. pos
  9838. };
  9839. }
  9840. }
  9841. } else {
  9842. ({
  9843. code,
  9844. pos
  9845. } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors));
  9846. }
  9847. return {
  9848. code,
  9849. pos
  9850. };
  9851. }
  9852. function buildPosition(pos, lineStart, curLine) {
  9853. return new Position(curLine, pos - lineStart, pos);
  9854. }
  9855. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]);
  9856. class Token {
  9857. constructor(state) {
  9858. const startIndex = state.startIndex || 0;
  9859. this.type = state.type;
  9860. this.value = state.value;
  9861. this.start = startIndex + state.start;
  9862. this.end = startIndex + state.end;
  9863. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  9864. }
  9865. }
  9866. class Tokenizer extends CommentsParser {
  9867. constructor(options, input) {
  9868. super();
  9869. this.isLookahead = void 0;
  9870. this.tokens = [];
  9871. this.errorHandlers_readInt = {
  9872. invalidDigit: (pos, lineStart, curLine, radix) => {
  9873. if (!(this.optionFlags & 2048)) return false;
  9874. this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), {
  9875. radix
  9876. });
  9877. return true;
  9878. },
  9879. numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence),
  9880. unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator)
  9881. };
  9882. this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, {
  9883. invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence),
  9884. invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint)
  9885. });
  9886. this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, {
  9887. strictNumericEscape: (pos, lineStart, curLine) => {
  9888. this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine));
  9889. },
  9890. unterminated: (pos, lineStart, curLine) => {
  9891. throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine));
  9892. }
  9893. });
  9894. this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, {
  9895. strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape),
  9896. unterminated: (pos, lineStart, curLine) => {
  9897. throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine));
  9898. }
  9899. });
  9900. this.state = new State();
  9901. this.state.init(options);
  9902. this.input = input;
  9903. this.length = input.length;
  9904. this.comments = [];
  9905. this.isLookahead = false;
  9906. }
  9907. pushToken(token) {
  9908. this.tokens.length = this.state.tokensLength;
  9909. this.tokens.push(token);
  9910. ++this.state.tokensLength;
  9911. }
  9912. next() {
  9913. this.checkKeywordEscapes();
  9914. if (this.optionFlags & 256) {
  9915. this.pushToken(new Token(this.state));
  9916. }
  9917. this.state.lastTokEndLoc = this.state.endLoc;
  9918. this.state.lastTokStartLoc = this.state.startLoc;
  9919. this.nextToken();
  9920. }
  9921. eat(type) {
  9922. if (this.match(type)) {
  9923. this.next();
  9924. return true;
  9925. } else {
  9926. return false;
  9927. }
  9928. }
  9929. match(type) {
  9930. return this.state.type === type;
  9931. }
  9932. createLookaheadState(state) {
  9933. return {
  9934. pos: state.pos,
  9935. value: null,
  9936. type: state.type,
  9937. start: state.start,
  9938. end: state.end,
  9939. context: [this.curContext()],
  9940. inType: state.inType,
  9941. startLoc: state.startLoc,
  9942. lastTokEndLoc: state.lastTokEndLoc,
  9943. curLine: state.curLine,
  9944. lineStart: state.lineStart,
  9945. curPosition: state.curPosition
  9946. };
  9947. }
  9948. lookahead() {
  9949. const old = this.state;
  9950. this.state = this.createLookaheadState(old);
  9951. this.isLookahead = true;
  9952. this.nextToken();
  9953. this.isLookahead = false;
  9954. const curr = this.state;
  9955. this.state = old;
  9956. return curr;
  9957. }
  9958. nextTokenStart() {
  9959. return this.nextTokenStartSince(this.state.pos);
  9960. }
  9961. nextTokenStartSince(pos) {
  9962. skipWhiteSpace.lastIndex = pos;
  9963. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  9964. }
  9965. lookaheadCharCode() {
  9966. return this.lookaheadCharCodeSince(this.state.pos);
  9967. }
  9968. lookaheadCharCodeSince(pos) {
  9969. return this.input.charCodeAt(this.nextTokenStartSince(pos));
  9970. }
  9971. nextTokenInLineStart() {
  9972. return this.nextTokenInLineStartSince(this.state.pos);
  9973. }
  9974. nextTokenInLineStartSince(pos) {
  9975. skipWhiteSpaceInLine.lastIndex = pos;
  9976. return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos;
  9977. }
  9978. lookaheadInLineCharCode() {
  9979. return this.input.charCodeAt(this.nextTokenInLineStart());
  9980. }
  9981. codePointAtPos(pos) {
  9982. let cp = this.input.charCodeAt(pos);
  9983. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  9984. const trail = this.input.charCodeAt(pos);
  9985. if ((trail & 0xfc00) === 0xdc00) {
  9986. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  9987. }
  9988. }
  9989. return cp;
  9990. }
  9991. setStrict(strict) {
  9992. this.state.strict = strict;
  9993. if (strict) {
  9994. this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at));
  9995. this.state.strictErrors.clear();
  9996. }
  9997. }
  9998. curContext() {
  9999. return this.state.context[this.state.context.length - 1];
  10000. }
  10001. nextToken() {
  10002. this.skipSpace();
  10003. this.state.start = this.state.pos;
  10004. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  10005. if (this.state.pos >= this.length) {
  10006. this.finishToken(140);
  10007. return;
  10008. }
  10009. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  10010. }
  10011. skipBlockComment(commentEnd) {
  10012. let startLoc;
  10013. if (!this.isLookahead) startLoc = this.state.curPosition();
  10014. const start = this.state.pos;
  10015. const end = this.input.indexOf(commentEnd, start + 2);
  10016. if (end === -1) {
  10017. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  10018. }
  10019. this.state.pos = end + commentEnd.length;
  10020. lineBreakG.lastIndex = start + 2;
  10021. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  10022. ++this.state.curLine;
  10023. this.state.lineStart = lineBreakG.lastIndex;
  10024. }
  10025. if (this.isLookahead) return;
  10026. const comment = {
  10027. type: "CommentBlock",
  10028. value: this.input.slice(start + 2, end),
  10029. start: this.sourceToOffsetPos(start),
  10030. end: this.sourceToOffsetPos(end + commentEnd.length),
  10031. loc: new SourceLocation(startLoc, this.state.curPosition())
  10032. };
  10033. if (this.optionFlags & 256) this.pushToken(comment);
  10034. return comment;
  10035. }
  10036. skipLineComment(startSkip) {
  10037. const start = this.state.pos;
  10038. let startLoc;
  10039. if (!this.isLookahead) startLoc = this.state.curPosition();
  10040. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  10041. if (this.state.pos < this.length) {
  10042. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  10043. ch = this.input.charCodeAt(this.state.pos);
  10044. }
  10045. }
  10046. if (this.isLookahead) return;
  10047. const end = this.state.pos;
  10048. const value = this.input.slice(start + startSkip, end);
  10049. const comment = {
  10050. type: "CommentLine",
  10051. value,
  10052. start: this.sourceToOffsetPos(start),
  10053. end: this.sourceToOffsetPos(end),
  10054. loc: new SourceLocation(startLoc, this.state.curPosition())
  10055. };
  10056. if (this.optionFlags & 256) this.pushToken(comment);
  10057. return comment;
  10058. }
  10059. skipSpace() {
  10060. const spaceStart = this.state.pos;
  10061. const comments = this.optionFlags & 4096 ? [] : null;
  10062. loop: while (this.state.pos < this.length) {
  10063. const ch = this.input.charCodeAt(this.state.pos);
  10064. switch (ch) {
  10065. case 32:
  10066. case 160:
  10067. case 9:
  10068. ++this.state.pos;
  10069. break;
  10070. case 13:
  10071. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  10072. ++this.state.pos;
  10073. }
  10074. case 10:
  10075. case 8232:
  10076. case 8233:
  10077. ++this.state.pos;
  10078. ++this.state.curLine;
  10079. this.state.lineStart = this.state.pos;
  10080. break;
  10081. case 47:
  10082. switch (this.input.charCodeAt(this.state.pos + 1)) {
  10083. case 42:
  10084. {
  10085. const comment = this.skipBlockComment("*/");
  10086. if (comment !== undefined) {
  10087. this.addComment(comment);
  10088. comments == null || comments.push(comment);
  10089. }
  10090. break;
  10091. }
  10092. case 47:
  10093. {
  10094. const comment = this.skipLineComment(2);
  10095. if (comment !== undefined) {
  10096. this.addComment(comment);
  10097. comments == null || comments.push(comment);
  10098. }
  10099. break;
  10100. }
  10101. default:
  10102. break loop;
  10103. }
  10104. break;
  10105. default:
  10106. if (isWhitespace(ch)) {
  10107. ++this.state.pos;
  10108. } else if (ch === 45 && !this.inModule && this.optionFlags & 8192) {
  10109. const pos = this.state.pos;
  10110. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  10111. const comment = this.skipLineComment(3);
  10112. if (comment !== undefined) {
  10113. this.addComment(comment);
  10114. comments == null || comments.push(comment);
  10115. }
  10116. } else {
  10117. break loop;
  10118. }
  10119. } else if (ch === 60 && !this.inModule && this.optionFlags & 8192) {
  10120. const pos = this.state.pos;
  10121. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  10122. const comment = this.skipLineComment(4);
  10123. if (comment !== undefined) {
  10124. this.addComment(comment);
  10125. comments == null || comments.push(comment);
  10126. }
  10127. } else {
  10128. break loop;
  10129. }
  10130. } else {
  10131. break loop;
  10132. }
  10133. }
  10134. }
  10135. if ((comments == null ? void 0 : comments.length) > 0) {
  10136. const end = this.state.pos;
  10137. const commentWhitespace = {
  10138. start: this.sourceToOffsetPos(spaceStart),
  10139. end: this.sourceToOffsetPos(end),
  10140. comments: comments,
  10141. leadingNode: null,
  10142. trailingNode: null,
  10143. containingNode: null
  10144. };
  10145. this.state.commentStack.push(commentWhitespace);
  10146. }
  10147. }
  10148. finishToken(type, val) {
  10149. this.state.end = this.state.pos;
  10150. this.state.endLoc = this.state.curPosition();
  10151. const prevType = this.state.type;
  10152. this.state.type = type;
  10153. this.state.value = val;
  10154. if (!this.isLookahead) {
  10155. this.updateContext(prevType);
  10156. }
  10157. }
  10158. replaceToken(type) {
  10159. this.state.type = type;
  10160. this.updateContext();
  10161. }
  10162. readToken_numberSign() {
  10163. if (this.state.pos === 0 && this.readToken_interpreter()) {
  10164. return;
  10165. }
  10166. const nextPos = this.state.pos + 1;
  10167. const next = this.codePointAtPos(nextPos);
  10168. if (next >= 48 && next <= 57) {
  10169. throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition());
  10170. }
  10171. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  10172. this.expectPlugin("recordAndTuple");
  10173. if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") {
  10174. throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition());
  10175. }
  10176. this.state.pos += 2;
  10177. if (next === 123) {
  10178. this.finishToken(7);
  10179. } else {
  10180. this.finishToken(1);
  10181. }
  10182. } else if (isIdentifierStart(next)) {
  10183. ++this.state.pos;
  10184. this.finishToken(139, this.readWord1(next));
  10185. } else if (next === 92) {
  10186. ++this.state.pos;
  10187. this.finishToken(139, this.readWord1());
  10188. } else {
  10189. this.finishOp(27, 1);
  10190. }
  10191. }
  10192. readToken_dot() {
  10193. const next = this.input.charCodeAt(this.state.pos + 1);
  10194. if (next >= 48 && next <= 57) {
  10195. this.readNumber(true);
  10196. return;
  10197. }
  10198. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  10199. this.state.pos += 3;
  10200. this.finishToken(21);
  10201. } else {
  10202. ++this.state.pos;
  10203. this.finishToken(16);
  10204. }
  10205. }
  10206. readToken_slash() {
  10207. const next = this.input.charCodeAt(this.state.pos + 1);
  10208. if (next === 61) {
  10209. this.finishOp(31, 2);
  10210. } else {
  10211. this.finishOp(56, 1);
  10212. }
  10213. }
  10214. readToken_interpreter() {
  10215. if (this.state.pos !== 0 || this.length < 2) return false;
  10216. let ch = this.input.charCodeAt(this.state.pos + 1);
  10217. if (ch !== 33) return false;
  10218. const start = this.state.pos;
  10219. this.state.pos += 1;
  10220. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  10221. ch = this.input.charCodeAt(this.state.pos);
  10222. }
  10223. const value = this.input.slice(start + 2, this.state.pos);
  10224. this.finishToken(28, value);
  10225. return true;
  10226. }
  10227. readToken_mult_modulo(code) {
  10228. let type = code === 42 ? 55 : 54;
  10229. let width = 1;
  10230. let next = this.input.charCodeAt(this.state.pos + 1);
  10231. if (code === 42 && next === 42) {
  10232. width++;
  10233. next = this.input.charCodeAt(this.state.pos + 2);
  10234. type = 57;
  10235. }
  10236. if (next === 61 && !this.state.inType) {
  10237. width++;
  10238. type = code === 37 ? 33 : 30;
  10239. }
  10240. this.finishOp(type, width);
  10241. }
  10242. readToken_pipe_amp(code) {
  10243. const next = this.input.charCodeAt(this.state.pos + 1);
  10244. if (next === code) {
  10245. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  10246. this.finishOp(30, 3);
  10247. } else {
  10248. this.finishOp(code === 124 ? 41 : 42, 2);
  10249. }
  10250. return;
  10251. }
  10252. if (code === 124) {
  10253. if (next === 62) {
  10254. this.finishOp(39, 2);
  10255. return;
  10256. }
  10257. if (this.hasPlugin("recordAndTuple") && next === 125) {
  10258. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10259. throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  10260. }
  10261. this.state.pos += 2;
  10262. this.finishToken(9);
  10263. return;
  10264. }
  10265. if (this.hasPlugin("recordAndTuple") && next === 93) {
  10266. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10267. throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  10268. }
  10269. this.state.pos += 2;
  10270. this.finishToken(4);
  10271. return;
  10272. }
  10273. }
  10274. if (next === 61) {
  10275. this.finishOp(30, 2);
  10276. return;
  10277. }
  10278. this.finishOp(code === 124 ? 43 : 45, 1);
  10279. }
  10280. readToken_caret() {
  10281. const next = this.input.charCodeAt(this.state.pos + 1);
  10282. if (next === 61 && !this.state.inType) {
  10283. this.finishOp(32, 2);
  10284. } else if (next === 94 && this.hasPlugin(["pipelineOperator", {
  10285. proposal: "hack",
  10286. topicToken: "^^"
  10287. }])) {
  10288. this.finishOp(37, 2);
  10289. const lookaheadCh = this.input.codePointAt(this.state.pos);
  10290. if (lookaheadCh === 94) {
  10291. this.unexpected();
  10292. }
  10293. } else {
  10294. this.finishOp(44, 1);
  10295. }
  10296. }
  10297. readToken_atSign() {
  10298. const next = this.input.charCodeAt(this.state.pos + 1);
  10299. if (next === 64 && this.hasPlugin(["pipelineOperator", {
  10300. proposal: "hack",
  10301. topicToken: "@@"
  10302. }])) {
  10303. this.finishOp(38, 2);
  10304. } else {
  10305. this.finishOp(26, 1);
  10306. }
  10307. }
  10308. readToken_plus_min(code) {
  10309. const next = this.input.charCodeAt(this.state.pos + 1);
  10310. if (next === code) {
  10311. this.finishOp(34, 2);
  10312. return;
  10313. }
  10314. if (next === 61) {
  10315. this.finishOp(30, 2);
  10316. } else {
  10317. this.finishOp(53, 1);
  10318. }
  10319. }
  10320. readToken_lt() {
  10321. const {
  10322. pos
  10323. } = this.state;
  10324. const next = this.input.charCodeAt(pos + 1);
  10325. if (next === 60) {
  10326. if (this.input.charCodeAt(pos + 2) === 61) {
  10327. this.finishOp(30, 3);
  10328. return;
  10329. }
  10330. this.finishOp(51, 2);
  10331. return;
  10332. }
  10333. if (next === 61) {
  10334. this.finishOp(49, 2);
  10335. return;
  10336. }
  10337. this.finishOp(47, 1);
  10338. }
  10339. readToken_gt() {
  10340. const {
  10341. pos
  10342. } = this.state;
  10343. const next = this.input.charCodeAt(pos + 1);
  10344. if (next === 62) {
  10345. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  10346. if (this.input.charCodeAt(pos + size) === 61) {
  10347. this.finishOp(30, size + 1);
  10348. return;
  10349. }
  10350. this.finishOp(52, size);
  10351. return;
  10352. }
  10353. if (next === 61) {
  10354. this.finishOp(49, 2);
  10355. return;
  10356. }
  10357. this.finishOp(48, 1);
  10358. }
  10359. readToken_eq_excl(code) {
  10360. const next = this.input.charCodeAt(this.state.pos + 1);
  10361. if (next === 61) {
  10362. this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  10363. return;
  10364. }
  10365. if (code === 61 && next === 62) {
  10366. this.state.pos += 2;
  10367. this.finishToken(19);
  10368. return;
  10369. }
  10370. this.finishOp(code === 61 ? 29 : 35, 1);
  10371. }
  10372. readToken_question() {
  10373. const next = this.input.charCodeAt(this.state.pos + 1);
  10374. const next2 = this.input.charCodeAt(this.state.pos + 2);
  10375. if (next === 63) {
  10376. if (next2 === 61) {
  10377. this.finishOp(30, 3);
  10378. } else {
  10379. this.finishOp(40, 2);
  10380. }
  10381. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  10382. this.state.pos += 2;
  10383. this.finishToken(18);
  10384. } else {
  10385. ++this.state.pos;
  10386. this.finishToken(17);
  10387. }
  10388. }
  10389. getTokenFromCode(code) {
  10390. switch (code) {
  10391. case 46:
  10392. this.readToken_dot();
  10393. return;
  10394. case 40:
  10395. ++this.state.pos;
  10396. this.finishToken(10);
  10397. return;
  10398. case 41:
  10399. ++this.state.pos;
  10400. this.finishToken(11);
  10401. return;
  10402. case 59:
  10403. ++this.state.pos;
  10404. this.finishToken(13);
  10405. return;
  10406. case 44:
  10407. ++this.state.pos;
  10408. this.finishToken(12);
  10409. return;
  10410. case 91:
  10411. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  10412. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10413. throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  10414. }
  10415. this.state.pos += 2;
  10416. this.finishToken(2);
  10417. } else {
  10418. ++this.state.pos;
  10419. this.finishToken(0);
  10420. }
  10421. return;
  10422. case 93:
  10423. ++this.state.pos;
  10424. this.finishToken(3);
  10425. return;
  10426. case 123:
  10427. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  10428. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10429. throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  10430. }
  10431. this.state.pos += 2;
  10432. this.finishToken(6);
  10433. } else {
  10434. ++this.state.pos;
  10435. this.finishToken(5);
  10436. }
  10437. return;
  10438. case 125:
  10439. ++this.state.pos;
  10440. this.finishToken(8);
  10441. return;
  10442. case 58:
  10443. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  10444. this.finishOp(15, 2);
  10445. } else {
  10446. ++this.state.pos;
  10447. this.finishToken(14);
  10448. }
  10449. return;
  10450. case 63:
  10451. this.readToken_question();
  10452. return;
  10453. case 96:
  10454. this.readTemplateToken();
  10455. return;
  10456. case 48:
  10457. {
  10458. const next = this.input.charCodeAt(this.state.pos + 1);
  10459. if (next === 120 || next === 88) {
  10460. this.readRadixNumber(16);
  10461. return;
  10462. }
  10463. if (next === 111 || next === 79) {
  10464. this.readRadixNumber(8);
  10465. return;
  10466. }
  10467. if (next === 98 || next === 66) {
  10468. this.readRadixNumber(2);
  10469. return;
  10470. }
  10471. }
  10472. case 49:
  10473. case 50:
  10474. case 51:
  10475. case 52:
  10476. case 53:
  10477. case 54:
  10478. case 55:
  10479. case 56:
  10480. case 57:
  10481. this.readNumber(false);
  10482. return;
  10483. case 34:
  10484. case 39:
  10485. this.readString(code);
  10486. return;
  10487. case 47:
  10488. this.readToken_slash();
  10489. return;
  10490. case 37:
  10491. case 42:
  10492. this.readToken_mult_modulo(code);
  10493. return;
  10494. case 124:
  10495. case 38:
  10496. this.readToken_pipe_amp(code);
  10497. return;
  10498. case 94:
  10499. this.readToken_caret();
  10500. return;
  10501. case 43:
  10502. case 45:
  10503. this.readToken_plus_min(code);
  10504. return;
  10505. case 60:
  10506. this.readToken_lt();
  10507. return;
  10508. case 62:
  10509. this.readToken_gt();
  10510. return;
  10511. case 61:
  10512. case 33:
  10513. this.readToken_eq_excl(code);
  10514. return;
  10515. case 126:
  10516. this.finishOp(36, 1);
  10517. return;
  10518. case 64:
  10519. this.readToken_atSign();
  10520. return;
  10521. case 35:
  10522. this.readToken_numberSign();
  10523. return;
  10524. case 92:
  10525. this.readWord();
  10526. return;
  10527. default:
  10528. if (isIdentifierStart(code)) {
  10529. this.readWord(code);
  10530. return;
  10531. }
  10532. }
  10533. throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), {
  10534. unexpected: String.fromCodePoint(code)
  10535. });
  10536. }
  10537. finishOp(type, size) {
  10538. const str = this.input.slice(this.state.pos, this.state.pos + size);
  10539. this.state.pos += size;
  10540. this.finishToken(type, str);
  10541. }
  10542. readRegexp() {
  10543. const startLoc = this.state.startLoc;
  10544. const start = this.state.start + 1;
  10545. let escaped, inClass;
  10546. let {
  10547. pos
  10548. } = this.state;
  10549. for (;; ++pos) {
  10550. if (pos >= this.length) {
  10551. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  10552. }
  10553. const ch = this.input.charCodeAt(pos);
  10554. if (isNewLine(ch)) {
  10555. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  10556. }
  10557. if (escaped) {
  10558. escaped = false;
  10559. } else {
  10560. if (ch === 91) {
  10561. inClass = true;
  10562. } else if (ch === 93 && inClass) {
  10563. inClass = false;
  10564. } else if (ch === 47 && !inClass) {
  10565. break;
  10566. }
  10567. escaped = ch === 92;
  10568. }
  10569. }
  10570. const content = this.input.slice(start, pos);
  10571. ++pos;
  10572. let mods = "";
  10573. const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start);
  10574. while (pos < this.length) {
  10575. const cp = this.codePointAtPos(pos);
  10576. const char = String.fromCharCode(cp);
  10577. if (VALID_REGEX_FLAGS.has(cp)) {
  10578. if (cp === 118) {
  10579. if (mods.includes("u")) {
  10580. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  10581. }
  10582. } else if (cp === 117) {
  10583. if (mods.includes("v")) {
  10584. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  10585. }
  10586. }
  10587. if (mods.includes(char)) {
  10588. this.raise(Errors.DuplicateRegExpFlags, nextPos());
  10589. }
  10590. } else if (isIdentifierChar(cp) || cp === 92) {
  10591. this.raise(Errors.MalformedRegExpFlags, nextPos());
  10592. } else {
  10593. break;
  10594. }
  10595. ++pos;
  10596. mods += char;
  10597. }
  10598. this.state.pos = pos;
  10599. this.finishToken(138, {
  10600. pattern: content,
  10601. flags: mods
  10602. });
  10603. }
  10604. readInt(radix, len, forceLen = false, allowNumSeparator = true) {
  10605. const {
  10606. n,
  10607. pos
  10608. } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false);
  10609. this.state.pos = pos;
  10610. return n;
  10611. }
  10612. readRadixNumber(radix) {
  10613. const start = this.state.pos;
  10614. const startLoc = this.state.curPosition();
  10615. let isBigInt = false;
  10616. this.state.pos += 2;
  10617. const val = this.readInt(radix);
  10618. if (val == null) {
  10619. this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), {
  10620. radix
  10621. });
  10622. }
  10623. const next = this.input.charCodeAt(this.state.pos);
  10624. if (next === 110) {
  10625. ++this.state.pos;
  10626. isBigInt = true;
  10627. } else if (next === 109) {
  10628. throw this.raise(Errors.InvalidDecimal, startLoc);
  10629. }
  10630. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  10631. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  10632. }
  10633. if (isBigInt) {
  10634. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  10635. this.finishToken(136, str);
  10636. return;
  10637. }
  10638. this.finishToken(135, val);
  10639. }
  10640. readNumber(startsWithDot) {
  10641. const start = this.state.pos;
  10642. const startLoc = this.state.curPosition();
  10643. let isFloat = false;
  10644. let isBigInt = false;
  10645. let hasExponent = false;
  10646. let isOctal = false;
  10647. if (!startsWithDot && this.readInt(10) === null) {
  10648. this.raise(Errors.InvalidNumber, this.state.curPosition());
  10649. }
  10650. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  10651. if (hasLeadingZero) {
  10652. const integer = this.input.slice(start, this.state.pos);
  10653. this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc);
  10654. if (!this.state.strict) {
  10655. const underscorePos = integer.indexOf("_");
  10656. if (underscorePos > 0) {
  10657. this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos));
  10658. }
  10659. }
  10660. isOctal = hasLeadingZero && !/[89]/.test(integer);
  10661. }
  10662. let next = this.input.charCodeAt(this.state.pos);
  10663. if (next === 46 && !isOctal) {
  10664. ++this.state.pos;
  10665. this.readInt(10);
  10666. isFloat = true;
  10667. next = this.input.charCodeAt(this.state.pos);
  10668. }
  10669. if ((next === 69 || next === 101) && !isOctal) {
  10670. next = this.input.charCodeAt(++this.state.pos);
  10671. if (next === 43 || next === 45) {
  10672. ++this.state.pos;
  10673. }
  10674. if (this.readInt(10) === null) {
  10675. this.raise(Errors.InvalidOrMissingExponent, startLoc);
  10676. }
  10677. isFloat = true;
  10678. hasExponent = true;
  10679. next = this.input.charCodeAt(this.state.pos);
  10680. }
  10681. if (next === 110) {
  10682. if (isFloat || hasLeadingZero) {
  10683. this.raise(Errors.InvalidBigIntLiteral, startLoc);
  10684. }
  10685. ++this.state.pos;
  10686. isBigInt = true;
  10687. }
  10688. if (next === 109) {
  10689. this.expectPlugin("decimal", this.state.curPosition());
  10690. if (hasExponent || hasLeadingZero) {
  10691. this.raise(Errors.InvalidDecimal, startLoc);
  10692. }
  10693. ++this.state.pos;
  10694. var isDecimal = true;
  10695. }
  10696. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  10697. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  10698. }
  10699. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  10700. if (isBigInt) {
  10701. this.finishToken(136, str);
  10702. return;
  10703. }
  10704. if (isDecimal) {
  10705. this.finishToken(137, str);
  10706. return;
  10707. }
  10708. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  10709. this.finishToken(135, val);
  10710. }
  10711. readCodePoint(throwOnInvalid) {
  10712. const {
  10713. code,
  10714. pos
  10715. } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint);
  10716. this.state.pos = pos;
  10717. return code;
  10718. }
  10719. readString(quote) {
  10720. const {
  10721. str,
  10722. pos,
  10723. curLine,
  10724. lineStart
  10725. } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string);
  10726. this.state.pos = pos + 1;
  10727. this.state.lineStart = lineStart;
  10728. this.state.curLine = curLine;
  10729. this.finishToken(134, str);
  10730. }
  10731. readTemplateContinuation() {
  10732. if (!this.match(8)) {
  10733. this.unexpected(null, 8);
  10734. }
  10735. this.state.pos--;
  10736. this.readTemplateToken();
  10737. }
  10738. readTemplateToken() {
  10739. const opening = this.input[this.state.pos];
  10740. const {
  10741. str,
  10742. firstInvalidLoc,
  10743. pos,
  10744. curLine,
  10745. lineStart
  10746. } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template);
  10747. this.state.pos = pos + 1;
  10748. this.state.lineStart = lineStart;
  10749. this.state.curLine = curLine;
  10750. if (firstInvalidLoc) {
  10751. this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, this.sourceToOffsetPos(firstInvalidLoc.pos));
  10752. }
  10753. if (this.input.codePointAt(pos) === 96) {
  10754. this.finishToken(24, firstInvalidLoc ? null : opening + str + "`");
  10755. } else {
  10756. this.state.pos++;
  10757. this.finishToken(25, firstInvalidLoc ? null : opening + str + "${");
  10758. }
  10759. }
  10760. recordStrictModeErrors(toParseError, at) {
  10761. const index = at.index;
  10762. if (this.state.strict && !this.state.strictErrors.has(index)) {
  10763. this.raise(toParseError, at);
  10764. } else {
  10765. this.state.strictErrors.set(index, [toParseError, at]);
  10766. }
  10767. }
  10768. readWord1(firstCode) {
  10769. this.state.containsEsc = false;
  10770. let word = "";
  10771. const start = this.state.pos;
  10772. let chunkStart = this.state.pos;
  10773. if (firstCode !== undefined) {
  10774. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  10775. }
  10776. while (this.state.pos < this.length) {
  10777. const ch = this.codePointAtPos(this.state.pos);
  10778. if (isIdentifierChar(ch)) {
  10779. this.state.pos += ch <= 0xffff ? 1 : 2;
  10780. } else if (ch === 92) {
  10781. this.state.containsEsc = true;
  10782. word += this.input.slice(chunkStart, this.state.pos);
  10783. const escStart = this.state.curPosition();
  10784. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  10785. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  10786. this.raise(Errors.MissingUnicodeEscape, this.state.curPosition());
  10787. chunkStart = this.state.pos - 1;
  10788. continue;
  10789. }
  10790. ++this.state.pos;
  10791. const esc = this.readCodePoint(true);
  10792. if (esc !== null) {
  10793. if (!identifierCheck(esc)) {
  10794. this.raise(Errors.EscapedCharNotAnIdentifier, escStart);
  10795. }
  10796. word += String.fromCodePoint(esc);
  10797. }
  10798. chunkStart = this.state.pos;
  10799. } else {
  10800. break;
  10801. }
  10802. }
  10803. return word + this.input.slice(chunkStart, this.state.pos);
  10804. }
  10805. readWord(firstCode) {
  10806. const word = this.readWord1(firstCode);
  10807. const type = keywords$1.get(word);
  10808. if (type !== undefined) {
  10809. this.finishToken(type, tokenLabelName(type));
  10810. } else {
  10811. this.finishToken(132, word);
  10812. }
  10813. }
  10814. checkKeywordEscapes() {
  10815. const {
  10816. type
  10817. } = this.state;
  10818. if (tokenIsKeyword(type) && this.state.containsEsc) {
  10819. this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, {
  10820. reservedWord: tokenLabelName(type)
  10821. });
  10822. }
  10823. }
  10824. raise(toParseError, at, details = {}) {
  10825. const loc = at instanceof Position ? at : at.loc.start;
  10826. const error = toParseError(loc, details);
  10827. if (!(this.optionFlags & 2048)) throw error;
  10828. if (!this.isLookahead) this.state.errors.push(error);
  10829. return error;
  10830. }
  10831. raiseOverwrite(toParseError, at, details = {}) {
  10832. const loc = at instanceof Position ? at : at.loc.start;
  10833. const pos = loc.index;
  10834. const errors = this.state.errors;
  10835. for (let i = errors.length - 1; i >= 0; i--) {
  10836. const error = errors[i];
  10837. if (error.loc.index === pos) {
  10838. return errors[i] = toParseError(loc, details);
  10839. }
  10840. if (error.loc.index < pos) break;
  10841. }
  10842. return this.raise(toParseError, at, details);
  10843. }
  10844. updateContext(prevType) {}
  10845. unexpected(loc, type) {
  10846. throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, {
  10847. expected: type ? tokenLabelName(type) : null
  10848. });
  10849. }
  10850. expectPlugin(pluginName, loc) {
  10851. if (this.hasPlugin(pluginName)) {
  10852. return true;
  10853. }
  10854. throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, {
  10855. missingPlugin: [pluginName]
  10856. });
  10857. }
  10858. expectOnePlugin(pluginNames) {
  10859. if (!pluginNames.some(name => this.hasPlugin(name))) {
  10860. throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, {
  10861. missingPlugin: pluginNames
  10862. });
  10863. }
  10864. }
  10865. errorBuilder(error) {
  10866. return (pos, lineStart, curLine) => {
  10867. this.raise(error, buildPosition(pos, lineStart, curLine));
  10868. };
  10869. }
  10870. }
  10871. class ClassScope {
  10872. constructor() {
  10873. this.privateNames = new Set();
  10874. this.loneAccessors = new Map();
  10875. this.undefinedPrivateNames = new Map();
  10876. }
  10877. }
  10878. class ClassScopeHandler {
  10879. constructor(parser) {
  10880. this.parser = void 0;
  10881. this.stack = [];
  10882. this.undefinedPrivateNames = new Map();
  10883. this.parser = parser;
  10884. }
  10885. current() {
  10886. return this.stack[this.stack.length - 1];
  10887. }
  10888. enter() {
  10889. this.stack.push(new ClassScope());
  10890. }
  10891. exit() {
  10892. const oldClassScope = this.stack.pop();
  10893. const current = this.current();
  10894. for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) {
  10895. if (current) {
  10896. if (!current.undefinedPrivateNames.has(name)) {
  10897. current.undefinedPrivateNames.set(name, loc);
  10898. }
  10899. } else {
  10900. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  10901. identifierName: name
  10902. });
  10903. }
  10904. }
  10905. }
  10906. declarePrivateName(name, elementType, loc) {
  10907. const {
  10908. privateNames,
  10909. loneAccessors,
  10910. undefinedPrivateNames
  10911. } = this.current();
  10912. let redefined = privateNames.has(name);
  10913. if (elementType & 3) {
  10914. const accessor = redefined && loneAccessors.get(name);
  10915. if (accessor) {
  10916. const oldStatic = accessor & 4;
  10917. const newStatic = elementType & 4;
  10918. const oldKind = accessor & 3;
  10919. const newKind = elementType & 3;
  10920. redefined = oldKind === newKind || oldStatic !== newStatic;
  10921. if (!redefined) loneAccessors.delete(name);
  10922. } else if (!redefined) {
  10923. loneAccessors.set(name, elementType);
  10924. }
  10925. }
  10926. if (redefined) {
  10927. this.parser.raise(Errors.PrivateNameRedeclaration, loc, {
  10928. identifierName: name
  10929. });
  10930. }
  10931. privateNames.add(name);
  10932. undefinedPrivateNames.delete(name);
  10933. }
  10934. usePrivateName(name, loc) {
  10935. let classScope;
  10936. for (classScope of this.stack) {
  10937. if (classScope.privateNames.has(name)) return;
  10938. }
  10939. if (classScope) {
  10940. classScope.undefinedPrivateNames.set(name, loc);
  10941. } else {
  10942. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  10943. identifierName: name
  10944. });
  10945. }
  10946. }
  10947. }
  10948. class ExpressionScope {
  10949. constructor(type = 0) {
  10950. this.type = type;
  10951. }
  10952. canBeArrowParameterDeclaration() {
  10953. return this.type === 2 || this.type === 1;
  10954. }
  10955. isCertainlyParameterDeclaration() {
  10956. return this.type === 3;
  10957. }
  10958. }
  10959. class ArrowHeadParsingScope extends ExpressionScope {
  10960. constructor(type) {
  10961. super(type);
  10962. this.declarationErrors = new Map();
  10963. }
  10964. recordDeclarationError(ParsingErrorClass, at) {
  10965. const index = at.index;
  10966. this.declarationErrors.set(index, [ParsingErrorClass, at]);
  10967. }
  10968. clearDeclarationError(index) {
  10969. this.declarationErrors.delete(index);
  10970. }
  10971. iterateErrors(iterator) {
  10972. this.declarationErrors.forEach(iterator);
  10973. }
  10974. }
  10975. class ExpressionScopeHandler {
  10976. constructor(parser) {
  10977. this.parser = void 0;
  10978. this.stack = [new ExpressionScope()];
  10979. this.parser = parser;
  10980. }
  10981. enter(scope) {
  10982. this.stack.push(scope);
  10983. }
  10984. exit() {
  10985. this.stack.pop();
  10986. }
  10987. recordParameterInitializerError(toParseError, node) {
  10988. const origin = node.loc.start;
  10989. const {
  10990. stack
  10991. } = this;
  10992. let i = stack.length - 1;
  10993. let scope = stack[i];
  10994. while (!scope.isCertainlyParameterDeclaration()) {
  10995. if (scope.canBeArrowParameterDeclaration()) {
  10996. scope.recordDeclarationError(toParseError, origin);
  10997. } else {
  10998. return;
  10999. }
  11000. scope = stack[--i];
  11001. }
  11002. this.parser.raise(toParseError, origin);
  11003. }
  11004. recordArrowParameterBindingError(error, node) {
  11005. const {
  11006. stack
  11007. } = this;
  11008. const scope = stack[stack.length - 1];
  11009. const origin = node.loc.start;
  11010. if (scope.isCertainlyParameterDeclaration()) {
  11011. this.parser.raise(error, origin);
  11012. } else if (scope.canBeArrowParameterDeclaration()) {
  11013. scope.recordDeclarationError(error, origin);
  11014. } else {
  11015. return;
  11016. }
  11017. }
  11018. recordAsyncArrowParametersError(at) {
  11019. const {
  11020. stack
  11021. } = this;
  11022. let i = stack.length - 1;
  11023. let scope = stack[i];
  11024. while (scope.canBeArrowParameterDeclaration()) {
  11025. if (scope.type === 2) {
  11026. scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at);
  11027. }
  11028. scope = stack[--i];
  11029. }
  11030. }
  11031. validateAsPattern() {
  11032. const {
  11033. stack
  11034. } = this;
  11035. const currentScope = stack[stack.length - 1];
  11036. if (!currentScope.canBeArrowParameterDeclaration()) return;
  11037. currentScope.iterateErrors(([toParseError, loc]) => {
  11038. this.parser.raise(toParseError, loc);
  11039. let i = stack.length - 2;
  11040. let scope = stack[i];
  11041. while (scope.canBeArrowParameterDeclaration()) {
  11042. scope.clearDeclarationError(loc.index);
  11043. scope = stack[--i];
  11044. }
  11045. });
  11046. }
  11047. }
  11048. function newParameterDeclarationScope() {
  11049. return new ExpressionScope(3);
  11050. }
  11051. function newArrowHeadScope() {
  11052. return new ArrowHeadParsingScope(1);
  11053. }
  11054. function newAsyncArrowScope() {
  11055. return new ArrowHeadParsingScope(2);
  11056. }
  11057. function newExpressionScope() {
  11058. return new ExpressionScope();
  11059. }
  11060. class UtilParser extends Tokenizer {
  11061. addExtra(node, key, value, enumerable = true) {
  11062. if (!node) return;
  11063. let {
  11064. extra
  11065. } = node;
  11066. if (extra == null) {
  11067. extra = {};
  11068. node.extra = extra;
  11069. }
  11070. if (enumerable) {
  11071. extra[key] = value;
  11072. } else {
  11073. Object.defineProperty(extra, key, {
  11074. enumerable,
  11075. value
  11076. });
  11077. }
  11078. }
  11079. isContextual(token) {
  11080. return this.state.type === token && !this.state.containsEsc;
  11081. }
  11082. isUnparsedContextual(nameStart, name) {
  11083. if (this.input.startsWith(name, nameStart)) {
  11084. const nextCh = this.input.charCodeAt(nameStart + name.length);
  11085. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  11086. }
  11087. return false;
  11088. }
  11089. isLookaheadContextual(name) {
  11090. const next = this.nextTokenStart();
  11091. return this.isUnparsedContextual(next, name);
  11092. }
  11093. eatContextual(token) {
  11094. if (this.isContextual(token)) {
  11095. this.next();
  11096. return true;
  11097. }
  11098. return false;
  11099. }
  11100. expectContextual(token, toParseError) {
  11101. if (!this.eatContextual(token)) {
  11102. if (toParseError != null) {
  11103. throw this.raise(toParseError, this.state.startLoc);
  11104. }
  11105. this.unexpected(null, token);
  11106. }
  11107. }
  11108. canInsertSemicolon() {
  11109. return this.match(140) || this.match(8) || this.hasPrecedingLineBreak();
  11110. }
  11111. hasPrecedingLineBreak() {
  11112. return hasNewLine(this.input, this.offsetToSourcePos(this.state.lastTokEndLoc.index), this.state.start);
  11113. }
  11114. hasFollowingLineBreak() {
  11115. return hasNewLine(this.input, this.state.end, this.nextTokenStart());
  11116. }
  11117. isLineTerminator() {
  11118. return this.eat(13) || this.canInsertSemicolon();
  11119. }
  11120. semicolon(allowAsi = true) {
  11121. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  11122. this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc);
  11123. }
  11124. expect(type, loc) {
  11125. if (!this.eat(type)) {
  11126. this.unexpected(loc, type);
  11127. }
  11128. }
  11129. tryParse(fn, oldState = this.state.clone()) {
  11130. const abortSignal = {
  11131. node: null
  11132. };
  11133. try {
  11134. const node = fn((node = null) => {
  11135. abortSignal.node = node;
  11136. throw abortSignal;
  11137. });
  11138. if (this.state.errors.length > oldState.errors.length) {
  11139. const failState = this.state;
  11140. this.state = oldState;
  11141. this.state.tokensLength = failState.tokensLength;
  11142. return {
  11143. node,
  11144. error: failState.errors[oldState.errors.length],
  11145. thrown: false,
  11146. aborted: false,
  11147. failState
  11148. };
  11149. }
  11150. return {
  11151. node: node,
  11152. error: null,
  11153. thrown: false,
  11154. aborted: false,
  11155. failState: null
  11156. };
  11157. } catch (error) {
  11158. const failState = this.state;
  11159. this.state = oldState;
  11160. if (error instanceof SyntaxError) {
  11161. return {
  11162. node: null,
  11163. error,
  11164. thrown: true,
  11165. aborted: false,
  11166. failState
  11167. };
  11168. }
  11169. if (error === abortSignal) {
  11170. return {
  11171. node: abortSignal.node,
  11172. error: null,
  11173. thrown: false,
  11174. aborted: true,
  11175. failState
  11176. };
  11177. }
  11178. throw error;
  11179. }
  11180. }
  11181. checkExpressionErrors(refExpressionErrors, andThrow) {
  11182. if (!refExpressionErrors) return false;
  11183. const {
  11184. shorthandAssignLoc,
  11185. doubleProtoLoc,
  11186. privateKeyLoc,
  11187. optionalParametersLoc,
  11188. voidPatternLoc
  11189. } = refExpressionErrors;
  11190. const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc || !!voidPatternLoc;
  11191. if (!andThrow) {
  11192. return hasErrors;
  11193. }
  11194. if (shorthandAssignLoc != null) {
  11195. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  11196. }
  11197. if (doubleProtoLoc != null) {
  11198. this.raise(Errors.DuplicateProto, doubleProtoLoc);
  11199. }
  11200. if (privateKeyLoc != null) {
  11201. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  11202. }
  11203. if (optionalParametersLoc != null) {
  11204. this.unexpected(optionalParametersLoc);
  11205. }
  11206. if (voidPatternLoc != null) {
  11207. this.raise(Errors.InvalidCoverDiscardElement, voidPatternLoc);
  11208. }
  11209. }
  11210. isLiteralPropertyName() {
  11211. return tokenIsLiteralPropertyName(this.state.type);
  11212. }
  11213. isPrivateName(node) {
  11214. return node.type === "PrivateName";
  11215. }
  11216. getPrivateNameSV(node) {
  11217. return node.id.name;
  11218. }
  11219. hasPropertyAsPrivateName(node) {
  11220. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  11221. }
  11222. isObjectProperty(node) {
  11223. return node.type === "ObjectProperty";
  11224. }
  11225. isObjectMethod(node) {
  11226. return node.type === "ObjectMethod";
  11227. }
  11228. initializeScopes(inModule = this.options.sourceType === "module") {
  11229. const oldLabels = this.state.labels;
  11230. this.state.labels = [];
  11231. const oldExportedIdentifiers = this.exportedIdentifiers;
  11232. this.exportedIdentifiers = new Set();
  11233. const oldInModule = this.inModule;
  11234. this.inModule = inModule;
  11235. const oldScope = this.scope;
  11236. const ScopeHandler = this.getScopeHandler();
  11237. this.scope = new ScopeHandler(this, inModule);
  11238. const oldProdParam = this.prodParam;
  11239. this.prodParam = new ProductionParameterHandler();
  11240. const oldClassScope = this.classScope;
  11241. this.classScope = new ClassScopeHandler(this);
  11242. const oldExpressionScope = this.expressionScope;
  11243. this.expressionScope = new ExpressionScopeHandler(this);
  11244. return () => {
  11245. this.state.labels = oldLabels;
  11246. this.exportedIdentifiers = oldExportedIdentifiers;
  11247. this.inModule = oldInModule;
  11248. this.scope = oldScope;
  11249. this.prodParam = oldProdParam;
  11250. this.classScope = oldClassScope;
  11251. this.expressionScope = oldExpressionScope;
  11252. };
  11253. }
  11254. enterInitialScopes() {
  11255. let paramFlags = 0;
  11256. if (this.inModule || this.optionFlags & 1) {
  11257. paramFlags |= 2;
  11258. }
  11259. if (this.optionFlags & 32) {
  11260. paramFlags |= 1;
  11261. }
  11262. const isCommonJS = !this.inModule && this.options.sourceType === "commonjs";
  11263. if (isCommonJS || this.optionFlags & 2) {
  11264. paramFlags |= 4;
  11265. }
  11266. this.prodParam.enter(paramFlags);
  11267. let scopeFlags = isCommonJS ? 514 : 1;
  11268. if (this.optionFlags & 4) {
  11269. scopeFlags |= 512;
  11270. }
  11271. this.scope.enter(scopeFlags);
  11272. }
  11273. checkDestructuringPrivate(refExpressionErrors) {
  11274. const {
  11275. privateKeyLoc
  11276. } = refExpressionErrors;
  11277. if (privateKeyLoc !== null) {
  11278. this.expectPlugin("destructuringPrivate", privateKeyLoc);
  11279. }
  11280. }
  11281. }
  11282. class ExpressionErrors {
  11283. constructor() {
  11284. this.shorthandAssignLoc = null;
  11285. this.doubleProtoLoc = null;
  11286. this.privateKeyLoc = null;
  11287. this.optionalParametersLoc = null;
  11288. this.voidPatternLoc = null;
  11289. }
  11290. }
  11291. class Node {
  11292. constructor(parser, pos, loc) {
  11293. this.type = "";
  11294. this.start = pos;
  11295. this.end = 0;
  11296. this.loc = new SourceLocation(loc);
  11297. if ((parser == null ? void 0 : parser.optionFlags) & 128) this.range = [pos, 0];
  11298. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  11299. }
  11300. }
  11301. const NodePrototype = Node.prototype;
  11302. NodePrototype.__clone = function () {
  11303. const newNode = new Node(undefined, this.start, this.loc.start);
  11304. const keys = Object.keys(this);
  11305. for (let i = 0, length = keys.length; i < length; i++) {
  11306. const key = keys[i];
  11307. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  11308. newNode[key] = this[key];
  11309. }
  11310. }
  11311. return newNode;
  11312. };
  11313. class NodeUtils extends UtilParser {
  11314. startNode() {
  11315. const loc = this.state.startLoc;
  11316. return new Node(this, loc.index, loc);
  11317. }
  11318. startNodeAt(loc) {
  11319. return new Node(this, loc.index, loc);
  11320. }
  11321. startNodeAtNode(type) {
  11322. return this.startNodeAt(type.loc.start);
  11323. }
  11324. finishNode(node, type) {
  11325. return this.finishNodeAt(node, type, this.state.lastTokEndLoc);
  11326. }
  11327. finishNodeAt(node, type, endLoc) {
  11328. node.type = type;
  11329. node.end = endLoc.index;
  11330. node.loc.end = endLoc;
  11331. if (this.optionFlags & 128) node.range[1] = endLoc.index;
  11332. if (this.optionFlags & 4096) {
  11333. this.processComment(node);
  11334. }
  11335. return node;
  11336. }
  11337. resetStartLocation(node, startLoc) {
  11338. node.start = startLoc.index;
  11339. node.loc.start = startLoc;
  11340. if (this.optionFlags & 128) node.range[0] = startLoc.index;
  11341. }
  11342. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  11343. node.end = endLoc.index;
  11344. node.loc.end = endLoc;
  11345. if (this.optionFlags & 128) node.range[1] = endLoc.index;
  11346. }
  11347. resetStartLocationFromNode(node, locationNode) {
  11348. this.resetStartLocation(node, locationNode.loc.start);
  11349. }
  11350. castNodeTo(node, type) {
  11351. node.type = type;
  11352. return node;
  11353. }
  11354. cloneIdentifier(node) {
  11355. const {
  11356. type,
  11357. start,
  11358. end,
  11359. loc,
  11360. range,
  11361. name
  11362. } = node;
  11363. const cloned = Object.create(NodePrototype);
  11364. cloned.type = type;
  11365. cloned.start = start;
  11366. cloned.end = end;
  11367. cloned.loc = loc;
  11368. cloned.range = range;
  11369. cloned.name = name;
  11370. if (node.extra) cloned.extra = node.extra;
  11371. return cloned;
  11372. }
  11373. cloneStringLiteral(node) {
  11374. const {
  11375. type,
  11376. start,
  11377. end,
  11378. loc,
  11379. range,
  11380. extra
  11381. } = node;
  11382. const cloned = Object.create(NodePrototype);
  11383. cloned.type = type;
  11384. cloned.start = start;
  11385. cloned.end = end;
  11386. cloned.loc = loc;
  11387. cloned.range = range;
  11388. cloned.extra = extra;
  11389. cloned.value = node.value;
  11390. return cloned;
  11391. }
  11392. }
  11393. const unwrapParenthesizedExpression = node => {
  11394. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  11395. };
  11396. class LValParser extends NodeUtils {
  11397. toAssignable(node, isLHS = false) {
  11398. var _node$extra, _node$extra3;
  11399. let parenthesized = undefined;
  11400. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  11401. parenthesized = unwrapParenthesizedExpression(node);
  11402. if (isLHS) {
  11403. if (parenthesized.type === "Identifier") {
  11404. this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node);
  11405. } else if (parenthesized.type !== "CallExpression" && parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) {
  11406. this.raise(Errors.InvalidParenthesizedAssignment, node);
  11407. }
  11408. } else {
  11409. this.raise(Errors.InvalidParenthesizedAssignment, node);
  11410. }
  11411. }
  11412. switch (node.type) {
  11413. case "Identifier":
  11414. case "ObjectPattern":
  11415. case "ArrayPattern":
  11416. case "AssignmentPattern":
  11417. case "RestElement":
  11418. case "VoidPattern":
  11419. break;
  11420. case "ObjectExpression":
  11421. this.castNodeTo(node, "ObjectPattern");
  11422. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  11423. var _node$extra2;
  11424. const prop = node.properties[i];
  11425. const isLast = i === last;
  11426. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  11427. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) {
  11428. this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc);
  11429. }
  11430. }
  11431. break;
  11432. case "ObjectProperty":
  11433. {
  11434. const {
  11435. key,
  11436. value
  11437. } = node;
  11438. if (this.isPrivateName(key)) {
  11439. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  11440. }
  11441. this.toAssignable(value, isLHS);
  11442. break;
  11443. }
  11444. case "SpreadElement":
  11445. {
  11446. throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller.");
  11447. }
  11448. case "ArrayExpression":
  11449. this.castNodeTo(node, "ArrayPattern");
  11450. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS);
  11451. break;
  11452. case "AssignmentExpression":
  11453. if (node.operator !== "=") {
  11454. this.raise(Errors.MissingEqInAssignment, node.left.loc.end);
  11455. }
  11456. this.castNodeTo(node, "AssignmentPattern");
  11457. delete node.operator;
  11458. if (node.left.type === "VoidPattern") {
  11459. this.raise(Errors.VoidPatternInitializer, node.left);
  11460. }
  11461. this.toAssignable(node.left, isLHS);
  11462. break;
  11463. case "ParenthesizedExpression":
  11464. this.toAssignable(parenthesized, isLHS);
  11465. break;
  11466. }
  11467. }
  11468. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  11469. if (prop.type === "ObjectMethod") {
  11470. this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key);
  11471. } else if (prop.type === "SpreadElement") {
  11472. this.castNodeTo(prop, "RestElement");
  11473. const arg = prop.argument;
  11474. this.checkToRestConversion(arg, false);
  11475. this.toAssignable(arg, isLHS);
  11476. if (!isLast) {
  11477. this.raise(Errors.RestTrailingComma, prop);
  11478. }
  11479. } else {
  11480. this.toAssignable(prop, isLHS);
  11481. }
  11482. }
  11483. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  11484. const end = exprList.length - 1;
  11485. for (let i = 0; i <= end; i++) {
  11486. const elt = exprList[i];
  11487. if (!elt) continue;
  11488. this.toAssignableListItem(exprList, i, isLHS);
  11489. if (elt.type === "RestElement") {
  11490. if (i < end) {
  11491. this.raise(Errors.RestTrailingComma, elt);
  11492. } else if (trailingCommaLoc) {
  11493. this.raise(Errors.RestTrailingComma, trailingCommaLoc);
  11494. }
  11495. }
  11496. }
  11497. }
  11498. toAssignableListItem(exprList, index, isLHS) {
  11499. const node = exprList[index];
  11500. if (node.type === "SpreadElement") {
  11501. this.castNodeTo(node, "RestElement");
  11502. const arg = node.argument;
  11503. this.checkToRestConversion(arg, true);
  11504. this.toAssignable(arg, isLHS);
  11505. } else {
  11506. this.toAssignable(node, isLHS);
  11507. }
  11508. }
  11509. isAssignable(node, isBinding) {
  11510. switch (node.type) {
  11511. case "Identifier":
  11512. case "ObjectPattern":
  11513. case "ArrayPattern":
  11514. case "AssignmentPattern":
  11515. case "RestElement":
  11516. case "VoidPattern":
  11517. return true;
  11518. case "ObjectExpression":
  11519. {
  11520. const last = node.properties.length - 1;
  11521. return node.properties.every((prop, i) => {
  11522. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  11523. });
  11524. }
  11525. case "ObjectProperty":
  11526. return this.isAssignable(node.value);
  11527. case "SpreadElement":
  11528. return this.isAssignable(node.argument);
  11529. case "ArrayExpression":
  11530. return node.elements.every(element => element === null || this.isAssignable(element));
  11531. case "AssignmentExpression":
  11532. return node.operator === "=";
  11533. case "ParenthesizedExpression":
  11534. return this.isAssignable(node.expression);
  11535. case "MemberExpression":
  11536. case "OptionalMemberExpression":
  11537. return !isBinding;
  11538. default:
  11539. return false;
  11540. }
  11541. }
  11542. toReferencedList(exprList, isParenthesizedExpr) {
  11543. return exprList;
  11544. }
  11545. toReferencedListDeep(exprList, isParenthesizedExpr) {
  11546. this.toReferencedList(exprList, isParenthesizedExpr);
  11547. for (const expr of exprList) {
  11548. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  11549. this.toReferencedListDeep(expr.elements);
  11550. }
  11551. }
  11552. }
  11553. parseSpread(refExpressionErrors) {
  11554. const node = this.startNode();
  11555. this.next();
  11556. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined);
  11557. return this.finishNode(node, "SpreadElement");
  11558. }
  11559. parseRestBinding() {
  11560. const node = this.startNode();
  11561. this.next();
  11562. const argument = this.parseBindingAtom();
  11563. if (argument.type === "VoidPattern") {
  11564. this.raise(Errors.UnexpectedVoidPattern, argument);
  11565. }
  11566. node.argument = argument;
  11567. return this.finishNode(node, "RestElement");
  11568. }
  11569. parseBindingAtom() {
  11570. switch (this.state.type) {
  11571. case 0:
  11572. {
  11573. const node = this.startNode();
  11574. this.next();
  11575. node.elements = this.parseBindingList(3, 93, 1);
  11576. return this.finishNode(node, "ArrayPattern");
  11577. }
  11578. case 5:
  11579. return this.parseObjectLike(8, true);
  11580. case 88:
  11581. return this.parseVoidPattern(null);
  11582. }
  11583. return this.parseIdentifier();
  11584. }
  11585. parseBindingList(close, closeCharCode, flags) {
  11586. const allowEmpty = flags & 1;
  11587. const elts = [];
  11588. let first = true;
  11589. while (!this.eat(close)) {
  11590. if (first) {
  11591. first = false;
  11592. } else {
  11593. this.expect(12);
  11594. }
  11595. if (allowEmpty && this.match(12)) {
  11596. elts.push(null);
  11597. } else if (this.eat(close)) {
  11598. break;
  11599. } else if (this.match(21)) {
  11600. let rest = this.parseRestBinding();
  11601. if (this.hasPlugin("flow") || flags & 2) {
  11602. rest = this.parseFunctionParamType(rest);
  11603. }
  11604. elts.push(rest);
  11605. if (!this.checkCommaAfterRest(closeCharCode)) {
  11606. this.expect(close);
  11607. break;
  11608. }
  11609. } else {
  11610. const decorators = [];
  11611. if (flags & 2) {
  11612. if (this.match(26) && this.hasPlugin("decorators")) {
  11613. this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc);
  11614. }
  11615. while (this.match(26)) {
  11616. decorators.push(this.parseDecorator());
  11617. }
  11618. }
  11619. elts.push(this.parseBindingElement(flags, decorators));
  11620. }
  11621. }
  11622. return elts;
  11623. }
  11624. parseBindingRestProperty(prop) {
  11625. this.next();
  11626. if (this.hasPlugin("discardBinding") && this.match(88)) {
  11627. prop.argument = this.parseVoidPattern(null);
  11628. this.raise(Errors.UnexpectedVoidPattern, prop.argument);
  11629. } else {
  11630. prop.argument = this.parseIdentifier();
  11631. }
  11632. this.checkCommaAfterRest(125);
  11633. return this.finishNode(prop, "RestElement");
  11634. }
  11635. parseBindingProperty() {
  11636. const {
  11637. type,
  11638. startLoc
  11639. } = this.state;
  11640. if (type === 21) {
  11641. return this.parseBindingRestProperty(this.startNode());
  11642. }
  11643. const prop = this.startNode();
  11644. if (type === 139) {
  11645. this.expectPlugin("destructuringPrivate", startLoc);
  11646. this.classScope.usePrivateName(this.state.value, startLoc);
  11647. prop.key = this.parsePrivateName();
  11648. } else {
  11649. this.parsePropertyName(prop);
  11650. }
  11651. prop.method = false;
  11652. return this.parseObjPropValue(prop, startLoc, false, false, true, false);
  11653. }
  11654. parseBindingElement(flags, decorators) {
  11655. const left = this.parseMaybeDefault();
  11656. if (this.hasPlugin("flow") || flags & 2) {
  11657. this.parseFunctionParamType(left);
  11658. }
  11659. if (decorators.length) {
  11660. left.decorators = decorators;
  11661. this.resetStartLocationFromNode(left, decorators[0]);
  11662. }
  11663. const elt = this.parseMaybeDefault(left.loc.start, left);
  11664. return elt;
  11665. }
  11666. parseFunctionParamType(param) {
  11667. return param;
  11668. }
  11669. parseMaybeDefault(startLoc, left) {
  11670. startLoc != null ? startLoc : startLoc = this.state.startLoc;
  11671. left = left != null ? left : this.parseBindingAtom();
  11672. if (!this.eat(29)) return left;
  11673. const node = this.startNodeAt(startLoc);
  11674. if (left.type === "VoidPattern") {
  11675. this.raise(Errors.VoidPatternInitializer, left);
  11676. }
  11677. node.left = left;
  11678. node.right = this.parseMaybeAssignAllowIn();
  11679. return this.finishNode(node, "AssignmentPattern");
  11680. }
  11681. isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) {
  11682. switch (type) {
  11683. case "AssignmentPattern":
  11684. return "left";
  11685. case "RestElement":
  11686. return "argument";
  11687. case "ObjectProperty":
  11688. return "value";
  11689. case "ParenthesizedExpression":
  11690. return "expression";
  11691. case "ArrayPattern":
  11692. return "elements";
  11693. case "ObjectPattern":
  11694. return "properties";
  11695. case "VoidPattern":
  11696. return true;
  11697. case "CallExpression":
  11698. if (!disallowCallExpression && !this.state.strict && this.optionFlags & 8192) {
  11699. return true;
  11700. }
  11701. }
  11702. return false;
  11703. }
  11704. isOptionalMemberExpression(expression) {
  11705. return expression.type === "OptionalMemberExpression";
  11706. }
  11707. checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false, disallowCallExpression = false) {
  11708. var _expression$extra;
  11709. const type = expression.type;
  11710. if (this.isObjectMethod(expression)) return;
  11711. const isOptionalMemberExpression = this.isOptionalMemberExpression(expression);
  11712. if (isOptionalMemberExpression || type === "MemberExpression") {
  11713. if (isOptionalMemberExpression) {
  11714. this.expectPlugin("optionalChainingAssign", expression.loc.start);
  11715. if (ancestor.type !== "AssignmentExpression") {
  11716. this.raise(Errors.InvalidLhsOptionalChaining, expression, {
  11717. ancestor
  11718. });
  11719. }
  11720. }
  11721. if (binding !== 64) {
  11722. this.raise(Errors.InvalidPropertyBindingPattern, expression);
  11723. }
  11724. return;
  11725. }
  11726. if (type === "Identifier") {
  11727. this.checkIdentifier(expression, binding, strictModeChanged);
  11728. const {
  11729. name
  11730. } = expression;
  11731. if (checkClashes) {
  11732. if (checkClashes.has(name)) {
  11733. this.raise(Errors.ParamDupe, expression);
  11734. } else {
  11735. checkClashes.add(name);
  11736. }
  11737. }
  11738. return;
  11739. } else if (type === "VoidPattern" && ancestor.type === "CatchClause") {
  11740. this.raise(Errors.VoidPatternCatchClauseParam, expression);
  11741. }
  11742. const unwrappedExpression = unwrapParenthesizedExpression(expression);
  11743. disallowCallExpression || (disallowCallExpression = unwrappedExpression.type === "CallExpression" && (unwrappedExpression.callee.type === "Import" || unwrappedExpression.callee.type === "Super"));
  11744. const validity = this.isValidLVal(type, disallowCallExpression, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding);
  11745. if (validity === true) return;
  11746. if (validity === false) {
  11747. const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
  11748. this.raise(ParseErrorClass, expression, {
  11749. ancestor
  11750. });
  11751. return;
  11752. }
  11753. let key, isParenthesizedExpression;
  11754. if (typeof validity === "string") {
  11755. key = validity;
  11756. isParenthesizedExpression = type === "ParenthesizedExpression";
  11757. } else {
  11758. [key, isParenthesizedExpression] = validity;
  11759. }
  11760. const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? {
  11761. type
  11762. } : ancestor;
  11763. const val = expression[key];
  11764. if (Array.isArray(val)) {
  11765. for (const child of val) {
  11766. if (child) {
  11767. this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, true);
  11768. }
  11769. }
  11770. } else if (val) {
  11771. this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, disallowCallExpression);
  11772. }
  11773. }
  11774. checkIdentifier(at, bindingType, strictModeChanged = false) {
  11775. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) {
  11776. if (bindingType === 64) {
  11777. this.raise(Errors.StrictEvalArguments, at, {
  11778. referenceName: at.name
  11779. });
  11780. } else {
  11781. this.raise(Errors.StrictEvalArgumentsBinding, at, {
  11782. bindingName: at.name
  11783. });
  11784. }
  11785. }
  11786. if (bindingType & 8192 && at.name === "let") {
  11787. this.raise(Errors.LetInLexicalBinding, at);
  11788. }
  11789. if (!(bindingType & 64)) {
  11790. this.declareNameFromIdentifier(at, bindingType);
  11791. }
  11792. }
  11793. declareNameFromIdentifier(identifier, binding) {
  11794. this.scope.declareName(identifier.name, binding, identifier.loc.start);
  11795. }
  11796. checkToRestConversion(node, allowPattern) {
  11797. switch (node.type) {
  11798. case "ParenthesizedExpression":
  11799. this.checkToRestConversion(node.expression, allowPattern);
  11800. break;
  11801. case "Identifier":
  11802. case "MemberExpression":
  11803. break;
  11804. case "ArrayExpression":
  11805. case "ObjectExpression":
  11806. if (allowPattern) break;
  11807. default:
  11808. this.raise(Errors.InvalidRestAssignmentPattern, node);
  11809. }
  11810. }
  11811. checkCommaAfterRest(close) {
  11812. if (!this.match(12)) {
  11813. return false;
  11814. }
  11815. this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc);
  11816. return true;
  11817. }
  11818. }
  11819. const keywordAndTSRelationalOperator = /in(?:stanceof)?|as|satisfies/y;
  11820. function nonNull(x) {
  11821. if (x == null) {
  11822. throw new Error(`Unexpected ${x} value.`);
  11823. }
  11824. return x;
  11825. }
  11826. function assert(x) {
  11827. if (!x) {
  11828. throw new Error("Assert fail");
  11829. }
  11830. }
  11831. const TSErrors = ParseErrorEnum`typescript`({
  11832. AbstractMethodHasImplementation: ({
  11833. methodName
  11834. }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`,
  11835. AbstractPropertyHasInitializer: ({
  11836. propertyName
  11837. }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`,
  11838. AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.",
  11839. AccessorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  11840. AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  11841. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  11842. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  11843. ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",
  11844. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  11845. DeclareAccessor: ({
  11846. kind
  11847. }) => `'declare' is not allowed in ${kind}ters.`,
  11848. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  11849. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  11850. DuplicateAccessibilityModifier: ({
  11851. modifier
  11852. }) => `Accessibility modifier already seen: '${modifier}'.`,
  11853. DuplicateModifier: ({
  11854. modifier
  11855. }) => `Duplicate modifier: '${modifier}'.`,
  11856. EmptyHeritageClauseType: ({
  11857. token
  11858. }) => `'${token}' list cannot be empty.`,
  11859. EmptyTypeArguments: "Type argument list cannot be empty.",
  11860. EmptyTypeParameters: "Type parameter list cannot be empty.",
  11861. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  11862. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  11863. ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier",
  11864. IncompatibleModifiers: ({
  11865. modifiers
  11866. }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,
  11867. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  11868. IndexSignatureHasAccessibility: ({
  11869. modifier
  11870. }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`,
  11871. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  11872. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  11873. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  11874. InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.",
  11875. InvalidHeritageClauseType: ({
  11876. token
  11877. }) => `'${token}' list can only include identifiers or qualified-names with optional type arguments.`,
  11878. InvalidModifierOnAwaitUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on an await using declaration.`,
  11879. InvalidModifierOnTypeMember: ({
  11880. modifier
  11881. }) => `'${modifier}' modifier cannot appear on a type member.`,
  11882. InvalidModifierOnTypeParameter: ({
  11883. modifier
  11884. }) => `'${modifier}' modifier cannot appear on a type parameter.`,
  11885. InvalidModifierOnTypeParameterPositions: ({
  11886. modifier
  11887. }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,
  11888. InvalidModifierOnUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on a using declaration.`,
  11889. InvalidModifiersOrder: ({
  11890. orderedModifiers
  11891. }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,
  11892. InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.",
  11893. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  11894. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  11895. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  11896. NonClassMethodPropertyHasAbstractModifier: "'abstract' modifier can only appear on a class, method, or property declaration.",
  11897. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  11898. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  11899. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  11900. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  11901. PrivateElementHasAccessibility: ({
  11902. modifier
  11903. }) => `Private elements cannot have an accessibility modifier ('${modifier}').`,
  11904. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  11905. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  11906. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  11907. SetAccessorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  11908. SetAccessorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  11909. SetAccessorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  11910. SingleTypeParameterWithoutTrailingComma: ({
  11911. typeParameterName
  11912. }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,
  11913. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  11914. TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",
  11915. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  11916. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  11917. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  11918. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  11919. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  11920. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  11921. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  11922. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  11923. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  11924. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  11925. UnsupportedSignatureParameterKind: ({
  11926. type
  11927. }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`,
  11928. UsingDeclarationInAmbientContext: kind => `'${kind}' declarations are not allowed in ambient contexts.`
  11929. });
  11930. function keywordTypeFromName(value) {
  11931. switch (value) {
  11932. case "any":
  11933. return "TSAnyKeyword";
  11934. case "boolean":
  11935. return "TSBooleanKeyword";
  11936. case "bigint":
  11937. return "TSBigIntKeyword";
  11938. case "never":
  11939. return "TSNeverKeyword";
  11940. case "number":
  11941. return "TSNumberKeyword";
  11942. case "object":
  11943. return "TSObjectKeyword";
  11944. case "string":
  11945. return "TSStringKeyword";
  11946. case "symbol":
  11947. return "TSSymbolKeyword";
  11948. case "undefined":
  11949. return "TSUndefinedKeyword";
  11950. case "unknown":
  11951. return "TSUnknownKeyword";
  11952. default:
  11953. return undefined;
  11954. }
  11955. }
  11956. function tsIsAccessModifier(modifier) {
  11957. return modifier === "private" || modifier === "public" || modifier === "protected";
  11958. }
  11959. function tsIsVarianceAnnotations(modifier) {
  11960. return modifier === "in" || modifier === "out";
  11961. }
  11962. var typescript = superClass => class TypeScriptParserMixin extends superClass {
  11963. constructor(...args) {
  11964. super(...args);
  11965. this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, {
  11966. allowedModifiers: ["in", "out"],
  11967. disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"],
  11968. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  11969. });
  11970. this.tsParseConstModifier = this.tsParseModifiers.bind(this, {
  11971. allowedModifiers: ["const"],
  11972. disallowedModifiers: ["in", "out"],
  11973. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  11974. });
  11975. this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, {
  11976. allowedModifiers: ["in", "out", "const"],
  11977. disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"],
  11978. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  11979. });
  11980. }
  11981. getScopeHandler() {
  11982. return TypeScriptScopeHandler;
  11983. }
  11984. tsIsIdentifier() {
  11985. return tokenIsIdentifier(this.state.type);
  11986. }
  11987. tsTokenCanFollowModifier() {
  11988. return this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(139) || this.isLiteralPropertyName();
  11989. }
  11990. tsNextTokenOnSameLineAndCanFollowModifier() {
  11991. this.next();
  11992. if (this.hasPrecedingLineBreak()) {
  11993. return false;
  11994. }
  11995. return this.tsTokenCanFollowModifier();
  11996. }
  11997. tsNextTokenCanFollowModifier() {
  11998. if (this.match(106)) {
  11999. this.next();
  12000. return this.tsTokenCanFollowModifier();
  12001. }
  12002. return this.tsNextTokenOnSameLineAndCanFollowModifier();
  12003. }
  12004. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock, hasSeenStaticModifier) {
  12005. if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) {
  12006. return undefined;
  12007. }
  12008. const modifier = this.state.value;
  12009. if (allowedModifiers.includes(modifier)) {
  12010. if (hasSeenStaticModifier && this.match(106)) {
  12011. return undefined;
  12012. }
  12013. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  12014. return undefined;
  12015. }
  12016. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  12017. return modifier;
  12018. }
  12019. }
  12020. return undefined;
  12021. }
  12022. tsParseModifiers({
  12023. allowedModifiers,
  12024. disallowedModifiers,
  12025. stopOnStartOfClassStaticBlock,
  12026. errorTemplate = TSErrors.InvalidModifierOnTypeMember
  12027. }, modified) {
  12028. const enforceOrder = (loc, modifier, before, after) => {
  12029. if (modifier === before && modified[after]) {
  12030. this.raise(TSErrors.InvalidModifiersOrder, loc, {
  12031. orderedModifiers: [before, after]
  12032. });
  12033. }
  12034. };
  12035. const incompatible = (loc, modifier, mod1, mod2) => {
  12036. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  12037. this.raise(TSErrors.IncompatibleModifiers, loc, {
  12038. modifiers: [mod1, mod2]
  12039. });
  12040. }
  12041. };
  12042. for (;;) {
  12043. const {
  12044. startLoc
  12045. } = this.state;
  12046. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock, modified.static);
  12047. if (!modifier) break;
  12048. if (tsIsAccessModifier(modifier)) {
  12049. if (modified.accessibility) {
  12050. this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, {
  12051. modifier
  12052. });
  12053. } else {
  12054. enforceOrder(startLoc, modifier, modifier, "override");
  12055. enforceOrder(startLoc, modifier, modifier, "static");
  12056. enforceOrder(startLoc, modifier, modifier, "readonly");
  12057. modified.accessibility = modifier;
  12058. }
  12059. } else if (tsIsVarianceAnnotations(modifier)) {
  12060. if (modified[modifier]) {
  12061. this.raise(TSErrors.DuplicateModifier, startLoc, {
  12062. modifier
  12063. });
  12064. }
  12065. modified[modifier] = true;
  12066. enforceOrder(startLoc, modifier, "in", "out");
  12067. } else {
  12068. if (hasOwnProperty.call(modified, modifier)) {
  12069. this.raise(TSErrors.DuplicateModifier, startLoc, {
  12070. modifier
  12071. });
  12072. } else {
  12073. enforceOrder(startLoc, modifier, "static", "readonly");
  12074. enforceOrder(startLoc, modifier, "static", "override");
  12075. enforceOrder(startLoc, modifier, "override", "readonly");
  12076. enforceOrder(startLoc, modifier, "abstract", "override");
  12077. incompatible(startLoc, modifier, "declare", "override");
  12078. incompatible(startLoc, modifier, "static", "abstract");
  12079. }
  12080. modified[modifier] = true;
  12081. }
  12082. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  12083. this.raise(errorTemplate, startLoc, {
  12084. modifier
  12085. });
  12086. }
  12087. }
  12088. }
  12089. tsIsListTerminator(kind) {
  12090. switch (kind) {
  12091. case "EnumMembers":
  12092. case "TypeMembers":
  12093. return this.match(8);
  12094. case "HeritageClauseElement":
  12095. return this.match(5);
  12096. case "TupleElementTypes":
  12097. return this.match(3);
  12098. case "TypeParametersOrArguments":
  12099. return this.match(48);
  12100. }
  12101. }
  12102. tsParseList(kind, parseElement) {
  12103. const result = [];
  12104. while (!this.tsIsListTerminator(kind)) {
  12105. result.push(parseElement());
  12106. }
  12107. return result;
  12108. }
  12109. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  12110. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  12111. }
  12112. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  12113. const result = [];
  12114. let trailingCommaPos = -1;
  12115. for (;;) {
  12116. if (this.tsIsListTerminator(kind)) {
  12117. break;
  12118. }
  12119. trailingCommaPos = -1;
  12120. const element = parseElement();
  12121. if (element == null) {
  12122. return undefined;
  12123. }
  12124. result.push(element);
  12125. if (this.eat(12)) {
  12126. trailingCommaPos = this.state.lastTokStartLoc.index;
  12127. continue;
  12128. }
  12129. if (this.tsIsListTerminator(kind)) {
  12130. break;
  12131. }
  12132. if (expectSuccess) {
  12133. this.expect(12);
  12134. }
  12135. return undefined;
  12136. }
  12137. if (refTrailingCommaPos) {
  12138. refTrailingCommaPos.value = trailingCommaPos;
  12139. }
  12140. return result;
  12141. }
  12142. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  12143. if (!skipFirstToken) {
  12144. if (bracket) {
  12145. this.expect(0);
  12146. } else {
  12147. this.expect(47);
  12148. }
  12149. }
  12150. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  12151. if (bracket) {
  12152. this.expect(3);
  12153. } else {
  12154. this.expect(48);
  12155. }
  12156. return result;
  12157. }
  12158. tsParseImportType() {
  12159. const node = this.startNode();
  12160. this.expect(83);
  12161. this.expect(10);
  12162. if (!this.match(134)) {
  12163. this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc);
  12164. node.argument = super.parseExprAtom();
  12165. } else {
  12166. node.argument = this.parseStringLiteral(this.state.value);
  12167. }
  12168. if (this.eat(12)) {
  12169. node.options = this.tsParseImportTypeOptions();
  12170. } else {
  12171. node.options = null;
  12172. }
  12173. this.expect(11);
  12174. if (this.eat(16)) {
  12175. node.qualifier = this.tsParseEntityName(1 | 2);
  12176. }
  12177. if (this.match(47)) {
  12178. node.typeParameters = this.tsParseTypeArguments();
  12179. }
  12180. return this.finishNode(node, "TSImportType");
  12181. }
  12182. tsParseImportTypeOptions() {
  12183. const node = this.startNode();
  12184. this.expect(5);
  12185. const withProperty = this.startNode();
  12186. if (this.isContextual(76)) {
  12187. withProperty.method = false;
  12188. withProperty.key = this.parseIdentifier(true);
  12189. withProperty.computed = false;
  12190. withProperty.shorthand = false;
  12191. } else {
  12192. this.unexpected(null, 76);
  12193. }
  12194. this.expect(14);
  12195. withProperty.value = this.tsParseImportTypeWithPropertyValue();
  12196. node.properties = [this.finishObjectProperty(withProperty)];
  12197. this.eat(12);
  12198. this.expect(8);
  12199. return this.finishNode(node, "ObjectExpression");
  12200. }
  12201. tsParseImportTypeWithPropertyValue() {
  12202. const node = this.startNode();
  12203. const properties = [];
  12204. this.expect(5);
  12205. while (!this.match(8)) {
  12206. const type = this.state.type;
  12207. if (tokenIsIdentifier(type) || type === 134) {
  12208. properties.push(super.parsePropertyDefinition(null));
  12209. } else {
  12210. this.unexpected();
  12211. }
  12212. this.eat(12);
  12213. }
  12214. node.properties = properties;
  12215. this.next();
  12216. return this.finishNode(node, "ObjectExpression");
  12217. }
  12218. tsParseEntityName(flags) {
  12219. let entity;
  12220. if (flags & 1 && this.match(78)) {
  12221. if (flags & 2) {
  12222. entity = this.parseIdentifier(true);
  12223. } else {
  12224. const node = this.startNode();
  12225. this.next();
  12226. entity = this.finishNode(node, "ThisExpression");
  12227. }
  12228. } else {
  12229. entity = this.parseIdentifier(!!(flags & 1));
  12230. }
  12231. while (this.eat(16)) {
  12232. const node = this.startNodeAtNode(entity);
  12233. node.left = entity;
  12234. node.right = this.parseIdentifier(!!(flags & 1));
  12235. entity = this.finishNode(node, "TSQualifiedName");
  12236. }
  12237. return entity;
  12238. }
  12239. tsParseTypeReference() {
  12240. const node = this.startNode();
  12241. node.typeName = this.tsParseEntityName(1);
  12242. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  12243. node.typeParameters = this.tsParseTypeArguments();
  12244. }
  12245. return this.finishNode(node, "TSTypeReference");
  12246. }
  12247. tsParseThisTypePredicate(lhs) {
  12248. this.next();
  12249. const node = this.startNodeAtNode(lhs);
  12250. node.parameterName = lhs;
  12251. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  12252. node.asserts = false;
  12253. return this.finishNode(node, "TSTypePredicate");
  12254. }
  12255. tsParseThisTypeNode() {
  12256. const node = this.startNode();
  12257. this.next();
  12258. return this.finishNode(node, "TSThisType");
  12259. }
  12260. tsParseTypeQuery() {
  12261. const node = this.startNode();
  12262. this.expect(87);
  12263. if (this.match(83)) {
  12264. node.exprName = this.tsParseImportType();
  12265. } else {
  12266. node.exprName = this.tsParseEntityName(1 | 2);
  12267. }
  12268. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  12269. node.typeParameters = this.tsParseTypeArguments();
  12270. }
  12271. return this.finishNode(node, "TSTypeQuery");
  12272. }
  12273. tsParseTypeParameter(parseModifiers) {
  12274. const node = this.startNode();
  12275. parseModifiers(node);
  12276. node.name = this.tsParseTypeParameterName();
  12277. node.constraint = this.tsEatThenParseType(81);
  12278. node.default = this.tsEatThenParseType(29);
  12279. return this.finishNode(node, "TSTypeParameter");
  12280. }
  12281. tsTryParseTypeParameters(parseModifiers) {
  12282. if (this.match(47)) {
  12283. return this.tsParseTypeParameters(parseModifiers);
  12284. }
  12285. }
  12286. tsParseTypeParameters(parseModifiers) {
  12287. const node = this.startNode();
  12288. if (this.match(47) || this.match(143)) {
  12289. this.next();
  12290. } else {
  12291. this.unexpected();
  12292. }
  12293. const refTrailingCommaPos = {
  12294. value: -1
  12295. };
  12296. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos);
  12297. if (node.params.length === 0) {
  12298. this.raise(TSErrors.EmptyTypeParameters, node);
  12299. }
  12300. if (refTrailingCommaPos.value !== -1) {
  12301. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  12302. }
  12303. return this.finishNode(node, "TSTypeParameterDeclaration");
  12304. }
  12305. tsFillSignature(returnToken, signature) {
  12306. const returnTokenRequired = returnToken === 19;
  12307. const paramsKey = "parameters";
  12308. const returnTypeKey = "typeAnnotation";
  12309. signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  12310. this.expect(10);
  12311. signature[paramsKey] = this.tsParseBindingListForSignature();
  12312. if (returnTokenRequired) {
  12313. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  12314. } else if (this.match(returnToken)) {
  12315. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  12316. }
  12317. }
  12318. tsParseBindingListForSignature() {
  12319. const list = super.parseBindingList(11, 41, 2);
  12320. for (const pattern of list) {
  12321. const {
  12322. type
  12323. } = pattern;
  12324. if (type === "AssignmentPattern" || type === "TSParameterProperty") {
  12325. this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, {
  12326. type
  12327. });
  12328. }
  12329. }
  12330. return list;
  12331. }
  12332. tsParseTypeMemberSemicolon() {
  12333. if (!this.eat(12) && !this.isLineTerminator()) {
  12334. this.expect(13);
  12335. }
  12336. }
  12337. tsParseSignatureMember(kind, node) {
  12338. this.tsFillSignature(14, node);
  12339. this.tsParseTypeMemberSemicolon();
  12340. return this.finishNode(node, kind);
  12341. }
  12342. tsIsUnambiguouslyIndexSignature() {
  12343. this.next();
  12344. if (tokenIsIdentifier(this.state.type)) {
  12345. this.next();
  12346. return this.match(14);
  12347. }
  12348. return false;
  12349. }
  12350. tsTryParseIndexSignature(node) {
  12351. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  12352. return;
  12353. }
  12354. this.expect(0);
  12355. const id = this.parseIdentifier();
  12356. id.typeAnnotation = this.tsParseTypeAnnotation();
  12357. this.resetEndLocation(id);
  12358. this.expect(3);
  12359. node.parameters = [id];
  12360. const type = this.tsTryParseTypeAnnotation();
  12361. if (type) node.typeAnnotation = type;
  12362. this.tsParseTypeMemberSemicolon();
  12363. return this.finishNode(node, "TSIndexSignature");
  12364. }
  12365. tsParsePropertyOrMethodSignature(node, readonly) {
  12366. if (this.eat(17)) node.optional = true;
  12367. if (this.match(10) || this.match(47)) {
  12368. if (readonly) {
  12369. this.raise(TSErrors.ReadonlyForMethodSignature, node);
  12370. }
  12371. const method = node;
  12372. if (method.kind && this.match(47)) {
  12373. this.raise(TSErrors.AccessorCannotHaveTypeParameters, this.state.curPosition());
  12374. }
  12375. this.tsFillSignature(14, method);
  12376. this.tsParseTypeMemberSemicolon();
  12377. const paramsKey = "parameters";
  12378. const returnTypeKey = "typeAnnotation";
  12379. if (method.kind === "get") {
  12380. if (method[paramsKey].length > 0) {
  12381. this.raise(Errors.BadGetterArity, this.state.curPosition());
  12382. if (this.isThisParam(method[paramsKey][0])) {
  12383. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  12384. }
  12385. }
  12386. } else if (method.kind === "set") {
  12387. if (method[paramsKey].length !== 1) {
  12388. this.raise(Errors.BadSetterArity, this.state.curPosition());
  12389. } else {
  12390. const firstParameter = method[paramsKey][0];
  12391. if (this.isThisParam(firstParameter)) {
  12392. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  12393. }
  12394. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  12395. this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, this.state.curPosition());
  12396. }
  12397. if (firstParameter.type === "RestElement") {
  12398. this.raise(TSErrors.SetAccessorCannotHaveRestParameter, this.state.curPosition());
  12399. }
  12400. }
  12401. if (method[returnTypeKey]) {
  12402. this.raise(TSErrors.SetAccessorCannotHaveReturnType, method[returnTypeKey]);
  12403. }
  12404. } else {
  12405. method.kind = "method";
  12406. }
  12407. return this.finishNode(method, "TSMethodSignature");
  12408. } else {
  12409. const property = node;
  12410. if (readonly) property.readonly = true;
  12411. const type = this.tsTryParseTypeAnnotation();
  12412. if (type) property.typeAnnotation = type;
  12413. this.tsParseTypeMemberSemicolon();
  12414. return this.finishNode(property, "TSPropertySignature");
  12415. }
  12416. }
  12417. tsParseTypeMember() {
  12418. const node = this.startNode();
  12419. if (this.match(10) || this.match(47)) {
  12420. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  12421. }
  12422. if (this.match(77)) {
  12423. const id = this.startNode();
  12424. this.next();
  12425. if (this.match(10) || this.match(47)) {
  12426. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  12427. } else {
  12428. node.key = this.createIdentifier(id, "new");
  12429. return this.tsParsePropertyOrMethodSignature(node, false);
  12430. }
  12431. }
  12432. this.tsParseModifiers({
  12433. allowedModifiers: ["readonly"],
  12434. disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"]
  12435. }, node);
  12436. const idx = this.tsTryParseIndexSignature(node);
  12437. if (idx) {
  12438. return idx;
  12439. }
  12440. super.parsePropertyName(node);
  12441. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  12442. node.kind = node.key.name;
  12443. super.parsePropertyName(node);
  12444. if (!this.match(10) && !this.match(47)) {
  12445. this.unexpected(null, 10);
  12446. }
  12447. }
  12448. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  12449. }
  12450. tsParseTypeLiteral() {
  12451. const node = this.startNode();
  12452. node.members = this.tsParseObjectTypeMembers();
  12453. return this.finishNode(node, "TSTypeLiteral");
  12454. }
  12455. tsParseObjectTypeMembers() {
  12456. this.expect(5);
  12457. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  12458. this.expect(8);
  12459. return members;
  12460. }
  12461. tsIsStartOfMappedType() {
  12462. this.next();
  12463. if (this.eat(53)) {
  12464. return this.isContextual(122);
  12465. }
  12466. if (this.isContextual(122)) {
  12467. this.next();
  12468. }
  12469. if (!this.match(0)) {
  12470. return false;
  12471. }
  12472. this.next();
  12473. if (!this.tsIsIdentifier()) {
  12474. return false;
  12475. }
  12476. this.next();
  12477. return this.match(58);
  12478. }
  12479. tsParseMappedType() {
  12480. const node = this.startNode();
  12481. this.expect(5);
  12482. if (this.match(53)) {
  12483. node.readonly = this.state.value;
  12484. this.next();
  12485. this.expectContextual(122);
  12486. } else if (this.eatContextual(122)) {
  12487. node.readonly = true;
  12488. }
  12489. this.expect(0);
  12490. const typeParameter = this.startNode();
  12491. typeParameter.name = this.tsParseTypeParameterName();
  12492. typeParameter.constraint = this.tsExpectThenParseType(58);
  12493. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  12494. node.nameType = this.eatContextual(93) ? this.tsParseType() : null;
  12495. this.expect(3);
  12496. if (this.match(53)) {
  12497. node.optional = this.state.value;
  12498. this.next();
  12499. this.expect(17);
  12500. } else if (this.eat(17)) {
  12501. node.optional = true;
  12502. }
  12503. node.typeAnnotation = this.tsTryParseType();
  12504. this.semicolon();
  12505. this.expect(8);
  12506. return this.finishNode(node, "TSMappedType");
  12507. }
  12508. tsParseTupleType() {
  12509. const node = this.startNode();
  12510. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  12511. let seenOptionalElement = false;
  12512. node.elementTypes.forEach(elementNode => {
  12513. const {
  12514. type
  12515. } = elementNode;
  12516. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  12517. this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode);
  12518. }
  12519. seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType");
  12520. });
  12521. return this.finishNode(node, "TSTupleType");
  12522. }
  12523. tsParseTupleElementType() {
  12524. const restStartLoc = this.state.startLoc;
  12525. const rest = this.eat(21);
  12526. const {
  12527. startLoc
  12528. } = this.state;
  12529. let labeled;
  12530. let label;
  12531. let optional;
  12532. let type;
  12533. const isWord = tokenIsKeywordOrIdentifier(this.state.type);
  12534. const chAfterWord = isWord ? this.lookaheadCharCode() : null;
  12535. if (chAfterWord === 58) {
  12536. labeled = true;
  12537. optional = false;
  12538. label = this.parseIdentifier(true);
  12539. this.expect(14);
  12540. type = this.tsParseType();
  12541. } else if (chAfterWord === 63) {
  12542. optional = true;
  12543. const wordName = this.state.value;
  12544. const typeOrLabel = this.tsParseNonArrayType();
  12545. if (this.lookaheadCharCode() === 58) {
  12546. labeled = true;
  12547. label = this.createIdentifier(this.startNodeAt(startLoc), wordName);
  12548. this.expect(17);
  12549. this.expect(14);
  12550. type = this.tsParseType();
  12551. } else {
  12552. labeled = false;
  12553. type = typeOrLabel;
  12554. this.expect(17);
  12555. }
  12556. } else {
  12557. type = this.tsParseType();
  12558. optional = this.eat(17);
  12559. labeled = this.eat(14);
  12560. }
  12561. if (labeled) {
  12562. let labeledNode;
  12563. if (label) {
  12564. labeledNode = this.startNodeAt(startLoc);
  12565. labeledNode.optional = optional;
  12566. labeledNode.label = label;
  12567. labeledNode.elementType = type;
  12568. if (this.eat(17)) {
  12569. labeledNode.optional = true;
  12570. this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc);
  12571. }
  12572. } else {
  12573. labeledNode = this.startNodeAt(startLoc);
  12574. labeledNode.optional = optional;
  12575. this.raise(TSErrors.InvalidTupleMemberLabel, type);
  12576. labeledNode.label = type;
  12577. labeledNode.elementType = this.tsParseType();
  12578. }
  12579. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  12580. } else if (optional) {
  12581. const optionalTypeNode = this.startNodeAt(startLoc);
  12582. optionalTypeNode.typeAnnotation = type;
  12583. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  12584. }
  12585. if (rest) {
  12586. const restNode = this.startNodeAt(restStartLoc);
  12587. restNode.typeAnnotation = type;
  12588. type = this.finishNode(restNode, "TSRestType");
  12589. }
  12590. return type;
  12591. }
  12592. tsParseParenthesizedType() {
  12593. const node = this.startNode();
  12594. this.expect(10);
  12595. node.typeAnnotation = this.tsParseType();
  12596. this.expect(11);
  12597. return this.finishNode(node, "TSParenthesizedType");
  12598. }
  12599. tsParseFunctionOrConstructorType(type, abstract) {
  12600. const node = this.startNode();
  12601. if (type === "TSConstructorType") {
  12602. node.abstract = !!abstract;
  12603. if (abstract) this.next();
  12604. this.next();
  12605. }
  12606. this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node));
  12607. return this.finishNode(node, type);
  12608. }
  12609. tsParseLiteralTypeNode() {
  12610. const node = this.startNode();
  12611. switch (this.state.type) {
  12612. case 135:
  12613. case 136:
  12614. case 134:
  12615. case 85:
  12616. case 86:
  12617. node.literal = super.parseExprAtom();
  12618. break;
  12619. default:
  12620. this.unexpected();
  12621. }
  12622. return this.finishNode(node, "TSLiteralType");
  12623. }
  12624. tsParseTemplateLiteralType() {
  12625. const node = this.startNode();
  12626. node.literal = super.parseTemplate(false);
  12627. return this.finishNode(node, "TSLiteralType");
  12628. }
  12629. parseTemplateSubstitution() {
  12630. if (this.state.inType) return this.tsParseType();
  12631. return super.parseTemplateSubstitution();
  12632. }
  12633. tsParseThisTypeOrThisTypePredicate() {
  12634. const thisKeyword = this.tsParseThisTypeNode();
  12635. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  12636. return this.tsParseThisTypePredicate(thisKeyword);
  12637. } else {
  12638. return thisKeyword;
  12639. }
  12640. }
  12641. tsParseNonArrayType() {
  12642. switch (this.state.type) {
  12643. case 134:
  12644. case 135:
  12645. case 136:
  12646. case 85:
  12647. case 86:
  12648. return this.tsParseLiteralTypeNode();
  12649. case 53:
  12650. if (this.state.value === "-") {
  12651. const node = this.startNode();
  12652. const nextToken = this.lookahead();
  12653. if (nextToken.type !== 135 && nextToken.type !== 136) {
  12654. this.unexpected();
  12655. }
  12656. node.literal = this.parseMaybeUnary();
  12657. return this.finishNode(node, "TSLiteralType");
  12658. }
  12659. break;
  12660. case 78:
  12661. return this.tsParseThisTypeOrThisTypePredicate();
  12662. case 87:
  12663. return this.tsParseTypeQuery();
  12664. case 83:
  12665. return this.tsParseImportType();
  12666. case 5:
  12667. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  12668. case 0:
  12669. return this.tsParseTupleType();
  12670. case 10:
  12671. return this.tsParseParenthesizedType();
  12672. case 25:
  12673. case 24:
  12674. return this.tsParseTemplateLiteralType();
  12675. default:
  12676. {
  12677. const {
  12678. type
  12679. } = this.state;
  12680. if (tokenIsIdentifier(type) || type === 88 || type === 84) {
  12681. const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  12682. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  12683. const node = this.startNode();
  12684. this.next();
  12685. return this.finishNode(node, nodeType);
  12686. }
  12687. return this.tsParseTypeReference();
  12688. }
  12689. }
  12690. }
  12691. throw this.unexpected();
  12692. }
  12693. tsParseArrayTypeOrHigher() {
  12694. const {
  12695. startLoc
  12696. } = this.state;
  12697. let type = this.tsParseNonArrayType();
  12698. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  12699. if (this.match(3)) {
  12700. const node = this.startNodeAt(startLoc);
  12701. node.elementType = type;
  12702. this.expect(3);
  12703. type = this.finishNode(node, "TSArrayType");
  12704. } else {
  12705. const node = this.startNodeAt(startLoc);
  12706. node.objectType = type;
  12707. node.indexType = this.tsParseType();
  12708. this.expect(3);
  12709. type = this.finishNode(node, "TSIndexedAccessType");
  12710. }
  12711. }
  12712. return type;
  12713. }
  12714. tsParseTypeOperator() {
  12715. const node = this.startNode();
  12716. const operator = this.state.value;
  12717. this.next();
  12718. node.operator = operator;
  12719. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  12720. if (operator === "readonly") {
  12721. this.tsCheckTypeAnnotationForReadOnly(node);
  12722. }
  12723. return this.finishNode(node, "TSTypeOperator");
  12724. }
  12725. tsCheckTypeAnnotationForReadOnly(node) {
  12726. switch (node.typeAnnotation.type) {
  12727. case "TSTupleType":
  12728. case "TSArrayType":
  12729. return;
  12730. default:
  12731. this.raise(TSErrors.UnexpectedReadonly, node);
  12732. }
  12733. }
  12734. tsParseInferType() {
  12735. const node = this.startNode();
  12736. this.expectContextual(115);
  12737. const typeParameter = this.startNode();
  12738. typeParameter.name = this.tsParseTypeParameterName();
  12739. typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType());
  12740. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  12741. return this.finishNode(node, "TSInferType");
  12742. }
  12743. tsParseConstraintForInferType() {
  12744. if (this.eat(81)) {
  12745. const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType());
  12746. if (this.state.inDisallowConditionalTypesContext || !this.match(17)) {
  12747. return constraint;
  12748. }
  12749. }
  12750. }
  12751. tsParseTypeOperatorOrHigher() {
  12752. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  12753. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher());
  12754. }
  12755. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  12756. const node = this.startNode();
  12757. const hasLeadingOperator = this.eat(operator);
  12758. const types = [];
  12759. do {
  12760. types.push(parseConstituentType());
  12761. } while (this.eat(operator));
  12762. if (types.length === 1 && !hasLeadingOperator) {
  12763. return types[0];
  12764. }
  12765. node.types = types;
  12766. return this.finishNode(node, kind);
  12767. }
  12768. tsParseIntersectionTypeOrHigher() {
  12769. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45);
  12770. }
  12771. tsParseUnionTypeOrHigher() {
  12772. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43);
  12773. }
  12774. tsIsStartOfFunctionType() {
  12775. if (this.match(47)) {
  12776. return true;
  12777. }
  12778. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  12779. }
  12780. tsSkipParameterStart() {
  12781. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  12782. this.next();
  12783. return true;
  12784. }
  12785. if (this.match(5)) {
  12786. const {
  12787. errors
  12788. } = this.state;
  12789. const previousErrorCount = errors.length;
  12790. try {
  12791. this.parseObjectLike(8, true);
  12792. return errors.length === previousErrorCount;
  12793. } catch (_unused) {
  12794. return false;
  12795. }
  12796. }
  12797. if (this.match(0)) {
  12798. this.next();
  12799. const {
  12800. errors
  12801. } = this.state;
  12802. const previousErrorCount = errors.length;
  12803. try {
  12804. super.parseBindingList(3, 93, 1);
  12805. return errors.length === previousErrorCount;
  12806. } catch (_unused2) {
  12807. return false;
  12808. }
  12809. }
  12810. return false;
  12811. }
  12812. tsIsUnambiguouslyStartOfFunctionType() {
  12813. this.next();
  12814. if (this.match(11) || this.match(21)) {
  12815. return true;
  12816. }
  12817. if (this.tsSkipParameterStart()) {
  12818. if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) {
  12819. return true;
  12820. }
  12821. if (this.match(11)) {
  12822. this.next();
  12823. if (this.match(19)) {
  12824. return true;
  12825. }
  12826. }
  12827. }
  12828. return false;
  12829. }
  12830. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  12831. return this.tsInType(() => {
  12832. const t = this.startNode();
  12833. this.expect(returnToken);
  12834. const node = this.startNode();
  12835. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  12836. if (asserts && this.match(78)) {
  12837. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  12838. if (thisTypePredicate.type === "TSThisType") {
  12839. node.parameterName = thisTypePredicate;
  12840. node.asserts = true;
  12841. node.typeAnnotation = null;
  12842. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  12843. } else {
  12844. this.resetStartLocationFromNode(thisTypePredicate, node);
  12845. thisTypePredicate.asserts = true;
  12846. }
  12847. t.typeAnnotation = thisTypePredicate;
  12848. return this.finishNode(t, "TSTypeAnnotation");
  12849. }
  12850. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  12851. if (!typePredicateVariable) {
  12852. if (!asserts) {
  12853. return this.tsParseTypeAnnotation(false, t);
  12854. }
  12855. node.parameterName = this.parseIdentifier();
  12856. node.asserts = asserts;
  12857. node.typeAnnotation = null;
  12858. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  12859. return this.finishNode(t, "TSTypeAnnotation");
  12860. }
  12861. const type = this.tsParseTypeAnnotation(false);
  12862. node.parameterName = typePredicateVariable;
  12863. node.typeAnnotation = type;
  12864. node.asserts = asserts;
  12865. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  12866. return this.finishNode(t, "TSTypeAnnotation");
  12867. });
  12868. }
  12869. tsTryParseTypeOrTypePredicateAnnotation() {
  12870. if (this.match(14)) {
  12871. return this.tsParseTypeOrTypePredicateAnnotation(14);
  12872. }
  12873. }
  12874. tsTryParseTypeAnnotation() {
  12875. if (this.match(14)) {
  12876. return this.tsParseTypeAnnotation();
  12877. }
  12878. }
  12879. tsTryParseType() {
  12880. return this.tsEatThenParseType(14);
  12881. }
  12882. tsParseTypePredicatePrefix() {
  12883. const id = this.parseIdentifier();
  12884. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  12885. this.next();
  12886. return id;
  12887. }
  12888. }
  12889. tsParseTypePredicateAsserts() {
  12890. if (this.state.type !== 109) {
  12891. return false;
  12892. }
  12893. const containsEsc = this.state.containsEsc;
  12894. this.next();
  12895. if (!tokenIsIdentifier(this.state.type) && !this.match(78)) {
  12896. return false;
  12897. }
  12898. if (containsEsc) {
  12899. this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, {
  12900. reservedWord: "asserts"
  12901. });
  12902. }
  12903. return true;
  12904. }
  12905. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  12906. this.tsInType(() => {
  12907. if (eatColon) this.expect(14);
  12908. t.typeAnnotation = this.tsParseType();
  12909. });
  12910. return this.finishNode(t, "TSTypeAnnotation");
  12911. }
  12912. tsParseType() {
  12913. assert(this.state.inType);
  12914. const type = this.tsParseNonConditionalType();
  12915. if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) {
  12916. return type;
  12917. }
  12918. const node = this.startNodeAtNode(type);
  12919. node.checkType = type;
  12920. node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType());
  12921. this.expect(17);
  12922. node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  12923. this.expect(14);
  12924. node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  12925. return this.finishNode(node, "TSConditionalType");
  12926. }
  12927. isAbstractConstructorSignature() {
  12928. return this.isContextual(124) && this.isLookaheadContextual("new");
  12929. }
  12930. tsParseNonConditionalType() {
  12931. if (this.tsIsStartOfFunctionType()) {
  12932. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  12933. }
  12934. if (this.match(77)) {
  12935. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  12936. } else if (this.isAbstractConstructorSignature()) {
  12937. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  12938. }
  12939. return this.tsParseUnionTypeOrHigher();
  12940. }
  12941. tsParseTypeAssertion() {
  12942. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  12943. this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc);
  12944. }
  12945. const node = this.startNode();
  12946. node.typeAnnotation = this.tsInType(() => {
  12947. this.next();
  12948. return this.match(75) ? this.tsParseTypeReference() : this.tsParseType();
  12949. });
  12950. this.expect(48);
  12951. node.expression = this.parseMaybeUnary();
  12952. return this.finishNode(node, "TSTypeAssertion");
  12953. }
  12954. tsParseHeritageClause(token) {
  12955. const originalStartLoc = this.state.startLoc;
  12956. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => {
  12957. const node = this.startNode();
  12958. node.expression = this.tsParseEntityName(1 | 2);
  12959. if (this.match(47)) {
  12960. node.typeParameters = this.tsParseTypeArguments();
  12961. }
  12962. return this.finishNode(node, "TSExpressionWithTypeArguments");
  12963. });
  12964. if (!delimitedList.length) {
  12965. this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, {
  12966. token
  12967. });
  12968. }
  12969. return delimitedList;
  12970. }
  12971. tsParseInterfaceDeclaration(node, properties = {}) {
  12972. if (this.hasFollowingLineBreak()) return null;
  12973. this.expectContextual(129);
  12974. if (properties.declare) node.declare = true;
  12975. if (tokenIsIdentifier(this.state.type)) {
  12976. node.id = this.parseIdentifier();
  12977. this.checkIdentifier(node.id, 130);
  12978. } else {
  12979. node.id = null;
  12980. this.raise(TSErrors.MissingInterfaceName, this.state.startLoc);
  12981. }
  12982. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  12983. if (this.eat(81)) {
  12984. node.extends = this.tsParseHeritageClause("extends");
  12985. }
  12986. const body = this.startNode();
  12987. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  12988. node.body = this.finishNode(body, "TSInterfaceBody");
  12989. return this.finishNode(node, "TSInterfaceDeclaration");
  12990. }
  12991. tsParseTypeAliasDeclaration(node) {
  12992. node.id = this.parseIdentifier();
  12993. this.checkIdentifier(node.id, 2);
  12994. node.typeAnnotation = this.tsInType(() => {
  12995. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers);
  12996. this.expect(29);
  12997. if (this.isContextual(114) && this.lookaheadCharCode() !== 46) {
  12998. const node = this.startNode();
  12999. this.next();
  13000. return this.finishNode(node, "TSIntrinsicKeyword");
  13001. }
  13002. return this.tsParseType();
  13003. });
  13004. this.semicolon();
  13005. return this.finishNode(node, "TSTypeAliasDeclaration");
  13006. }
  13007. tsInTopLevelContext(cb) {
  13008. if (this.curContext() !== types.brace) {
  13009. const oldContext = this.state.context;
  13010. this.state.context = [oldContext[0]];
  13011. try {
  13012. return cb();
  13013. } finally {
  13014. this.state.context = oldContext;
  13015. }
  13016. } else {
  13017. return cb();
  13018. }
  13019. }
  13020. tsInType(cb) {
  13021. const oldInType = this.state.inType;
  13022. this.state.inType = true;
  13023. try {
  13024. return cb();
  13025. } finally {
  13026. this.state.inType = oldInType;
  13027. }
  13028. }
  13029. tsInDisallowConditionalTypesContext(cb) {
  13030. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  13031. this.state.inDisallowConditionalTypesContext = true;
  13032. try {
  13033. return cb();
  13034. } finally {
  13035. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  13036. }
  13037. }
  13038. tsInAllowConditionalTypesContext(cb) {
  13039. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  13040. this.state.inDisallowConditionalTypesContext = false;
  13041. try {
  13042. return cb();
  13043. } finally {
  13044. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  13045. }
  13046. }
  13047. tsEatThenParseType(token) {
  13048. if (this.match(token)) {
  13049. return this.tsNextThenParseType();
  13050. }
  13051. }
  13052. tsExpectThenParseType(token) {
  13053. return this.tsInType(() => {
  13054. this.expect(token);
  13055. return this.tsParseType();
  13056. });
  13057. }
  13058. tsNextThenParseType() {
  13059. return this.tsInType(() => {
  13060. this.next();
  13061. return this.tsParseType();
  13062. });
  13063. }
  13064. tsParseEnumMember() {
  13065. const node = this.startNode();
  13066. node.id = this.match(134) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true);
  13067. if (this.eat(29)) {
  13068. node.initializer = super.parseMaybeAssignAllowIn();
  13069. }
  13070. return this.finishNode(node, "TSEnumMember");
  13071. }
  13072. tsParseEnumDeclaration(node, properties = {}) {
  13073. if (properties.const) node.const = true;
  13074. if (properties.declare) node.declare = true;
  13075. this.expectContextual(126);
  13076. node.id = this.parseIdentifier();
  13077. this.checkIdentifier(node.id, node.const ? 8971 : 8459);
  13078. this.expect(5);
  13079. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  13080. this.expect(8);
  13081. return this.finishNode(node, "TSEnumDeclaration");
  13082. }
  13083. tsParseEnumBody() {
  13084. const node = this.startNode();
  13085. this.expect(5);
  13086. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  13087. this.expect(8);
  13088. return this.finishNode(node, "TSEnumBody");
  13089. }
  13090. tsParseModuleBlock() {
  13091. const node = this.startNode();
  13092. this.scope.enter(0);
  13093. this.expect(5);
  13094. super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  13095. this.scope.exit();
  13096. return this.finishNode(node, "TSModuleBlock");
  13097. }
  13098. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  13099. node.id = this.parseIdentifier();
  13100. if (!nested) {
  13101. this.checkIdentifier(node.id, 1024);
  13102. }
  13103. if (this.eat(16)) {
  13104. const inner = this.startNode();
  13105. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  13106. node.body = inner;
  13107. } else {
  13108. this.scope.enter(1024);
  13109. this.prodParam.enter(0);
  13110. node.body = this.tsParseModuleBlock();
  13111. this.prodParam.exit();
  13112. this.scope.exit();
  13113. }
  13114. return this.finishNode(node, "TSModuleDeclaration");
  13115. }
  13116. tsParseAmbientExternalModuleDeclaration(node) {
  13117. if (this.isContextual(112)) {
  13118. node.kind = "global";
  13119. node.global = true;
  13120. node.id = this.parseIdentifier();
  13121. } else if (this.match(134)) {
  13122. node.kind = "module";
  13123. node.id = super.parseStringLiteral(this.state.value);
  13124. } else {
  13125. this.unexpected();
  13126. }
  13127. if (this.match(5)) {
  13128. this.scope.enter(1024);
  13129. this.prodParam.enter(0);
  13130. node.body = this.tsParseModuleBlock();
  13131. this.prodParam.exit();
  13132. this.scope.exit();
  13133. } else {
  13134. this.semicolon();
  13135. }
  13136. return this.finishNode(node, "TSModuleDeclaration");
  13137. }
  13138. tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) {
  13139. node.isExport = isExport || false;
  13140. node.id = maybeDefaultIdentifier || this.parseIdentifier();
  13141. this.checkIdentifier(node.id, 4096);
  13142. this.expect(29);
  13143. const moduleReference = this.tsParseModuleReference();
  13144. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  13145. this.raise(TSErrors.ImportAliasHasImportType, moduleReference);
  13146. }
  13147. node.moduleReference = moduleReference;
  13148. this.semicolon();
  13149. return this.finishNode(node, "TSImportEqualsDeclaration");
  13150. }
  13151. tsIsExternalModuleReference() {
  13152. return this.isContextual(119) && this.lookaheadCharCode() === 40;
  13153. }
  13154. tsParseModuleReference() {
  13155. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(0);
  13156. }
  13157. tsParseExternalModuleReference() {
  13158. const node = this.startNode();
  13159. this.expectContextual(119);
  13160. this.expect(10);
  13161. if (!this.match(134)) {
  13162. this.unexpected();
  13163. }
  13164. node.expression = super.parseExprAtom();
  13165. this.expect(11);
  13166. this.sawUnambiguousESM = true;
  13167. return this.finishNode(node, "TSExternalModuleReference");
  13168. }
  13169. tsLookAhead(f) {
  13170. const state = this.state.clone();
  13171. const res = f();
  13172. this.state = state;
  13173. return res;
  13174. }
  13175. tsTryParseAndCatch(f) {
  13176. const result = this.tryParse(abort => f() || abort());
  13177. if (result.aborted || !result.node) return;
  13178. if (result.error) this.state = result.failState;
  13179. return result.node;
  13180. }
  13181. tsTryParse(f) {
  13182. const state = this.state.clone();
  13183. const result = f();
  13184. if (result !== undefined && result !== false) {
  13185. return result;
  13186. }
  13187. this.state = state;
  13188. }
  13189. tsTryParseDeclare(node) {
  13190. if (this.isLineTerminator()) {
  13191. return;
  13192. }
  13193. const startType = this.state.type;
  13194. return this.tsInAmbientContext(() => {
  13195. switch (startType) {
  13196. case 68:
  13197. node.declare = true;
  13198. return super.parseFunctionStatement(node, false, false);
  13199. case 80:
  13200. node.declare = true;
  13201. return this.parseClass(node, true, false);
  13202. case 126:
  13203. return this.tsParseEnumDeclaration(node, {
  13204. declare: true
  13205. });
  13206. case 112:
  13207. return this.tsParseAmbientExternalModuleDeclaration(node);
  13208. case 100:
  13209. if (this.state.containsEsc) {
  13210. return;
  13211. }
  13212. case 75:
  13213. case 74:
  13214. if (!this.match(75) || !this.isLookaheadContextual("enum")) {
  13215. node.declare = true;
  13216. return this.parseVarStatement(node, this.state.value, true);
  13217. }
  13218. this.expect(75);
  13219. return this.tsParseEnumDeclaration(node, {
  13220. const: true,
  13221. declare: true
  13222. });
  13223. case 107:
  13224. if (this.isUsing()) {
  13225. this.raise(TSErrors.InvalidModifierOnUsingDeclaration, this.state.startLoc, "declare");
  13226. node.declare = true;
  13227. return this.parseVarStatement(node, "using", true);
  13228. }
  13229. break;
  13230. case 96:
  13231. if (this.isAwaitUsing()) {
  13232. this.raise(TSErrors.InvalidModifierOnAwaitUsingDeclaration, this.state.startLoc, "declare");
  13233. node.declare = true;
  13234. this.next();
  13235. return this.parseVarStatement(node, "await using", true);
  13236. }
  13237. break;
  13238. case 129:
  13239. {
  13240. const result = this.tsParseInterfaceDeclaration(node, {
  13241. declare: true
  13242. });
  13243. if (result) return result;
  13244. }
  13245. default:
  13246. if (tokenIsIdentifier(startType)) {
  13247. return this.tsParseDeclaration(node, this.state.type, true, null);
  13248. }
  13249. }
  13250. });
  13251. }
  13252. tsTryParseExportDeclaration() {
  13253. return this.tsParseDeclaration(this.startNode(), this.state.type, true, null);
  13254. }
  13255. tsParseDeclaration(node, type, next, decorators) {
  13256. switch (type) {
  13257. case 124:
  13258. if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) {
  13259. return this.tsParseAbstractDeclaration(node, decorators);
  13260. }
  13261. break;
  13262. case 127:
  13263. if (this.tsCheckLineTerminator(next)) {
  13264. if (this.match(134)) {
  13265. return this.tsParseAmbientExternalModuleDeclaration(node);
  13266. } else if (tokenIsIdentifier(this.state.type)) {
  13267. node.kind = "module";
  13268. return this.tsParseModuleOrNamespaceDeclaration(node);
  13269. }
  13270. }
  13271. break;
  13272. case 128:
  13273. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  13274. node.kind = "namespace";
  13275. return this.tsParseModuleOrNamespaceDeclaration(node);
  13276. }
  13277. break;
  13278. case 130:
  13279. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  13280. return this.tsParseTypeAliasDeclaration(node);
  13281. }
  13282. break;
  13283. }
  13284. }
  13285. tsCheckLineTerminator(next) {
  13286. if (next) {
  13287. if (this.hasFollowingLineBreak()) return false;
  13288. this.next();
  13289. return true;
  13290. }
  13291. return !this.isLineTerminator();
  13292. }
  13293. tsTryParseGenericAsyncArrowFunction(startLoc) {
  13294. if (!this.match(47)) return;
  13295. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  13296. this.state.maybeInArrowParameters = true;
  13297. const res = this.tsTryParseAndCatch(() => {
  13298. const node = this.startNodeAt(startLoc);
  13299. node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  13300. super.parseFunctionParams(node);
  13301. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  13302. this.expect(19);
  13303. return node;
  13304. });
  13305. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  13306. if (!res) return;
  13307. return super.parseArrowExpression(res, null, true);
  13308. }
  13309. tsParseTypeArgumentsInExpression() {
  13310. if (this.reScan_lt() !== 47) return;
  13311. return this.tsParseTypeArguments();
  13312. }
  13313. tsParseTypeArguments() {
  13314. const node = this.startNode();
  13315. node.params = this.tsInType(() => this.tsInTopLevelContext(() => {
  13316. this.expect(47);
  13317. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  13318. }));
  13319. if (node.params.length === 0) {
  13320. this.raise(TSErrors.EmptyTypeArguments, node);
  13321. } else if (!this.state.inType && this.curContext() === types.brace) {
  13322. this.reScan_lt_gt();
  13323. }
  13324. this.expect(48);
  13325. return this.finishNode(node, "TSTypeParameterInstantiation");
  13326. }
  13327. tsIsDeclarationStart() {
  13328. return tokenIsTSDeclarationStart(this.state.type);
  13329. }
  13330. isExportDefaultSpecifier() {
  13331. if (this.tsIsDeclarationStart()) return false;
  13332. return super.isExportDefaultSpecifier();
  13333. }
  13334. parseBindingElement(flags, decorators) {
  13335. const startLoc = decorators.length ? decorators[0].loc.start : this.state.startLoc;
  13336. const modified = {};
  13337. this.tsParseModifiers({
  13338. allowedModifiers: ["public", "private", "protected", "override", "readonly"]
  13339. }, modified);
  13340. const accessibility = modified.accessibility;
  13341. const override = modified.override;
  13342. const readonly = modified.readonly;
  13343. if (!(flags & 4) && (accessibility || readonly || override)) {
  13344. this.raise(TSErrors.UnexpectedParameterModifier, startLoc);
  13345. }
  13346. const left = this.parseMaybeDefault();
  13347. if (flags & 2) {
  13348. this.parseFunctionParamType(left);
  13349. }
  13350. const elt = this.parseMaybeDefault(left.loc.start, left);
  13351. if (accessibility || readonly || override) {
  13352. const pp = this.startNodeAt(startLoc);
  13353. if (decorators.length) {
  13354. pp.decorators = decorators;
  13355. }
  13356. if (accessibility) pp.accessibility = accessibility;
  13357. if (readonly) pp.readonly = readonly;
  13358. if (override) pp.override = override;
  13359. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  13360. this.raise(TSErrors.UnsupportedParameterPropertyKind, pp);
  13361. }
  13362. pp.parameter = elt;
  13363. return this.finishNode(pp, "TSParameterProperty");
  13364. }
  13365. if (decorators.length) {
  13366. left.decorators = decorators;
  13367. }
  13368. return elt;
  13369. }
  13370. isSimpleParameter(node) {
  13371. return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node);
  13372. }
  13373. tsDisallowOptionalPattern(node) {
  13374. for (const param of node.params) {
  13375. if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) {
  13376. this.raise(TSErrors.PatternIsOptional, param);
  13377. }
  13378. }
  13379. }
  13380. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  13381. super.setArrowFunctionParameters(node, params, trailingCommaLoc);
  13382. this.tsDisallowOptionalPattern(node);
  13383. }
  13384. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  13385. if (this.match(14)) {
  13386. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  13387. }
  13388. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  13389. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  13390. return this.finishNode(node, bodilessType);
  13391. }
  13392. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  13393. this.raise(TSErrors.DeclareFunctionHasImplementation, node);
  13394. if (node.declare) {
  13395. return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  13396. }
  13397. }
  13398. this.tsDisallowOptionalPattern(node);
  13399. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  13400. }
  13401. registerFunctionStatementId(node) {
  13402. if (!node.body && node.id) {
  13403. this.checkIdentifier(node.id, 1024);
  13404. } else {
  13405. super.registerFunctionStatementId(node);
  13406. }
  13407. }
  13408. tsCheckForInvalidTypeCasts(items) {
  13409. items.forEach(node => {
  13410. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  13411. this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation);
  13412. }
  13413. });
  13414. }
  13415. toReferencedList(exprList, isInParens) {
  13416. this.tsCheckForInvalidTypeCasts(exprList);
  13417. return exprList;
  13418. }
  13419. parseArrayLike(close, isTuple, refExpressionErrors) {
  13420. const node = super.parseArrayLike(close, isTuple, refExpressionErrors);
  13421. if (node.type === "ArrayExpression") {
  13422. this.tsCheckForInvalidTypeCasts(node.elements);
  13423. }
  13424. return node;
  13425. }
  13426. parseSubscript(base, startLoc, noCalls, state) {
  13427. if (!this.hasPrecedingLineBreak() && this.match(35)) {
  13428. this.state.canStartJSXElement = false;
  13429. this.next();
  13430. const nonNullExpression = this.startNodeAt(startLoc);
  13431. nonNullExpression.expression = base;
  13432. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  13433. }
  13434. let isOptionalCall = false;
  13435. if (this.match(18) && this.lookaheadCharCode() === 60) {
  13436. if (noCalls) {
  13437. state.stop = true;
  13438. return base;
  13439. }
  13440. state.optionalChainMember = isOptionalCall = true;
  13441. this.next();
  13442. }
  13443. if (this.match(47) || this.match(51)) {
  13444. let missingParenErrorLoc;
  13445. const result = this.tsTryParseAndCatch(() => {
  13446. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  13447. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc);
  13448. if (asyncArrowFn) {
  13449. state.stop = true;
  13450. return asyncArrowFn;
  13451. }
  13452. }
  13453. const typeArguments = this.tsParseTypeArgumentsInExpression();
  13454. if (!typeArguments) return;
  13455. if (isOptionalCall && !this.match(10)) {
  13456. missingParenErrorLoc = this.state.curPosition();
  13457. return;
  13458. }
  13459. if (tokenIsTemplate(this.state.type)) {
  13460. const result = super.parseTaggedTemplateExpression(base, startLoc, state);
  13461. result.typeParameters = typeArguments;
  13462. return result;
  13463. }
  13464. if (!noCalls && this.eat(10)) {
  13465. const node = this.startNodeAt(startLoc);
  13466. node.callee = base;
  13467. node.arguments = this.parseCallExpressionArguments();
  13468. this.tsCheckForInvalidTypeCasts(node.arguments);
  13469. node.typeParameters = typeArguments;
  13470. if (state.optionalChainMember) {
  13471. node.optional = isOptionalCall;
  13472. }
  13473. return this.finishCallExpression(node, state.optionalChainMember);
  13474. }
  13475. const tokenType = this.state.type;
  13476. if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenType !== 93 && tokenType !== 120 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) {
  13477. return;
  13478. }
  13479. const node = this.startNodeAt(startLoc);
  13480. node.expression = base;
  13481. node.typeParameters = typeArguments;
  13482. return this.finishNode(node, "TSInstantiationExpression");
  13483. });
  13484. if (missingParenErrorLoc) {
  13485. this.unexpected(missingParenErrorLoc, 10);
  13486. }
  13487. if (result) {
  13488. if (result.type === "TSInstantiationExpression") {
  13489. if (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40) {
  13490. this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc);
  13491. }
  13492. if (!this.match(16) && !this.match(18)) {
  13493. result.expression = super.stopParseSubscript(base, state);
  13494. }
  13495. }
  13496. return result;
  13497. }
  13498. }
  13499. return super.parseSubscript(base, startLoc, noCalls, state);
  13500. }
  13501. parseNewCallee(node) {
  13502. var _callee$extra;
  13503. super.parseNewCallee(node);
  13504. const {
  13505. callee
  13506. } = node;
  13507. if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) {
  13508. node.typeParameters = callee.typeParameters;
  13509. node.callee = callee.expression;
  13510. }
  13511. }
  13512. parseExprOp(left, leftStartLoc, minPrec) {
  13513. let isSatisfies;
  13514. if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) {
  13515. const node = this.startNodeAt(leftStartLoc);
  13516. node.expression = left;
  13517. node.typeAnnotation = this.tsInType(() => {
  13518. this.next();
  13519. if (this.match(75)) {
  13520. if (isSatisfies) {
  13521. this.raise(Errors.UnexpectedKeyword, this.state.startLoc, {
  13522. keyword: "const"
  13523. });
  13524. }
  13525. return this.tsParseTypeReference();
  13526. }
  13527. return this.tsParseType();
  13528. });
  13529. this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression");
  13530. this.reScan_lt_gt();
  13531. return this.parseExprOp(node, leftStartLoc, minPrec);
  13532. }
  13533. return super.parseExprOp(left, leftStartLoc, minPrec);
  13534. }
  13535. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  13536. if (!this.state.isAmbientContext) {
  13537. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  13538. }
  13539. }
  13540. checkImportReflection(node) {
  13541. super.checkImportReflection(node);
  13542. if (node.module && node.importKind !== "value") {
  13543. this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  13544. }
  13545. }
  13546. checkDuplicateExports() {}
  13547. isPotentialImportPhase(isExport) {
  13548. if (super.isPotentialImportPhase(isExport)) return true;
  13549. if (this.isContextual(130)) {
  13550. const ch = this.lookaheadCharCode();
  13551. return isExport ? ch === 123 || ch === 42 : ch !== 61;
  13552. }
  13553. return !isExport && this.isContextual(87);
  13554. }
  13555. applyImportPhase(node, isExport, phase, loc) {
  13556. super.applyImportPhase(node, isExport, phase, loc);
  13557. if (isExport) {
  13558. node.exportKind = phase === "type" ? "type" : "value";
  13559. } else {
  13560. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  13561. }
  13562. }
  13563. parseImport(node) {
  13564. if (this.match(134)) {
  13565. node.importKind = "value";
  13566. return super.parseImport(node);
  13567. }
  13568. let importNode;
  13569. if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) {
  13570. node.importKind = "value";
  13571. return this.tsParseImportEqualsDeclaration(node);
  13572. } else if (this.isContextual(130)) {
  13573. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false);
  13574. if (this.lookaheadCharCode() === 61) {
  13575. return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier);
  13576. } else {
  13577. importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier);
  13578. }
  13579. } else {
  13580. importNode = super.parseImport(node);
  13581. }
  13582. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  13583. this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode);
  13584. }
  13585. return importNode;
  13586. }
  13587. parseExport(node, decorators) {
  13588. if (this.match(83)) {
  13589. const nodeImportEquals = node;
  13590. this.next();
  13591. let maybeDefaultIdentifier = null;
  13592. if (this.isContextual(130) && this.isPotentialImportPhase(false)) {
  13593. maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false);
  13594. } else {
  13595. nodeImportEquals.importKind = "value";
  13596. }
  13597. const declaration = this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true);
  13598. return declaration;
  13599. } else if (this.eat(29)) {
  13600. const assign = node;
  13601. assign.expression = super.parseExpression();
  13602. this.semicolon();
  13603. this.sawUnambiguousESM = true;
  13604. return this.finishNode(assign, "TSExportAssignment");
  13605. } else if (this.eatContextual(93)) {
  13606. const decl = node;
  13607. this.expectContextual(128);
  13608. decl.id = this.parseIdentifier();
  13609. this.semicolon();
  13610. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  13611. } else {
  13612. return super.parseExport(node, decorators);
  13613. }
  13614. }
  13615. isAbstractClass() {
  13616. return this.isContextual(124) && this.isLookaheadContextual("class");
  13617. }
  13618. parseExportDefaultExpression() {
  13619. if (this.isAbstractClass()) {
  13620. const cls = this.startNode();
  13621. this.next();
  13622. cls.abstract = true;
  13623. return this.parseClass(cls, true, true);
  13624. }
  13625. if (this.match(129)) {
  13626. const result = this.tsParseInterfaceDeclaration(this.startNode());
  13627. if (result) return result;
  13628. }
  13629. return super.parseExportDefaultExpression();
  13630. }
  13631. parseVarStatement(node, kind, allowMissingInitializer = false) {
  13632. const {
  13633. isAmbientContext
  13634. } = this.state;
  13635. const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext);
  13636. if (!isAmbientContext) return declaration;
  13637. if (!node.declare && (kind === "using" || kind === "await using")) {
  13638. this.raiseOverwrite(TSErrors.UsingDeclarationInAmbientContext, node, kind);
  13639. return declaration;
  13640. }
  13641. for (const {
  13642. id,
  13643. init
  13644. } of declaration.declarations) {
  13645. if (!init) continue;
  13646. if (kind === "var" || kind === "let" || !!id.typeAnnotation) {
  13647. this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init);
  13648. } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) {
  13649. this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference, init);
  13650. }
  13651. }
  13652. return declaration;
  13653. }
  13654. parseStatementContent(flags, decorators) {
  13655. if (!this.state.containsEsc) {
  13656. switch (this.state.type) {
  13657. case 75:
  13658. {
  13659. if (this.isLookaheadContextual("enum")) {
  13660. const node = this.startNode();
  13661. this.expect(75);
  13662. return this.tsParseEnumDeclaration(node, {
  13663. const: true
  13664. });
  13665. }
  13666. break;
  13667. }
  13668. case 124:
  13669. case 125:
  13670. {
  13671. if (this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()) {
  13672. const token = this.state.type;
  13673. const node = this.startNode();
  13674. this.next();
  13675. const declaration = token === 125 ? this.tsTryParseDeclare(node) : this.tsParseAbstractDeclaration(node, decorators);
  13676. if (declaration) {
  13677. if (token === 125) {
  13678. declaration.declare = true;
  13679. }
  13680. return declaration;
  13681. } else {
  13682. node.expression = this.createIdentifier(this.startNodeAt(node.loc.start), token === 125 ? "declare" : "abstract");
  13683. this.semicolon(false);
  13684. return this.finishNode(node, "ExpressionStatement");
  13685. }
  13686. }
  13687. break;
  13688. }
  13689. case 126:
  13690. return this.tsParseEnumDeclaration(this.startNode());
  13691. case 112:
  13692. {
  13693. const nextCh = this.lookaheadCharCode();
  13694. if (nextCh === 123) {
  13695. const node = this.startNode();
  13696. return this.tsParseAmbientExternalModuleDeclaration(node);
  13697. }
  13698. break;
  13699. }
  13700. case 129:
  13701. {
  13702. const result = this.tsParseInterfaceDeclaration(this.startNode());
  13703. if (result) return result;
  13704. break;
  13705. }
  13706. case 127:
  13707. {
  13708. if (this.nextTokenIsIdentifierOrStringLiteralOnSameLine()) {
  13709. const node = this.startNode();
  13710. this.next();
  13711. return this.tsParseDeclaration(node, 127, false, decorators);
  13712. }
  13713. break;
  13714. }
  13715. case 128:
  13716. {
  13717. if (this.nextTokenIsIdentifierOnSameLine()) {
  13718. const node = this.startNode();
  13719. this.next();
  13720. return this.tsParseDeclaration(node, 128, false, decorators);
  13721. }
  13722. break;
  13723. }
  13724. case 130:
  13725. {
  13726. if (this.nextTokenIsIdentifierOnSameLine()) {
  13727. const node = this.startNode();
  13728. this.next();
  13729. return this.tsParseTypeAliasDeclaration(node);
  13730. }
  13731. break;
  13732. }
  13733. }
  13734. }
  13735. return super.parseStatementContent(flags, decorators);
  13736. }
  13737. parseAccessModifier() {
  13738. return this.tsParseModifier(["public", "protected", "private"]);
  13739. }
  13740. tsHasSomeModifiers(member, modifiers) {
  13741. return modifiers.some(modifier => {
  13742. if (tsIsAccessModifier(modifier)) {
  13743. return member.accessibility === modifier;
  13744. }
  13745. return !!member[modifier];
  13746. });
  13747. }
  13748. tsIsStartOfStaticBlocks() {
  13749. return this.isContextual(106) && this.lookaheadCharCode() === 123;
  13750. }
  13751. parseClassMember(classBody, member, state) {
  13752. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  13753. this.tsParseModifiers({
  13754. allowedModifiers: modifiers,
  13755. disallowedModifiers: ["in", "out"],
  13756. stopOnStartOfClassStaticBlock: true,
  13757. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  13758. }, member);
  13759. const callParseClassMemberWithIsStatic = () => {
  13760. if (this.tsIsStartOfStaticBlocks()) {
  13761. this.next();
  13762. this.next();
  13763. if (this.tsHasSomeModifiers(member, modifiers)) {
  13764. this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition());
  13765. }
  13766. super.parseClassStaticBlock(classBody, member);
  13767. } else {
  13768. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  13769. }
  13770. };
  13771. if (member.declare) {
  13772. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  13773. } else {
  13774. callParseClassMemberWithIsStatic();
  13775. }
  13776. }
  13777. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  13778. const idx = this.tsTryParseIndexSignature(member);
  13779. if (idx) {
  13780. classBody.body.push(idx);
  13781. if (member.abstract) {
  13782. this.raise(TSErrors.IndexSignatureHasAbstract, member);
  13783. }
  13784. if (member.accessibility) {
  13785. this.raise(TSErrors.IndexSignatureHasAccessibility, member, {
  13786. modifier: member.accessibility
  13787. });
  13788. }
  13789. if (member.declare) {
  13790. this.raise(TSErrors.IndexSignatureHasDeclare, member);
  13791. }
  13792. if (member.override) {
  13793. this.raise(TSErrors.IndexSignatureHasOverride, member);
  13794. }
  13795. return;
  13796. }
  13797. if (!this.state.inAbstractClass && member.abstract) {
  13798. this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member);
  13799. }
  13800. if (member.override) {
  13801. if (!state.hadSuperClass) {
  13802. this.raise(TSErrors.OverrideNotInSubClass, member);
  13803. }
  13804. }
  13805. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  13806. }
  13807. parsePostMemberNameModifiers(methodOrProp) {
  13808. const optional = this.eat(17);
  13809. if (optional) methodOrProp.optional = true;
  13810. if (methodOrProp.readonly && this.match(10)) {
  13811. this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp);
  13812. }
  13813. if (methodOrProp.declare && this.match(10)) {
  13814. this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp);
  13815. }
  13816. }
  13817. shouldParseExportDeclaration() {
  13818. if (this.tsIsDeclarationStart()) return true;
  13819. return super.shouldParseExportDeclaration();
  13820. }
  13821. parseConditional(expr, startLoc, refExpressionErrors) {
  13822. if (!this.match(17)) return expr;
  13823. if (this.state.maybeInArrowParameters) {
  13824. const nextCh = this.lookaheadCharCode();
  13825. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  13826. this.setOptionalParametersError(refExpressionErrors);
  13827. return expr;
  13828. }
  13829. }
  13830. return super.parseConditional(expr, startLoc, refExpressionErrors);
  13831. }
  13832. parseParenItem(node, startLoc) {
  13833. const newNode = super.parseParenItem(node, startLoc);
  13834. if (this.eat(17)) {
  13835. newNode.optional = true;
  13836. this.resetEndLocation(node);
  13837. }
  13838. if (this.match(14)) {
  13839. const typeCastNode = this.startNodeAt(startLoc);
  13840. typeCastNode.expression = node;
  13841. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  13842. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  13843. }
  13844. return node;
  13845. }
  13846. parseExportDeclaration(node) {
  13847. if (!this.state.isAmbientContext && this.isContextual(125)) {
  13848. return this.tsInAmbientContext(() => this.parseExportDeclaration(node));
  13849. }
  13850. const startLoc = this.state.startLoc;
  13851. const isDeclare = this.eatContextual(125);
  13852. if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) {
  13853. throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc);
  13854. }
  13855. const isIdentifier = tokenIsIdentifier(this.state.type);
  13856. const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node);
  13857. if (!declaration) return null;
  13858. if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) {
  13859. node.exportKind = "type";
  13860. }
  13861. if (isDeclare && declaration.type !== "TSImportEqualsDeclaration") {
  13862. this.resetStartLocation(declaration, startLoc);
  13863. declaration.declare = true;
  13864. }
  13865. return declaration;
  13866. }
  13867. parseClassId(node, isStatement, optionalId, bindingType) {
  13868. if ((!isStatement || optionalId) && this.isContextual(113)) {
  13869. return;
  13870. }
  13871. super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331);
  13872. const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  13873. if (typeParameters) node.typeParameters = typeParameters;
  13874. }
  13875. parseClassPropertyAnnotation(node) {
  13876. if (!node.optional) {
  13877. if (this.eat(35)) {
  13878. node.definite = true;
  13879. } else if (this.eat(17)) {
  13880. node.optional = true;
  13881. }
  13882. }
  13883. const type = this.tsTryParseTypeAnnotation();
  13884. if (type) node.typeAnnotation = type;
  13885. }
  13886. parseClassProperty(node) {
  13887. this.parseClassPropertyAnnotation(node);
  13888. if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) {
  13889. this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc);
  13890. }
  13891. if (node.abstract && this.match(29)) {
  13892. const {
  13893. key
  13894. } = node;
  13895. this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, {
  13896. propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  13897. });
  13898. }
  13899. return super.parseClassProperty(node);
  13900. }
  13901. parseClassPrivateProperty(node) {
  13902. if (node.abstract) {
  13903. this.raise(TSErrors.PrivateElementHasAbstract, node);
  13904. }
  13905. if (node.accessibility) {
  13906. this.raise(TSErrors.PrivateElementHasAccessibility, node, {
  13907. modifier: node.accessibility
  13908. });
  13909. }
  13910. this.parseClassPropertyAnnotation(node);
  13911. return super.parseClassPrivateProperty(node);
  13912. }
  13913. parseClassAccessorProperty(node) {
  13914. this.parseClassPropertyAnnotation(node);
  13915. if (node.optional) {
  13916. this.raise(TSErrors.AccessorCannotBeOptional, node);
  13917. }
  13918. return super.parseClassAccessorProperty(node);
  13919. }
  13920. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  13921. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13922. if (typeParameters && isConstructor) {
  13923. this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters);
  13924. }
  13925. const {
  13926. declare = false,
  13927. kind
  13928. } = method;
  13929. if (declare && (kind === "get" || kind === "set")) {
  13930. this.raise(TSErrors.DeclareAccessor, method, {
  13931. kind
  13932. });
  13933. }
  13934. if (typeParameters) method.typeParameters = typeParameters;
  13935. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  13936. }
  13937. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  13938. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13939. if (typeParameters) method.typeParameters = typeParameters;
  13940. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  13941. }
  13942. declareClassPrivateMethodInScope(node, kind) {
  13943. if (node.type === "TSDeclareMethod") return;
  13944. if (node.type === "MethodDefinition" && node.value.body == null) {
  13945. return;
  13946. }
  13947. super.declareClassPrivateMethodInScope(node, kind);
  13948. }
  13949. parseClassSuper(node) {
  13950. super.parseClassSuper(node);
  13951. if (node.superClass) {
  13952. if (node.superClass.type === "TSInstantiationExpression") {
  13953. const tsInstantiationExpression = node.superClass;
  13954. const superClass = tsInstantiationExpression.expression;
  13955. this.takeSurroundingComments(superClass, superClass.start, superClass.end);
  13956. const superTypeArguments = tsInstantiationExpression.typeParameters;
  13957. this.takeSurroundingComments(superTypeArguments, superTypeArguments.start, superTypeArguments.end);
  13958. node.superClass = superClass;
  13959. node.superTypeParameters = superTypeArguments;
  13960. } else if (this.match(47) || this.match(51)) {
  13961. node.superTypeParameters = this.tsParseTypeArgumentsInExpression();
  13962. }
  13963. }
  13964. if (this.eatContextual(113)) {
  13965. node.implements = this.tsParseHeritageClause("implements");
  13966. }
  13967. }
  13968. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  13969. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13970. if (typeParameters) prop.typeParameters = typeParameters;
  13971. return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  13972. }
  13973. parseFunctionParams(node, isConstructor) {
  13974. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13975. if (typeParameters) node.typeParameters = typeParameters;
  13976. super.parseFunctionParams(node, isConstructor);
  13977. }
  13978. parseVarId(decl, kind) {
  13979. super.parseVarId(decl, kind);
  13980. if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) {
  13981. decl.definite = true;
  13982. }
  13983. const type = this.tsTryParseTypeAnnotation();
  13984. if (type) {
  13985. decl.id.typeAnnotation = type;
  13986. this.resetEndLocation(decl.id);
  13987. }
  13988. }
  13989. parseAsyncArrowFromCallExpression(node, call) {
  13990. if (this.match(14)) {
  13991. node.returnType = this.tsParseTypeAnnotation();
  13992. }
  13993. return super.parseAsyncArrowFromCallExpression(node, call);
  13994. }
  13995. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  13996. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2;
  13997. let state;
  13998. let jsx;
  13999. let typeCast;
  14000. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  14001. state = this.state.clone();
  14002. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  14003. if (!jsx.error) return jsx.node;
  14004. const {
  14005. context
  14006. } = this.state;
  14007. const currentContext = context[context.length - 1];
  14008. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  14009. context.pop();
  14010. }
  14011. }
  14012. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) {
  14013. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  14014. }
  14015. if (!state || state === this.state) state = this.state.clone();
  14016. let typeParameters;
  14017. const arrow = this.tryParse(abort => {
  14018. var _expr$extra, _typeParameters;
  14019. typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  14020. const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  14021. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  14022. abort();
  14023. }
  14024. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  14025. this.resetStartLocationFromNode(expr, typeParameters);
  14026. }
  14027. expr.typeParameters = typeParameters;
  14028. return expr;
  14029. }, state);
  14030. if (!arrow.error && !arrow.aborted) {
  14031. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  14032. return arrow.node;
  14033. }
  14034. if (!jsx) {
  14035. assert(!this.hasPlugin("jsx"));
  14036. typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  14037. if (!typeCast.error) return typeCast.node;
  14038. }
  14039. if ((_jsx2 = jsx) != null && _jsx2.node) {
  14040. this.state = jsx.failState;
  14041. return jsx.node;
  14042. }
  14043. if (arrow.node) {
  14044. this.state = arrow.failState;
  14045. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  14046. return arrow.node;
  14047. }
  14048. if ((_typeCast = typeCast) != null && _typeCast.node) {
  14049. this.state = typeCast.failState;
  14050. return typeCast.node;
  14051. }
  14052. throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error);
  14053. }
  14054. reportReservedArrowTypeParam(node) {
  14055. var _node$extra2;
  14056. if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra2 = node.extra) != null && _node$extra2.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  14057. this.raise(TSErrors.ReservedArrowTypeParam, node);
  14058. }
  14059. }
  14060. parseMaybeUnary(refExpressionErrors, sawUnary) {
  14061. if (!this.hasPlugin("jsx") && this.match(47)) {
  14062. return this.tsParseTypeAssertion();
  14063. }
  14064. return super.parseMaybeUnary(refExpressionErrors, sawUnary);
  14065. }
  14066. parseArrow(node) {
  14067. if (this.match(14)) {
  14068. const result = this.tryParse(abort => {
  14069. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  14070. if (this.canInsertSemicolon() || !this.match(19)) abort();
  14071. return returnType;
  14072. });
  14073. if (result.aborted) return;
  14074. if (!result.thrown) {
  14075. if (result.error) this.state = result.failState;
  14076. node.returnType = result.node;
  14077. }
  14078. }
  14079. return super.parseArrow(node);
  14080. }
  14081. parseFunctionParamType(param) {
  14082. if (this.eat(17)) {
  14083. param.optional = true;
  14084. }
  14085. const type = this.tsTryParseTypeAnnotation();
  14086. if (type) param.typeAnnotation = type;
  14087. this.resetEndLocation(param);
  14088. return param;
  14089. }
  14090. isAssignable(node, isBinding) {
  14091. switch (node.type) {
  14092. case "TSTypeCastExpression":
  14093. return this.isAssignable(node.expression, isBinding);
  14094. case "TSParameterProperty":
  14095. return true;
  14096. default:
  14097. return super.isAssignable(node, isBinding);
  14098. }
  14099. }
  14100. toAssignable(node, isLHS = false) {
  14101. switch (node.type) {
  14102. case "ParenthesizedExpression":
  14103. this.toAssignableParenthesizedExpression(node, isLHS);
  14104. break;
  14105. case "TSAsExpression":
  14106. case "TSSatisfiesExpression":
  14107. case "TSNonNullExpression":
  14108. case "TSTypeAssertion":
  14109. if (isLHS) {
  14110. this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node);
  14111. } else {
  14112. this.raise(TSErrors.UnexpectedTypeCastInParameter, node);
  14113. }
  14114. this.toAssignable(node.expression, isLHS);
  14115. break;
  14116. case "AssignmentExpression":
  14117. if (!isLHS && node.left.type === "TSTypeCastExpression") {
  14118. node.left = this.typeCastToParameter(node.left);
  14119. }
  14120. default:
  14121. super.toAssignable(node, isLHS);
  14122. }
  14123. }
  14124. toAssignableParenthesizedExpression(node, isLHS) {
  14125. switch (node.expression.type) {
  14126. case "TSAsExpression":
  14127. case "TSSatisfiesExpression":
  14128. case "TSNonNullExpression":
  14129. case "TSTypeAssertion":
  14130. case "ParenthesizedExpression":
  14131. this.toAssignable(node.expression, isLHS);
  14132. break;
  14133. default:
  14134. super.toAssignable(node, isLHS);
  14135. }
  14136. }
  14137. checkToRestConversion(node, allowPattern) {
  14138. switch (node.type) {
  14139. case "TSAsExpression":
  14140. case "TSSatisfiesExpression":
  14141. case "TSTypeAssertion":
  14142. case "TSNonNullExpression":
  14143. this.checkToRestConversion(node.expression, false);
  14144. break;
  14145. default:
  14146. super.checkToRestConversion(node, allowPattern);
  14147. }
  14148. }
  14149. isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) {
  14150. switch (type) {
  14151. case "TSTypeCastExpression":
  14152. return true;
  14153. case "TSParameterProperty":
  14154. return "parameter";
  14155. case "TSNonNullExpression":
  14156. return "expression";
  14157. case "TSAsExpression":
  14158. case "TSSatisfiesExpression":
  14159. case "TSTypeAssertion":
  14160. return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true];
  14161. default:
  14162. return super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding);
  14163. }
  14164. }
  14165. parseBindingAtom() {
  14166. if (this.state.type === 78) {
  14167. return this.parseIdentifier(true);
  14168. }
  14169. return super.parseBindingAtom();
  14170. }
  14171. parseMaybeDecoratorArguments(expr, startLoc) {
  14172. if (this.match(47) || this.match(51)) {
  14173. const typeArguments = this.tsParseTypeArgumentsInExpression();
  14174. if (this.match(10)) {
  14175. const call = super.parseMaybeDecoratorArguments(expr, startLoc);
  14176. call.typeParameters = typeArguments;
  14177. return call;
  14178. }
  14179. this.unexpected(null, 10);
  14180. }
  14181. return super.parseMaybeDecoratorArguments(expr, startLoc);
  14182. }
  14183. checkCommaAfterRest(close) {
  14184. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  14185. this.next();
  14186. return false;
  14187. }
  14188. return super.checkCommaAfterRest(close);
  14189. }
  14190. isClassMethod() {
  14191. return this.match(47) || super.isClassMethod();
  14192. }
  14193. isClassProperty() {
  14194. return this.match(35) || this.match(14) || super.isClassProperty();
  14195. }
  14196. parseMaybeDefault(startLoc, left) {
  14197. const node = super.parseMaybeDefault(startLoc, left);
  14198. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  14199. this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation);
  14200. }
  14201. return node;
  14202. }
  14203. getTokenFromCode(code) {
  14204. if (this.state.inType) {
  14205. if (code === 62) {
  14206. this.finishOp(48, 1);
  14207. return;
  14208. }
  14209. if (code === 60) {
  14210. this.finishOp(47, 1);
  14211. return;
  14212. }
  14213. }
  14214. super.getTokenFromCode(code);
  14215. }
  14216. reScan_lt_gt() {
  14217. const {
  14218. type
  14219. } = this.state;
  14220. if (type === 47) {
  14221. this.state.pos -= 1;
  14222. this.readToken_lt();
  14223. } else if (type === 48) {
  14224. this.state.pos -= 1;
  14225. this.readToken_gt();
  14226. }
  14227. }
  14228. reScan_lt() {
  14229. const {
  14230. type
  14231. } = this.state;
  14232. if (type === 51) {
  14233. this.state.pos -= 2;
  14234. this.finishOp(47, 1);
  14235. return 47;
  14236. }
  14237. return type;
  14238. }
  14239. toAssignableListItem(exprList, index, isLHS) {
  14240. const node = exprList[index];
  14241. if (node.type === "TSTypeCastExpression") {
  14242. exprList[index] = this.typeCastToParameter(node);
  14243. }
  14244. super.toAssignableListItem(exprList, index, isLHS);
  14245. }
  14246. typeCastToParameter(node) {
  14247. node.expression.typeAnnotation = node.typeAnnotation;
  14248. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  14249. return node.expression;
  14250. }
  14251. shouldParseArrow(params) {
  14252. if (this.match(14)) {
  14253. return params.every(expr => this.isAssignable(expr, true));
  14254. }
  14255. return super.shouldParseArrow(params);
  14256. }
  14257. shouldParseAsyncArrow() {
  14258. return this.match(14) || super.shouldParseAsyncArrow();
  14259. }
  14260. canHaveLeadingDecorator() {
  14261. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  14262. }
  14263. jsxParseOpeningElementAfterName(node) {
  14264. if (this.match(47) || this.match(51)) {
  14265. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression());
  14266. if (typeArguments) {
  14267. node.typeParameters = typeArguments;
  14268. }
  14269. }
  14270. return super.jsxParseOpeningElementAfterName(node);
  14271. }
  14272. getGetterSetterExpectedParamCount(method) {
  14273. const baseCount = super.getGetterSetterExpectedParamCount(method);
  14274. const params = this.getObjectOrClassMethodParams(method);
  14275. const firstParam = params[0];
  14276. const hasContextParam = firstParam && this.isThisParam(firstParam);
  14277. return hasContextParam ? baseCount + 1 : baseCount;
  14278. }
  14279. parseCatchClauseParam() {
  14280. const param = super.parseCatchClauseParam();
  14281. const type = this.tsTryParseTypeAnnotation();
  14282. if (type) {
  14283. param.typeAnnotation = type;
  14284. this.resetEndLocation(param);
  14285. }
  14286. return param;
  14287. }
  14288. tsInAmbientContext(cb) {
  14289. const {
  14290. isAmbientContext: oldIsAmbientContext,
  14291. strict: oldStrict
  14292. } = this.state;
  14293. this.state.isAmbientContext = true;
  14294. this.state.strict = false;
  14295. try {
  14296. return cb();
  14297. } finally {
  14298. this.state.isAmbientContext = oldIsAmbientContext;
  14299. this.state.strict = oldStrict;
  14300. }
  14301. }
  14302. parseClass(node, isStatement, optionalId) {
  14303. const oldInAbstractClass = this.state.inAbstractClass;
  14304. this.state.inAbstractClass = !!node.abstract;
  14305. try {
  14306. return super.parseClass(node, isStatement, optionalId);
  14307. } finally {
  14308. this.state.inAbstractClass = oldInAbstractClass;
  14309. }
  14310. }
  14311. tsParseAbstractDeclaration(node, decorators) {
  14312. if (this.match(80)) {
  14313. node.abstract = true;
  14314. return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false));
  14315. } else if (this.isContextual(129)) {
  14316. if (!this.hasFollowingLineBreak()) {
  14317. node.abstract = true;
  14318. this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifier, node);
  14319. return this.tsParseInterfaceDeclaration(node);
  14320. } else {
  14321. return null;
  14322. }
  14323. }
  14324. throw this.unexpected(null, 80);
  14325. }
  14326. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) {
  14327. const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  14328. if (method.abstract || method.type === "TSAbstractMethodDefinition") {
  14329. const hasEstreePlugin = this.hasPlugin("estree");
  14330. const methodFn = hasEstreePlugin ? method.value : method;
  14331. if (methodFn.body) {
  14332. const {
  14333. key
  14334. } = method;
  14335. this.raise(TSErrors.AbstractMethodHasImplementation, method, {
  14336. methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  14337. });
  14338. }
  14339. }
  14340. return method;
  14341. }
  14342. tsParseTypeParameterName() {
  14343. const typeName = this.parseIdentifier();
  14344. return typeName.name;
  14345. }
  14346. shouldParseAsAmbientContext() {
  14347. return !!this.getPluginOption("typescript", "dts");
  14348. }
  14349. parse() {
  14350. if (this.shouldParseAsAmbientContext()) {
  14351. this.state.isAmbientContext = true;
  14352. }
  14353. return super.parse();
  14354. }
  14355. getExpression() {
  14356. if (this.shouldParseAsAmbientContext()) {
  14357. this.state.isAmbientContext = true;
  14358. }
  14359. return super.getExpression();
  14360. }
  14361. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  14362. if (!isString && isMaybeTypeOnly) {
  14363. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  14364. return this.finishNode(node, "ExportSpecifier");
  14365. }
  14366. node.exportKind = "value";
  14367. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  14368. }
  14369. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  14370. if (!importedIsString && isMaybeTypeOnly) {
  14371. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  14372. return this.finishNode(specifier, "ImportSpecifier");
  14373. }
  14374. specifier.importKind = "value";
  14375. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096);
  14376. }
  14377. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  14378. const leftOfAsKey = isImport ? "imported" : "local";
  14379. const rightOfAsKey = isImport ? "local" : "exported";
  14380. let leftOfAs = node[leftOfAsKey];
  14381. let rightOfAs;
  14382. let hasTypeSpecifier = false;
  14383. let canParseAsKeyword = true;
  14384. const loc = leftOfAs.loc.start;
  14385. if (this.isContextual(93)) {
  14386. const firstAs = this.parseIdentifier();
  14387. if (this.isContextual(93)) {
  14388. const secondAs = this.parseIdentifier();
  14389. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14390. hasTypeSpecifier = true;
  14391. leftOfAs = firstAs;
  14392. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  14393. canParseAsKeyword = false;
  14394. } else {
  14395. rightOfAs = secondAs;
  14396. canParseAsKeyword = false;
  14397. }
  14398. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14399. canParseAsKeyword = false;
  14400. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  14401. } else {
  14402. hasTypeSpecifier = true;
  14403. leftOfAs = firstAs;
  14404. }
  14405. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14406. hasTypeSpecifier = true;
  14407. if (isImport) {
  14408. leftOfAs = this.parseIdentifier(true);
  14409. if (!this.isContextual(93)) {
  14410. this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true);
  14411. }
  14412. } else {
  14413. leftOfAs = this.parseModuleExportName();
  14414. }
  14415. }
  14416. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  14417. this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc);
  14418. }
  14419. node[leftOfAsKey] = leftOfAs;
  14420. node[rightOfAsKey] = rightOfAs;
  14421. const kindKey = isImport ? "importKind" : "exportKind";
  14422. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  14423. if (canParseAsKeyword && this.eatContextual(93)) {
  14424. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  14425. }
  14426. if (!node[rightOfAsKey]) {
  14427. node[rightOfAsKey] = this.cloneIdentifier(node[leftOfAsKey]);
  14428. }
  14429. if (isImport) {
  14430. this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096);
  14431. }
  14432. }
  14433. fillOptionalPropertiesForTSESLint(node) {
  14434. var _node$directive, _node$decorators, _node$optional, _node$typeAnnotation, _node$accessibility, _node$decorators2, _node$override, _node$readonly, _node$static, _node$declare, _node$returnType, _node$typeParameters, _node$optional2, _node$optional3, _node$accessibility2, _node$readonly2, _node$static2, _node$declare2, _node$definite, _node$readonly3, _node$typeAnnotation2, _node$accessibility3, _node$decorators3, _node$override2, _node$optional4, _node$id, _node$abstract, _node$declare3, _node$decorators4, _node$implements, _node$superTypeArgume, _node$typeParameters2, _node$declare4, _node$definite2, _node$const, _node$declare5, _node$computed, _node$qualifier, _node$options, _node$declare6, _node$extends, _node$optional5, _node$readonly4, _node$declare7, _node$global, _node$const2, _node$in, _node$out;
  14435. switch (node.type) {
  14436. case "ExpressionStatement":
  14437. (_node$directive = node.directive) != null ? _node$directive : node.directive = undefined;
  14438. return;
  14439. case "RestElement":
  14440. node.value = undefined;
  14441. case "Identifier":
  14442. case "ArrayPattern":
  14443. case "AssignmentPattern":
  14444. case "ObjectPattern":
  14445. (_node$decorators = node.decorators) != null ? _node$decorators : node.decorators = [];
  14446. (_node$optional = node.optional) != null ? _node$optional : node.optional = false;
  14447. (_node$typeAnnotation = node.typeAnnotation) != null ? _node$typeAnnotation : node.typeAnnotation = undefined;
  14448. return;
  14449. case "TSParameterProperty":
  14450. (_node$accessibility = node.accessibility) != null ? _node$accessibility : node.accessibility = undefined;
  14451. (_node$decorators2 = node.decorators) != null ? _node$decorators2 : node.decorators = [];
  14452. (_node$override = node.override) != null ? _node$override : node.override = false;
  14453. (_node$readonly = node.readonly) != null ? _node$readonly : node.readonly = false;
  14454. (_node$static = node.static) != null ? _node$static : node.static = false;
  14455. return;
  14456. case "TSEmptyBodyFunctionExpression":
  14457. node.body = null;
  14458. case "TSDeclareFunction":
  14459. case "FunctionDeclaration":
  14460. case "FunctionExpression":
  14461. case "ClassMethod":
  14462. case "ClassPrivateMethod":
  14463. (_node$declare = node.declare) != null ? _node$declare : node.declare = false;
  14464. (_node$returnType = node.returnType) != null ? _node$returnType : node.returnType = undefined;
  14465. (_node$typeParameters = node.typeParameters) != null ? _node$typeParameters : node.typeParameters = undefined;
  14466. return;
  14467. case "Property":
  14468. (_node$optional2 = node.optional) != null ? _node$optional2 : node.optional = false;
  14469. return;
  14470. case "TSMethodSignature":
  14471. case "TSPropertySignature":
  14472. (_node$optional3 = node.optional) != null ? _node$optional3 : node.optional = false;
  14473. case "TSIndexSignature":
  14474. (_node$accessibility2 = node.accessibility) != null ? _node$accessibility2 : node.accessibility = undefined;
  14475. (_node$readonly2 = node.readonly) != null ? _node$readonly2 : node.readonly = false;
  14476. (_node$static2 = node.static) != null ? _node$static2 : node.static = false;
  14477. return;
  14478. case "TSAbstractPropertyDefinition":
  14479. case "PropertyDefinition":
  14480. case "TSAbstractAccessorProperty":
  14481. case "AccessorProperty":
  14482. (_node$declare2 = node.declare) != null ? _node$declare2 : node.declare = false;
  14483. (_node$definite = node.definite) != null ? _node$definite : node.definite = false;
  14484. (_node$readonly3 = node.readonly) != null ? _node$readonly3 : node.readonly = false;
  14485. (_node$typeAnnotation2 = node.typeAnnotation) != null ? _node$typeAnnotation2 : node.typeAnnotation = undefined;
  14486. case "TSAbstractMethodDefinition":
  14487. case "MethodDefinition":
  14488. (_node$accessibility3 = node.accessibility) != null ? _node$accessibility3 : node.accessibility = undefined;
  14489. (_node$decorators3 = node.decorators) != null ? _node$decorators3 : node.decorators = [];
  14490. (_node$override2 = node.override) != null ? _node$override2 : node.override = false;
  14491. (_node$optional4 = node.optional) != null ? _node$optional4 : node.optional = false;
  14492. return;
  14493. case "ClassExpression":
  14494. (_node$id = node.id) != null ? _node$id : node.id = null;
  14495. case "ClassDeclaration":
  14496. (_node$abstract = node.abstract) != null ? _node$abstract : node.abstract = false;
  14497. (_node$declare3 = node.declare) != null ? _node$declare3 : node.declare = false;
  14498. (_node$decorators4 = node.decorators) != null ? _node$decorators4 : node.decorators = [];
  14499. (_node$implements = node.implements) != null ? _node$implements : node.implements = [];
  14500. (_node$superTypeArgume = node.superTypeArguments) != null ? _node$superTypeArgume : node.superTypeArguments = undefined;
  14501. (_node$typeParameters2 = node.typeParameters) != null ? _node$typeParameters2 : node.typeParameters = undefined;
  14502. return;
  14503. case "TSTypeAliasDeclaration":
  14504. case "VariableDeclaration":
  14505. (_node$declare4 = node.declare) != null ? _node$declare4 : node.declare = false;
  14506. return;
  14507. case "VariableDeclarator":
  14508. (_node$definite2 = node.definite) != null ? _node$definite2 : node.definite = false;
  14509. return;
  14510. case "TSEnumDeclaration":
  14511. (_node$const = node.const) != null ? _node$const : node.const = false;
  14512. (_node$declare5 = node.declare) != null ? _node$declare5 : node.declare = false;
  14513. return;
  14514. case "TSEnumMember":
  14515. (_node$computed = node.computed) != null ? _node$computed : node.computed = false;
  14516. return;
  14517. case "TSImportType":
  14518. (_node$qualifier = node.qualifier) != null ? _node$qualifier : node.qualifier = null;
  14519. (_node$options = node.options) != null ? _node$options : node.options = null;
  14520. return;
  14521. case "TSInterfaceDeclaration":
  14522. (_node$declare6 = node.declare) != null ? _node$declare6 : node.declare = false;
  14523. (_node$extends = node.extends) != null ? _node$extends : node.extends = [];
  14524. return;
  14525. case "TSMappedType":
  14526. (_node$optional5 = node.optional) != null ? _node$optional5 : node.optional = false;
  14527. (_node$readonly4 = node.readonly) != null ? _node$readonly4 : node.readonly = undefined;
  14528. return;
  14529. case "TSModuleDeclaration":
  14530. (_node$declare7 = node.declare) != null ? _node$declare7 : node.declare = false;
  14531. (_node$global = node.global) != null ? _node$global : node.global = node.kind === "global";
  14532. return;
  14533. case "TSTypeParameter":
  14534. (_node$const2 = node.const) != null ? _node$const2 : node.const = false;
  14535. (_node$in = node.in) != null ? _node$in : node.in = false;
  14536. (_node$out = node.out) != null ? _node$out : node.out = false;
  14537. return;
  14538. }
  14539. }
  14540. chStartsBindingIdentifierAndNotRelationalOperator(ch, pos) {
  14541. if (isIdentifierStart(ch)) {
  14542. keywordAndTSRelationalOperator.lastIndex = pos;
  14543. if (keywordAndTSRelationalOperator.test(this.input)) {
  14544. const endCh = this.codePointAtPos(keywordAndTSRelationalOperator.lastIndex);
  14545. if (!isIdentifierChar(endCh) && endCh !== 92) {
  14546. return false;
  14547. }
  14548. }
  14549. return true;
  14550. } else if (ch === 92) {
  14551. return true;
  14552. } else {
  14553. return false;
  14554. }
  14555. }
  14556. nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine() {
  14557. const next = this.nextTokenInLineStart();
  14558. const nextCh = this.codePointAtPos(next);
  14559. return this.chStartsBindingIdentifierAndNotRelationalOperator(nextCh, next);
  14560. }
  14561. nextTokenIsIdentifierOrStringLiteralOnSameLine() {
  14562. const next = this.nextTokenInLineStart();
  14563. const nextCh = this.codePointAtPos(next);
  14564. return this.chStartsBindingIdentifier(nextCh, next) || nextCh === 34 || nextCh === 39;
  14565. }
  14566. };
  14567. function isPossiblyLiteralEnum(expression) {
  14568. if (expression.type !== "MemberExpression") return false;
  14569. const {
  14570. computed,
  14571. property
  14572. } = expression;
  14573. if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) {
  14574. return false;
  14575. }
  14576. return isUncomputedMemberExpressionChain(expression.object);
  14577. }
  14578. function isValidAmbientConstInitializer(expression, estree) {
  14579. var _expression$extra;
  14580. const {
  14581. type
  14582. } = expression;
  14583. if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) {
  14584. return false;
  14585. }
  14586. if (estree) {
  14587. if (type === "Literal") {
  14588. const {
  14589. value
  14590. } = expression;
  14591. if (typeof value === "string" || typeof value === "boolean") {
  14592. return true;
  14593. }
  14594. }
  14595. } else {
  14596. if (type === "StringLiteral" || type === "BooleanLiteral") {
  14597. return true;
  14598. }
  14599. }
  14600. if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) {
  14601. return true;
  14602. }
  14603. if (type === "TemplateLiteral" && expression.expressions.length === 0) {
  14604. return true;
  14605. }
  14606. if (isPossiblyLiteralEnum(expression)) {
  14607. return true;
  14608. }
  14609. return false;
  14610. }
  14611. function isNumber(expression, estree) {
  14612. if (estree) {
  14613. return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression);
  14614. }
  14615. return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral";
  14616. }
  14617. function isNegativeNumber(expression, estree) {
  14618. if (expression.type === "UnaryExpression") {
  14619. const {
  14620. operator,
  14621. argument
  14622. } = expression;
  14623. if (operator === "-" && isNumber(argument, estree)) {
  14624. return true;
  14625. }
  14626. }
  14627. return false;
  14628. }
  14629. function isUncomputedMemberExpressionChain(expression) {
  14630. if (expression.type === "Identifier") return true;
  14631. if (expression.type !== "MemberExpression" || expression.computed) {
  14632. return false;
  14633. }
  14634. return isUncomputedMemberExpressionChain(expression.object);
  14635. }
  14636. const PlaceholderErrors = ParseErrorEnum`placeholders`({
  14637. ClassNameIsRequired: "A class name is required.",
  14638. UnexpectedSpace: "Unexpected space in placeholder."
  14639. });
  14640. var placeholders = superClass => class PlaceholdersParserMixin extends superClass {
  14641. parsePlaceholder(expectedNode) {
  14642. if (this.match(133)) {
  14643. const node = this.startNode();
  14644. this.next();
  14645. this.assertNoSpace();
  14646. node.name = super.parseIdentifier(true);
  14647. this.assertNoSpace();
  14648. this.expect(133);
  14649. return this.finishPlaceholder(node, expectedNode);
  14650. }
  14651. }
  14652. finishPlaceholder(node, expectedNode) {
  14653. let placeholder = node;
  14654. if (!placeholder.expectedNode || !placeholder.type) {
  14655. placeholder = this.finishNode(placeholder, "Placeholder");
  14656. }
  14657. placeholder.expectedNode = expectedNode;
  14658. return placeholder;
  14659. }
  14660. getTokenFromCode(code) {
  14661. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  14662. this.finishOp(133, 2);
  14663. } else {
  14664. super.getTokenFromCode(code);
  14665. }
  14666. }
  14667. parseExprAtom(refExpressionErrors) {
  14668. return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors);
  14669. }
  14670. parseIdentifier(liberal) {
  14671. return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal);
  14672. }
  14673. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  14674. if (word !== undefined) {
  14675. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  14676. }
  14677. }
  14678. cloneIdentifier(node) {
  14679. const cloned = super.cloneIdentifier(node);
  14680. if (cloned.type === "Placeholder") {
  14681. cloned.expectedNode = node.expectedNode;
  14682. }
  14683. return cloned;
  14684. }
  14685. cloneStringLiteral(node) {
  14686. if (node.type === "Placeholder") {
  14687. return this.cloneIdentifier(node);
  14688. }
  14689. return super.cloneStringLiteral(node);
  14690. }
  14691. parseBindingAtom() {
  14692. return this.parsePlaceholder("Pattern") || super.parseBindingAtom();
  14693. }
  14694. isValidLVal(type, disallowCallExpression, isParenthesized, binding) {
  14695. return type === "Placeholder" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding);
  14696. }
  14697. toAssignable(node, isLHS) {
  14698. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  14699. node.expectedNode = "Pattern";
  14700. } else {
  14701. super.toAssignable(node, isLHS);
  14702. }
  14703. }
  14704. chStartsBindingIdentifier(ch, pos) {
  14705. if (super.chStartsBindingIdentifier(ch, pos)) {
  14706. return true;
  14707. }
  14708. const next = this.nextTokenStart();
  14709. if (this.input.charCodeAt(next) === 37 && this.input.charCodeAt(next + 1) === 37) {
  14710. return true;
  14711. }
  14712. return false;
  14713. }
  14714. verifyBreakContinue(node, isBreak) {
  14715. var _node$label;
  14716. if (((_node$label = node.label) == null ? void 0 : _node$label.type) === "Placeholder") return;
  14717. super.verifyBreakContinue(node, isBreak);
  14718. }
  14719. parseExpressionStatement(node, expr) {
  14720. var _expr$extra;
  14721. if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  14722. return super.parseExpressionStatement(node, expr);
  14723. }
  14724. if (this.match(14)) {
  14725. const stmt = node;
  14726. stmt.label = this.finishPlaceholder(expr, "Identifier");
  14727. this.next();
  14728. stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration();
  14729. return this.finishNode(stmt, "LabeledStatement");
  14730. }
  14731. this.semicolon();
  14732. const stmtPlaceholder = node;
  14733. stmtPlaceholder.name = expr.name;
  14734. return this.finishPlaceholder(stmtPlaceholder, "Statement");
  14735. }
  14736. parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) {
  14737. return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse);
  14738. }
  14739. parseFunctionId(requireId) {
  14740. return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId);
  14741. }
  14742. parseClass(node, isStatement, optionalId) {
  14743. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  14744. this.next();
  14745. const oldStrict = this.state.strict;
  14746. const placeholder = this.parsePlaceholder("Identifier");
  14747. if (placeholder) {
  14748. if (this.match(81) || this.match(133) || this.match(5)) {
  14749. node.id = placeholder;
  14750. } else if (optionalId || !isStatement) {
  14751. node.id = null;
  14752. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  14753. return this.finishNode(node, type);
  14754. } else {
  14755. throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc);
  14756. }
  14757. } else {
  14758. this.parseClassId(node, isStatement, optionalId);
  14759. }
  14760. super.parseClassSuper(node);
  14761. node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict);
  14762. return this.finishNode(node, type);
  14763. }
  14764. parseExport(node, decorators) {
  14765. const placeholder = this.parsePlaceholder("Identifier");
  14766. if (!placeholder) return super.parseExport(node, decorators);
  14767. const node2 = node;
  14768. if (!this.isContextual(98) && !this.match(12)) {
  14769. node2.specifiers = [];
  14770. node2.source = null;
  14771. node2.declaration = this.finishPlaceholder(placeholder, "Declaration");
  14772. return this.finishNode(node2, "ExportNamedDeclaration");
  14773. }
  14774. this.expectPlugin("exportDefaultFrom");
  14775. const specifier = this.startNode();
  14776. specifier.exported = placeholder;
  14777. node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  14778. return super.parseExport(node2, decorators);
  14779. }
  14780. isExportDefaultSpecifier() {
  14781. if (this.match(65)) {
  14782. const next = this.nextTokenStart();
  14783. if (this.isUnparsedContextual(next, "from")) {
  14784. if (this.input.startsWith(tokenLabelName(133), this.nextTokenStartSince(next + 4))) {
  14785. return true;
  14786. }
  14787. }
  14788. }
  14789. return super.isExportDefaultSpecifier();
  14790. }
  14791. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  14792. var _specifiers;
  14793. if ((_specifiers = node.specifiers) != null && _specifiers.length) {
  14794. return true;
  14795. }
  14796. return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  14797. }
  14798. checkExport(node) {
  14799. const {
  14800. specifiers
  14801. } = node;
  14802. if (specifiers != null && specifiers.length) {
  14803. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  14804. }
  14805. super.checkExport(node);
  14806. node.specifiers = specifiers;
  14807. }
  14808. parseImport(node) {
  14809. const placeholder = this.parsePlaceholder("Identifier");
  14810. if (!placeholder) return super.parseImport(node);
  14811. node.specifiers = [];
  14812. if (!this.isContextual(98) && !this.match(12)) {
  14813. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  14814. this.semicolon();
  14815. return this.finishNode(node, "ImportDeclaration");
  14816. }
  14817. const specifier = this.startNodeAtNode(placeholder);
  14818. specifier.local = placeholder;
  14819. node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier"));
  14820. if (this.eat(12)) {
  14821. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  14822. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  14823. }
  14824. this.expectContextual(98);
  14825. node.source = this.parseImportSource();
  14826. this.semicolon();
  14827. return this.finishNode(node, "ImportDeclaration");
  14828. }
  14829. parseImportSource() {
  14830. return this.parsePlaceholder("StringLiteral") || super.parseImportSource();
  14831. }
  14832. assertNoSpace() {
  14833. if (this.state.start > this.offsetToSourcePos(this.state.lastTokEndLoc.index)) {
  14834. this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc);
  14835. }
  14836. }
  14837. };
  14838. var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass {
  14839. parseV8Intrinsic() {
  14840. if (this.match(54)) {
  14841. const v8IntrinsicStartLoc = this.state.startLoc;
  14842. const node = this.startNode();
  14843. this.next();
  14844. if (tokenIsIdentifier(this.state.type)) {
  14845. const name = this.parseIdentifierName();
  14846. const identifier = this.createIdentifier(node, name);
  14847. this.castNodeTo(identifier, "V8IntrinsicIdentifier");
  14848. if (this.match(10)) {
  14849. return identifier;
  14850. }
  14851. }
  14852. this.unexpected(v8IntrinsicStartLoc);
  14853. }
  14854. }
  14855. parseExprAtom(refExpressionErrors) {
  14856. return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors);
  14857. }
  14858. };
  14859. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  14860. const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"];
  14861. function validatePlugins(pluginsMap) {
  14862. if (pluginsMap.has("decorators")) {
  14863. if (pluginsMap.has("decorators-legacy")) {
  14864. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  14865. }
  14866. const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport;
  14867. if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") {
  14868. throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");
  14869. }
  14870. const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized;
  14871. if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") {
  14872. throw new Error("'allowCallParenthesized' must be a boolean.");
  14873. }
  14874. }
  14875. if (pluginsMap.has("flow") && pluginsMap.has("typescript")) {
  14876. throw new Error("Cannot combine flow and typescript plugins.");
  14877. }
  14878. if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) {
  14879. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  14880. }
  14881. if (pluginsMap.has("pipelineOperator")) {
  14882. var _pluginsMap$get2;
  14883. const proposal = pluginsMap.get("pipelineOperator").proposal;
  14884. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  14885. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  14886. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  14887. }
  14888. if (proposal === "hack") {
  14889. var _pluginsMap$get;
  14890. if (pluginsMap.has("placeholders")) {
  14891. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  14892. }
  14893. if (pluginsMap.has("v8intrinsic")) {
  14894. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  14895. }
  14896. const topicToken = pluginsMap.get("pipelineOperator").topicToken;
  14897. if (!TOPIC_TOKENS.includes(topicToken)) {
  14898. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  14899. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  14900. }
  14901. if (topicToken === "#" && ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash") {
  14902. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  14903. }
  14904. } else if (proposal === "smart" && ((_pluginsMap$get2 = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get2.syntaxType) === "hash") {
  14905. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  14906. }
  14907. }
  14908. if (pluginsMap.has("moduleAttributes")) {
  14909. if (pluginsMap.has("deprecatedImportAssert") || pluginsMap.has("importAssertions")) {
  14910. throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");
  14911. }
  14912. const moduleAttributesVersionPluginOption = pluginsMap.get("moduleAttributes").version;
  14913. if (moduleAttributesVersionPluginOption !== "may-2020") {
  14914. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  14915. }
  14916. }
  14917. if (pluginsMap.has("importAssertions")) {
  14918. if (pluginsMap.has("deprecatedImportAssert")) {
  14919. throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");
  14920. }
  14921. }
  14922. if (pluginsMap.has("deprecatedImportAssert")) ;else if (pluginsMap.has("importAttributes") && pluginsMap.get("importAttributes").deprecatedAssertSyntax) {
  14923. pluginsMap.set("deprecatedImportAssert", {});
  14924. }
  14925. if (pluginsMap.has("recordAndTuple")) {
  14926. const syntaxType = pluginsMap.get("recordAndTuple").syntaxType;
  14927. if (syntaxType != null) {
  14928. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  14929. if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) {
  14930. throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  14931. }
  14932. }
  14933. }
  14934. if (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) {
  14935. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  14936. error.missingPlugins = "doExpressions";
  14937. throw error;
  14938. }
  14939. if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("optionalChainingAssign").version !== "2023-07") {
  14940. throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'.");
  14941. }
  14942. if (pluginsMap.has("discardBinding") && pluginsMap.get("discardBinding").syntaxType !== "void") {
  14943. throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.");
  14944. }
  14945. }
  14946. const mixinPlugins = {
  14947. estree,
  14948. jsx,
  14949. flow,
  14950. typescript,
  14951. v8intrinsic,
  14952. placeholders
  14953. };
  14954. const mixinPluginNames = Object.keys(mixinPlugins);
  14955. class ExpressionParser extends LValParser {
  14956. checkProto(prop, isRecord, sawProto, refExpressionErrors) {
  14957. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  14958. return sawProto;
  14959. }
  14960. const key = prop.key;
  14961. const name = key.type === "Identifier" ? key.name : key.value;
  14962. if (name === "__proto__") {
  14963. if (isRecord) {
  14964. this.raise(Errors.RecordNoProto, key);
  14965. return true;
  14966. }
  14967. if (sawProto) {
  14968. if (refExpressionErrors) {
  14969. if (refExpressionErrors.doubleProtoLoc === null) {
  14970. refExpressionErrors.doubleProtoLoc = key.loc.start;
  14971. }
  14972. } else {
  14973. this.raise(Errors.DuplicateProto, key);
  14974. }
  14975. }
  14976. return true;
  14977. }
  14978. return sawProto;
  14979. }
  14980. shouldExitDescending(expr, potentialArrowAt) {
  14981. return expr.type === "ArrowFunctionExpression" && this.offsetToSourcePos(expr.start) === potentialArrowAt;
  14982. }
  14983. getExpression() {
  14984. this.enterInitialScopes();
  14985. this.nextToken();
  14986. if (this.match(140)) {
  14987. throw this.raise(Errors.ParseExpressionEmptyInput, this.state.startLoc);
  14988. }
  14989. const expr = this.parseExpression();
  14990. if (!this.match(140)) {
  14991. throw this.raise(Errors.ParseExpressionExpectsEOF, this.state.startLoc, {
  14992. unexpected: this.input.codePointAt(this.state.start)
  14993. });
  14994. }
  14995. this.finalizeRemainingComments();
  14996. expr.comments = this.comments;
  14997. expr.errors = this.state.errors;
  14998. if (this.optionFlags & 256) {
  14999. expr.tokens = this.tokens;
  15000. }
  15001. return expr;
  15002. }
  15003. parseExpression(disallowIn, refExpressionErrors) {
  15004. if (disallowIn) {
  15005. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  15006. }
  15007. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  15008. }
  15009. parseExpressionBase(refExpressionErrors) {
  15010. const startLoc = this.state.startLoc;
  15011. const expr = this.parseMaybeAssign(refExpressionErrors);
  15012. if (this.match(12)) {
  15013. const node = this.startNodeAt(startLoc);
  15014. node.expressions = [expr];
  15015. while (this.eat(12)) {
  15016. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  15017. }
  15018. this.toReferencedList(node.expressions);
  15019. return this.finishNode(node, "SequenceExpression");
  15020. }
  15021. return expr;
  15022. }
  15023. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  15024. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  15025. }
  15026. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  15027. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  15028. }
  15029. setOptionalParametersError(refExpressionErrors) {
  15030. refExpressionErrors.optionalParametersLoc = this.state.startLoc;
  15031. }
  15032. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  15033. const startLoc = this.state.startLoc;
  15034. const isYield = this.isContextual(108);
  15035. if (isYield) {
  15036. if (this.prodParam.hasYield) {
  15037. this.next();
  15038. let left = this.parseYield(startLoc);
  15039. if (afterLeftParse) {
  15040. left = afterLeftParse.call(this, left, startLoc);
  15041. }
  15042. return left;
  15043. }
  15044. }
  15045. let ownExpressionErrors;
  15046. if (refExpressionErrors) {
  15047. ownExpressionErrors = false;
  15048. } else {
  15049. refExpressionErrors = new ExpressionErrors();
  15050. ownExpressionErrors = true;
  15051. }
  15052. const {
  15053. type
  15054. } = this.state;
  15055. if (type === 10 || tokenIsIdentifier(type)) {
  15056. this.state.potentialArrowAt = this.state.start;
  15057. }
  15058. let left = this.parseMaybeConditional(refExpressionErrors);
  15059. if (afterLeftParse) {
  15060. left = afterLeftParse.call(this, left, startLoc);
  15061. }
  15062. if (tokenIsAssignment(this.state.type)) {
  15063. const node = this.startNodeAt(startLoc);
  15064. const operator = this.state.value;
  15065. node.operator = operator;
  15066. if (this.match(29)) {
  15067. this.toAssignable(left, true);
  15068. node.left = left;
  15069. const startIndex = startLoc.index;
  15070. if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) {
  15071. refExpressionErrors.doubleProtoLoc = null;
  15072. }
  15073. if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) {
  15074. refExpressionErrors.shorthandAssignLoc = null;
  15075. }
  15076. if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) {
  15077. this.checkDestructuringPrivate(refExpressionErrors);
  15078. refExpressionErrors.privateKeyLoc = null;
  15079. }
  15080. if (refExpressionErrors.voidPatternLoc != null && refExpressionErrors.voidPatternLoc.index >= startIndex) {
  15081. refExpressionErrors.voidPatternLoc = null;
  15082. }
  15083. } else {
  15084. node.left = left;
  15085. }
  15086. this.next();
  15087. node.right = this.parseMaybeAssign();
  15088. this.checkLVal(left, this.finishNode(node, "AssignmentExpression"), undefined, undefined, undefined, undefined, operator === "||=" || operator === "&&=" || operator === "??=");
  15089. return node;
  15090. } else if (ownExpressionErrors) {
  15091. this.checkExpressionErrors(refExpressionErrors, true);
  15092. }
  15093. if (isYield) {
  15094. const {
  15095. type
  15096. } = this.state;
  15097. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  15098. if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {
  15099. this.raiseOverwrite(Errors.YieldNotInGeneratorFunction, startLoc);
  15100. return this.parseYield(startLoc);
  15101. }
  15102. }
  15103. return left;
  15104. }
  15105. parseMaybeConditional(refExpressionErrors) {
  15106. const startLoc = this.state.startLoc;
  15107. const potentialArrowAt = this.state.potentialArrowAt;
  15108. const expr = this.parseExprOps(refExpressionErrors);
  15109. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  15110. return expr;
  15111. }
  15112. return this.parseConditional(expr, startLoc, refExpressionErrors);
  15113. }
  15114. parseConditional(expr, startLoc, refExpressionErrors) {
  15115. if (this.eat(17)) {
  15116. const node = this.startNodeAt(startLoc);
  15117. node.test = expr;
  15118. node.consequent = this.parseMaybeAssignAllowIn();
  15119. this.expect(14);
  15120. node.alternate = this.parseMaybeAssign();
  15121. return this.finishNode(node, "ConditionalExpression");
  15122. }
  15123. return expr;
  15124. }
  15125. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  15126. return this.match(139) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  15127. }
  15128. parseExprOps(refExpressionErrors) {
  15129. const startLoc = this.state.startLoc;
  15130. const potentialArrowAt = this.state.potentialArrowAt;
  15131. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  15132. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  15133. return expr;
  15134. }
  15135. return this.parseExprOp(expr, startLoc, -1);
  15136. }
  15137. parseExprOp(left, leftStartLoc, minPrec) {
  15138. if (this.isPrivateName(left)) {
  15139. const value = this.getPrivateNameSV(left);
  15140. if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) {
  15141. this.raise(Errors.PrivateInExpectedIn, left, {
  15142. identifierName: value
  15143. });
  15144. }
  15145. this.classScope.usePrivateName(value, left.loc.start);
  15146. }
  15147. const op = this.state.type;
  15148. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) {
  15149. let prec = tokenOperatorPrecedence(op);
  15150. if (prec > minPrec) {
  15151. if (op === 39) {
  15152. this.expectPlugin("pipelineOperator");
  15153. if (this.state.inFSharpPipelineDirectBody) {
  15154. return left;
  15155. }
  15156. this.checkPipelineAtInfixOperator(left, leftStartLoc);
  15157. }
  15158. const node = this.startNodeAt(leftStartLoc);
  15159. node.left = left;
  15160. node.operator = this.state.value;
  15161. const logical = op === 41 || op === 42;
  15162. const coalesce = op === 40;
  15163. if (coalesce) {
  15164. prec = tokenOperatorPrecedence(42);
  15165. }
  15166. this.next();
  15167. if (op === 39 && this.hasPlugin(["pipelineOperator", {
  15168. proposal: "minimal"
  15169. }])) {
  15170. if (this.state.type === 96 && this.prodParam.hasAwait) {
  15171. throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc);
  15172. }
  15173. }
  15174. node.right = this.parseExprOpRightExpr(op, prec);
  15175. const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  15176. const nextOp = this.state.type;
  15177. if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) {
  15178. throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc);
  15179. }
  15180. return this.parseExprOp(finishedNode, leftStartLoc, minPrec);
  15181. }
  15182. }
  15183. return left;
  15184. }
  15185. parseExprOpRightExpr(op, prec) {
  15186. const startLoc = this.state.startLoc;
  15187. switch (op) {
  15188. case 39:
  15189. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  15190. case "hack":
  15191. return this.withTopicBindingContext(() => {
  15192. return this.parseHackPipeBody();
  15193. });
  15194. case "fsharp":
  15195. return this.withSoloAwaitPermittingContext(() => {
  15196. return this.parseFSharpPipelineBody(prec);
  15197. });
  15198. }
  15199. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  15200. return this.withTopicBindingContext(() => {
  15201. if (this.prodParam.hasYield && this.isContextual(108)) {
  15202. throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc);
  15203. }
  15204. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc);
  15205. });
  15206. }
  15207. default:
  15208. return this.parseExprOpBaseRightExpr(op, prec);
  15209. }
  15210. }
  15211. parseExprOpBaseRightExpr(op, prec) {
  15212. const startLoc = this.state.startLoc;
  15213. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  15214. }
  15215. parseHackPipeBody() {
  15216. var _body$extra;
  15217. const {
  15218. startLoc
  15219. } = this.state;
  15220. const body = this.parseMaybeAssign();
  15221. const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type);
  15222. if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  15223. this.raise(Errors.PipeUnparenthesizedBody, startLoc, {
  15224. type: body.type
  15225. });
  15226. }
  15227. if (!this.topicReferenceWasUsedInCurrentContext()) {
  15228. this.raise(Errors.PipeTopicUnused, startLoc);
  15229. }
  15230. return body;
  15231. }
  15232. checkExponentialAfterUnary(node) {
  15233. if (this.match(57)) {
  15234. this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument);
  15235. }
  15236. }
  15237. parseMaybeUnary(refExpressionErrors, sawUnary) {
  15238. const startLoc = this.state.startLoc;
  15239. const isAwait = this.isContextual(96);
  15240. if (isAwait && this.recordAwaitIfAllowed()) {
  15241. this.next();
  15242. const expr = this.parseAwait(startLoc);
  15243. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  15244. return expr;
  15245. }
  15246. const update = this.match(34);
  15247. const node = this.startNode();
  15248. if (tokenIsPrefix(this.state.type)) {
  15249. node.operator = this.state.value;
  15250. node.prefix = true;
  15251. if (this.match(72)) {
  15252. this.expectPlugin("throwExpressions");
  15253. }
  15254. const isDelete = this.match(89);
  15255. this.next();
  15256. node.argument = this.parseMaybeUnary(null, true);
  15257. this.checkExpressionErrors(refExpressionErrors, true);
  15258. if (this.state.strict && isDelete) {
  15259. const arg = node.argument;
  15260. if (arg.type === "Identifier") {
  15261. this.raise(Errors.StrictDelete, node);
  15262. } else if (this.hasPropertyAsPrivateName(arg)) {
  15263. this.raise(Errors.DeletePrivateField, node);
  15264. }
  15265. }
  15266. if (!update) {
  15267. if (!sawUnary) {
  15268. this.checkExponentialAfterUnary(node);
  15269. }
  15270. return this.finishNode(node, "UnaryExpression");
  15271. }
  15272. }
  15273. const expr = this.parseUpdate(node, update, refExpressionErrors);
  15274. if (isAwait) {
  15275. const {
  15276. type
  15277. } = this.state;
  15278. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  15279. if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {
  15280. this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc);
  15281. return this.parseAwait(startLoc);
  15282. }
  15283. }
  15284. return expr;
  15285. }
  15286. parseUpdate(node, update, refExpressionErrors) {
  15287. if (update) {
  15288. const updateExpressionNode = node;
  15289. this.checkLVal(updateExpressionNode.argument, this.finishNode(updateExpressionNode, "UpdateExpression"));
  15290. return node;
  15291. }
  15292. const startLoc = this.state.startLoc;
  15293. let expr = this.parseExprSubscripts(refExpressionErrors);
  15294. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  15295. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  15296. const node = this.startNodeAt(startLoc);
  15297. node.operator = this.state.value;
  15298. node.prefix = false;
  15299. node.argument = expr;
  15300. this.next();
  15301. this.checkLVal(expr, expr = this.finishNode(node, "UpdateExpression"));
  15302. }
  15303. return expr;
  15304. }
  15305. parseExprSubscripts(refExpressionErrors) {
  15306. const startLoc = this.state.startLoc;
  15307. const potentialArrowAt = this.state.potentialArrowAt;
  15308. const expr = this.parseExprAtom(refExpressionErrors);
  15309. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  15310. return expr;
  15311. }
  15312. return this.parseSubscripts(expr, startLoc);
  15313. }
  15314. parseSubscripts(base, startLoc, noCalls) {
  15315. const state = {
  15316. optionalChainMember: false,
  15317. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  15318. stop: false
  15319. };
  15320. do {
  15321. base = this.parseSubscript(base, startLoc, noCalls, state);
  15322. state.maybeAsyncArrow = false;
  15323. } while (!state.stop);
  15324. return base;
  15325. }
  15326. parseSubscript(base, startLoc, noCalls, state) {
  15327. const {
  15328. type
  15329. } = this.state;
  15330. if (!noCalls && type === 15) {
  15331. return this.parseBind(base, startLoc, noCalls, state);
  15332. } else if (tokenIsTemplate(type)) {
  15333. return this.parseTaggedTemplateExpression(base, startLoc, state);
  15334. }
  15335. let optional = false;
  15336. if (type === 18) {
  15337. if (noCalls) {
  15338. this.raise(Errors.OptionalChainingNoNew, this.state.startLoc);
  15339. if (this.lookaheadCharCode() === 40) {
  15340. return this.stopParseSubscript(base, state);
  15341. }
  15342. }
  15343. state.optionalChainMember = optional = true;
  15344. this.next();
  15345. }
  15346. if (!noCalls && this.match(10)) {
  15347. return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional);
  15348. } else {
  15349. const computed = this.eat(0);
  15350. if (computed || optional || this.eat(16)) {
  15351. return this.parseMember(base, startLoc, state, computed, optional);
  15352. } else {
  15353. return this.stopParseSubscript(base, state);
  15354. }
  15355. }
  15356. }
  15357. stopParseSubscript(base, state) {
  15358. state.stop = true;
  15359. return base;
  15360. }
  15361. parseMember(base, startLoc, state, computed, optional) {
  15362. const node = this.startNodeAt(startLoc);
  15363. node.object = base;
  15364. node.computed = computed;
  15365. if (computed) {
  15366. node.property = this.parseExpression();
  15367. this.expect(3);
  15368. } else if (this.match(139)) {
  15369. if (base.type === "Super") {
  15370. this.raise(Errors.SuperPrivateField, startLoc);
  15371. }
  15372. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  15373. node.property = this.parsePrivateName();
  15374. } else {
  15375. node.property = this.parseIdentifier(true);
  15376. }
  15377. if (state.optionalChainMember) {
  15378. node.optional = optional;
  15379. return this.finishNode(node, "OptionalMemberExpression");
  15380. } else {
  15381. return this.finishNode(node, "MemberExpression");
  15382. }
  15383. }
  15384. parseBind(base, startLoc, noCalls, state) {
  15385. const node = this.startNodeAt(startLoc);
  15386. node.object = base;
  15387. this.next();
  15388. node.callee = this.parseNoCallExpr();
  15389. state.stop = true;
  15390. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls);
  15391. }
  15392. parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) {
  15393. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  15394. let refExpressionErrors = null;
  15395. this.state.maybeInArrowParameters = true;
  15396. this.next();
  15397. const node = this.startNodeAt(startLoc);
  15398. node.callee = base;
  15399. const {
  15400. maybeAsyncArrow,
  15401. optionalChainMember
  15402. } = state;
  15403. if (maybeAsyncArrow) {
  15404. this.expressionScope.enter(newAsyncArrowScope());
  15405. refExpressionErrors = new ExpressionErrors();
  15406. }
  15407. if (optionalChainMember) {
  15408. node.optional = optional;
  15409. }
  15410. if (optional) {
  15411. node.arguments = this.parseCallExpressionArguments();
  15412. } else {
  15413. node.arguments = this.parseCallExpressionArguments(base.type !== "Super", node, refExpressionErrors);
  15414. }
  15415. let finishedNode = this.finishCallExpression(node, optionalChainMember);
  15416. if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  15417. state.stop = true;
  15418. this.checkDestructuringPrivate(refExpressionErrors);
  15419. this.expressionScope.validateAsPattern();
  15420. this.expressionScope.exit();
  15421. finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode);
  15422. } else {
  15423. if (maybeAsyncArrow) {
  15424. this.checkExpressionErrors(refExpressionErrors, true);
  15425. this.expressionScope.exit();
  15426. }
  15427. this.toReferencedArguments(finishedNode);
  15428. }
  15429. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  15430. return finishedNode;
  15431. }
  15432. toReferencedArguments(node, isParenthesizedExpr) {
  15433. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  15434. }
  15435. parseTaggedTemplateExpression(base, startLoc, state) {
  15436. const node = this.startNodeAt(startLoc);
  15437. node.tag = base;
  15438. node.quasi = this.parseTemplate(true);
  15439. if (state.optionalChainMember) {
  15440. this.raise(Errors.OptionalChainingNoTemplate, startLoc);
  15441. }
  15442. return this.finishNode(node, "TaggedTemplateExpression");
  15443. }
  15444. atPossibleAsyncArrow(base) {
  15445. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.offsetToSourcePos(base.start) === this.state.potentialArrowAt;
  15446. }
  15447. finishCallExpression(node, optional) {
  15448. if (node.callee.type === "Import") {
  15449. if (node.arguments.length === 0 || node.arguments.length > 2) {
  15450. this.raise(Errors.ImportCallArity, node);
  15451. } else {
  15452. for (const arg of node.arguments) {
  15453. if (arg.type === "SpreadElement") {
  15454. this.raise(Errors.ImportCallSpreadArgument, arg);
  15455. }
  15456. }
  15457. }
  15458. }
  15459. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  15460. }
  15461. parseCallExpressionArguments(allowPlaceholder, nodeForExtra, refExpressionErrors) {
  15462. const elts = [];
  15463. let first = true;
  15464. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  15465. this.state.inFSharpPipelineDirectBody = false;
  15466. while (!this.eat(11)) {
  15467. if (first) {
  15468. first = false;
  15469. } else {
  15470. this.expect(12);
  15471. if (this.match(11)) {
  15472. if (nodeForExtra) {
  15473. this.addTrailingCommaExtraToNode(nodeForExtra);
  15474. }
  15475. this.next();
  15476. break;
  15477. }
  15478. }
  15479. elts.push(this.parseExprListItem(11, false, refExpressionErrors, allowPlaceholder));
  15480. }
  15481. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  15482. return elts;
  15483. }
  15484. shouldParseAsyncArrow() {
  15485. return this.match(19) && !this.canInsertSemicolon();
  15486. }
  15487. parseAsyncArrowFromCallExpression(node, call) {
  15488. var _call$extra;
  15489. this.resetPreviousNodeTrailingComments(call);
  15490. this.expect(19);
  15491. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc);
  15492. if (call.innerComments) {
  15493. setInnerComments(node, call.innerComments);
  15494. }
  15495. if (call.callee.trailingComments) {
  15496. setInnerComments(node, call.callee.trailingComments);
  15497. }
  15498. return node;
  15499. }
  15500. parseNoCallExpr() {
  15501. const startLoc = this.state.startLoc;
  15502. return this.parseSubscripts(this.parseExprAtom(), startLoc, true);
  15503. }
  15504. parseExprAtom(refExpressionErrors) {
  15505. let node;
  15506. let decorators = null;
  15507. const {
  15508. type
  15509. } = this.state;
  15510. switch (type) {
  15511. case 79:
  15512. return this.parseSuper();
  15513. case 83:
  15514. node = this.startNode();
  15515. this.next();
  15516. if (this.match(16)) {
  15517. return this.parseImportMetaPropertyOrPhaseCall(node);
  15518. }
  15519. if (this.match(10)) {
  15520. if (this.optionFlags & 512) {
  15521. return this.parseImportCall(node);
  15522. } else {
  15523. return this.finishNode(node, "Import");
  15524. }
  15525. } else {
  15526. this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc);
  15527. return this.finishNode(node, "Import");
  15528. }
  15529. case 78:
  15530. node = this.startNode();
  15531. this.next();
  15532. return this.finishNode(node, "ThisExpression");
  15533. case 90:
  15534. {
  15535. return this.parseDo(this.startNode(), false);
  15536. }
  15537. case 56:
  15538. case 31:
  15539. {
  15540. this.readRegexp();
  15541. return this.parseRegExpLiteral(this.state.value);
  15542. }
  15543. case 135:
  15544. return this.parseNumericLiteral(this.state.value);
  15545. case 136:
  15546. return this.parseBigIntLiteral(this.state.value);
  15547. case 134:
  15548. return this.parseStringLiteral(this.state.value);
  15549. case 84:
  15550. return this.parseNullLiteral();
  15551. case 85:
  15552. return this.parseBooleanLiteral(true);
  15553. case 86:
  15554. return this.parseBooleanLiteral(false);
  15555. case 10:
  15556. {
  15557. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  15558. return this.parseParenAndDistinguishExpression(canBeArrow);
  15559. }
  15560. case 0:
  15561. {
  15562. return this.parseArrayLike(3, false, refExpressionErrors);
  15563. }
  15564. case 5:
  15565. {
  15566. return this.parseObjectLike(8, false, false, refExpressionErrors);
  15567. }
  15568. case 68:
  15569. return this.parseFunctionOrFunctionSent();
  15570. case 26:
  15571. decorators = this.parseDecorators();
  15572. case 80:
  15573. return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false);
  15574. case 77:
  15575. return this.parseNewOrNewTarget();
  15576. case 25:
  15577. case 24:
  15578. return this.parseTemplate(false);
  15579. case 15:
  15580. {
  15581. node = this.startNode();
  15582. this.next();
  15583. node.object = null;
  15584. const callee = node.callee = this.parseNoCallExpr();
  15585. if (callee.type === "MemberExpression") {
  15586. return this.finishNode(node, "BindExpression");
  15587. } else {
  15588. throw this.raise(Errors.UnsupportedBind, callee);
  15589. }
  15590. }
  15591. case 139:
  15592. {
  15593. this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, {
  15594. identifierName: this.state.value
  15595. });
  15596. return this.parsePrivateName();
  15597. }
  15598. case 33:
  15599. {
  15600. return this.parseTopicReferenceThenEqualsSign(54, "%");
  15601. }
  15602. case 32:
  15603. {
  15604. return this.parseTopicReferenceThenEqualsSign(44, "^");
  15605. }
  15606. case 37:
  15607. case 38:
  15608. {
  15609. return this.parseTopicReference("hack");
  15610. }
  15611. case 44:
  15612. case 54:
  15613. case 27:
  15614. {
  15615. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  15616. if (pipeProposal) {
  15617. return this.parseTopicReference(pipeProposal);
  15618. }
  15619. throw this.unexpected();
  15620. }
  15621. case 47:
  15622. {
  15623. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  15624. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  15625. throw this.expectOnePlugin(["jsx", "flow", "typescript"]);
  15626. }
  15627. throw this.unexpected();
  15628. }
  15629. default:
  15630. if (type === 137) {
  15631. return this.parseDecimalLiteral(this.state.value);
  15632. } else if (type === 2 || type === 1) {
  15633. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, true);
  15634. } else if (type === 6 || type === 7) {
  15635. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  15636. }
  15637. if (tokenIsIdentifier(type)) {
  15638. if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) {
  15639. return this.parseModuleExpression();
  15640. }
  15641. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  15642. const containsEsc = this.state.containsEsc;
  15643. const id = this.parseIdentifier();
  15644. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  15645. const {
  15646. type
  15647. } = this.state;
  15648. if (type === 68) {
  15649. this.resetPreviousNodeTrailingComments(id);
  15650. this.next();
  15651. return this.parseAsyncFunctionExpression(this.startNodeAtNode(id));
  15652. } else if (tokenIsIdentifier(type)) {
  15653. if (canBeArrow && this.lookaheadCharCode() === 61) {
  15654. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  15655. } else {
  15656. return id;
  15657. }
  15658. } else if (type === 90) {
  15659. this.resetPreviousNodeTrailingComments(id);
  15660. return this.parseDo(this.startNodeAtNode(id), true);
  15661. }
  15662. }
  15663. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  15664. this.next();
  15665. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  15666. }
  15667. return id;
  15668. } else {
  15669. throw this.unexpected();
  15670. }
  15671. }
  15672. }
  15673. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  15674. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  15675. if (pipeProposal) {
  15676. this.state.type = topicTokenType;
  15677. this.state.value = topicTokenValue;
  15678. this.state.pos--;
  15679. this.state.end--;
  15680. this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1);
  15681. return this.parseTopicReference(pipeProposal);
  15682. }
  15683. throw this.unexpected();
  15684. }
  15685. parseTopicReference(pipeProposal) {
  15686. const node = this.startNode();
  15687. const startLoc = this.state.startLoc;
  15688. const tokenType = this.state.type;
  15689. this.next();
  15690. return this.finishTopicReference(node, startLoc, pipeProposal, tokenType);
  15691. }
  15692. finishTopicReference(node, startLoc, pipeProposal, tokenType) {
  15693. if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) {
  15694. if (pipeProposal === "hack") {
  15695. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  15696. this.raise(Errors.PipeTopicUnbound, startLoc);
  15697. }
  15698. this.registerTopicReference();
  15699. return this.finishNode(node, "TopicReference");
  15700. } else {
  15701. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  15702. this.raise(Errors.PrimaryTopicNotAllowed, startLoc);
  15703. }
  15704. this.registerTopicReference();
  15705. return this.finishNode(node, "PipelinePrimaryTopicReference");
  15706. }
  15707. } else {
  15708. throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, {
  15709. token: tokenLabelName(tokenType)
  15710. });
  15711. }
  15712. }
  15713. testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) {
  15714. switch (pipeProposal) {
  15715. case "hack":
  15716. {
  15717. return this.hasPlugin(["pipelineOperator", {
  15718. topicToken: tokenLabelName(tokenType)
  15719. }]);
  15720. }
  15721. case "smart":
  15722. return tokenType === 27;
  15723. default:
  15724. throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc);
  15725. }
  15726. }
  15727. parseAsyncArrowUnaryFunction(node) {
  15728. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  15729. const params = [this.parseIdentifier()];
  15730. this.prodParam.exit();
  15731. if (this.hasPrecedingLineBreak()) {
  15732. this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition());
  15733. }
  15734. this.expect(19);
  15735. return this.parseArrowExpression(node, params, true);
  15736. }
  15737. parseDo(node, isAsync) {
  15738. this.expectPlugin("doExpressions");
  15739. if (isAsync) {
  15740. this.expectPlugin("asyncDoExpressions");
  15741. }
  15742. node.async = isAsync;
  15743. this.next();
  15744. const oldLabels = this.state.labels;
  15745. this.state.labels = [];
  15746. if (isAsync) {
  15747. this.prodParam.enter(2);
  15748. node.body = this.parseBlock();
  15749. this.prodParam.exit();
  15750. } else {
  15751. node.body = this.parseBlock();
  15752. }
  15753. this.state.labels = oldLabels;
  15754. return this.finishNode(node, "DoExpression");
  15755. }
  15756. parseSuper() {
  15757. const node = this.startNode();
  15758. this.next();
  15759. if (this.match(10) && !this.scope.allowDirectSuper) {
  15760. if (!(this.optionFlags & 16)) {
  15761. this.raise(Errors.SuperNotAllowed, node);
  15762. }
  15763. } else if (!this.scope.allowSuper) {
  15764. if (!(this.optionFlags & 16)) {
  15765. this.raise(Errors.UnexpectedSuper, node);
  15766. }
  15767. }
  15768. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  15769. this.raise(Errors.UnsupportedSuper, node);
  15770. }
  15771. return this.finishNode(node, "Super");
  15772. }
  15773. parsePrivateName() {
  15774. const node = this.startNode();
  15775. const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1));
  15776. const name = this.state.value;
  15777. this.next();
  15778. node.id = this.createIdentifier(id, name);
  15779. return this.finishNode(node, "PrivateName");
  15780. }
  15781. parseFunctionOrFunctionSent() {
  15782. const node = this.startNode();
  15783. this.next();
  15784. if (this.prodParam.hasYield && this.match(16)) {
  15785. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  15786. this.next();
  15787. if (this.match(103)) {
  15788. this.expectPlugin("functionSent");
  15789. } else if (!this.hasPlugin("functionSent")) {
  15790. this.unexpected();
  15791. }
  15792. return this.parseMetaProperty(node, meta, "sent");
  15793. }
  15794. return this.parseFunction(node);
  15795. }
  15796. parseMetaProperty(node, meta, propertyName) {
  15797. node.meta = meta;
  15798. const containsEsc = this.state.containsEsc;
  15799. node.property = this.parseIdentifier(true);
  15800. if (node.property.name !== propertyName || containsEsc) {
  15801. this.raise(Errors.UnsupportedMetaProperty, node.property, {
  15802. target: meta.name,
  15803. onlyValidPropertyName: propertyName
  15804. });
  15805. }
  15806. return this.finishNode(node, "MetaProperty");
  15807. }
  15808. parseImportMetaPropertyOrPhaseCall(node) {
  15809. this.next();
  15810. if (this.isContextual(105) || this.isContextual(97)) {
  15811. const isSource = this.isContextual(105);
  15812. this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation");
  15813. this.next();
  15814. node.phase = isSource ? "source" : "defer";
  15815. return this.parseImportCall(node);
  15816. } else {
  15817. const id = this.createIdentifierAt(this.startNodeAtNode(node), "import", this.state.lastTokStartLoc);
  15818. if (this.isContextual(101)) {
  15819. if (!this.inModule) {
  15820. this.raise(Errors.ImportMetaOutsideModule, id);
  15821. }
  15822. this.sawUnambiguousESM = true;
  15823. }
  15824. return this.parseMetaProperty(node, id, "meta");
  15825. }
  15826. }
  15827. parseLiteralAtNode(value, type, node) {
  15828. this.addExtra(node, "rawValue", value);
  15829. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  15830. node.value = value;
  15831. this.next();
  15832. return this.finishNode(node, type);
  15833. }
  15834. parseLiteral(value, type) {
  15835. const node = this.startNode();
  15836. return this.parseLiteralAtNode(value, type, node);
  15837. }
  15838. parseStringLiteral(value) {
  15839. return this.parseLiteral(value, "StringLiteral");
  15840. }
  15841. parseNumericLiteral(value) {
  15842. return this.parseLiteral(value, "NumericLiteral");
  15843. }
  15844. parseBigIntLiteral(value) {
  15845. return this.parseLiteral(value, "BigIntLiteral");
  15846. }
  15847. parseDecimalLiteral(value) {
  15848. return this.parseLiteral(value, "DecimalLiteral");
  15849. }
  15850. parseRegExpLiteral(value) {
  15851. const node = this.startNode();
  15852. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  15853. node.pattern = value.pattern;
  15854. node.flags = value.flags;
  15855. this.next();
  15856. return this.finishNode(node, "RegExpLiteral");
  15857. }
  15858. parseBooleanLiteral(value) {
  15859. const node = this.startNode();
  15860. node.value = value;
  15861. this.next();
  15862. return this.finishNode(node, "BooleanLiteral");
  15863. }
  15864. parseNullLiteral() {
  15865. const node = this.startNode();
  15866. this.next();
  15867. return this.finishNode(node, "NullLiteral");
  15868. }
  15869. parseParenAndDistinguishExpression(canBeArrow) {
  15870. const startLoc = this.state.startLoc;
  15871. let val;
  15872. this.next();
  15873. this.expressionScope.enter(newArrowHeadScope());
  15874. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  15875. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  15876. this.state.maybeInArrowParameters = true;
  15877. this.state.inFSharpPipelineDirectBody = false;
  15878. const innerStartLoc = this.state.startLoc;
  15879. const exprList = [];
  15880. const refExpressionErrors = new ExpressionErrors();
  15881. let first = true;
  15882. let spreadStartLoc;
  15883. let optionalCommaStartLoc;
  15884. while (!this.match(11)) {
  15885. if (first) {
  15886. first = false;
  15887. } else {
  15888. this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc);
  15889. if (this.match(11)) {
  15890. optionalCommaStartLoc = this.state.startLoc;
  15891. break;
  15892. }
  15893. }
  15894. if (this.match(21)) {
  15895. const spreadNodeStartLoc = this.state.startLoc;
  15896. spreadStartLoc = this.state.startLoc;
  15897. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc));
  15898. if (!this.checkCommaAfterRest(41)) {
  15899. break;
  15900. }
  15901. } else {
  15902. exprList.push(this.parseMaybeAssignAllowInOrVoidPattern(11, refExpressionErrors, this.parseParenItem));
  15903. }
  15904. }
  15905. const innerEndLoc = this.state.lastTokEndLoc;
  15906. this.expect(11);
  15907. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  15908. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  15909. let arrowNode = this.startNodeAt(startLoc);
  15910. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  15911. this.checkDestructuringPrivate(refExpressionErrors);
  15912. this.expressionScope.validateAsPattern();
  15913. this.expressionScope.exit();
  15914. this.parseArrowExpression(arrowNode, exprList, false);
  15915. return arrowNode;
  15916. }
  15917. this.expressionScope.exit();
  15918. if (!exprList.length) {
  15919. this.unexpected(this.state.lastTokStartLoc);
  15920. }
  15921. if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc);
  15922. if (spreadStartLoc) this.unexpected(spreadStartLoc);
  15923. this.checkExpressionErrors(refExpressionErrors, true);
  15924. this.toReferencedListDeep(exprList, true);
  15925. if (exprList.length > 1) {
  15926. val = this.startNodeAt(innerStartLoc);
  15927. val.expressions = exprList;
  15928. this.finishNode(val, "SequenceExpression");
  15929. this.resetEndLocation(val, innerEndLoc);
  15930. } else {
  15931. val = exprList[0];
  15932. }
  15933. return this.wrapParenthesis(startLoc, val);
  15934. }
  15935. wrapParenthesis(startLoc, expression) {
  15936. if (!(this.optionFlags & 1024)) {
  15937. this.addExtra(expression, "parenthesized", true);
  15938. this.addExtra(expression, "parenStart", startLoc.index);
  15939. this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index);
  15940. return expression;
  15941. }
  15942. const parenExpression = this.startNodeAt(startLoc);
  15943. parenExpression.expression = expression;
  15944. return this.finishNode(parenExpression, "ParenthesizedExpression");
  15945. }
  15946. shouldParseArrow(params) {
  15947. return !this.canInsertSemicolon();
  15948. }
  15949. parseArrow(node) {
  15950. if (this.eat(19)) {
  15951. return node;
  15952. }
  15953. }
  15954. parseParenItem(node, startLoc) {
  15955. return node;
  15956. }
  15957. parseNewOrNewTarget() {
  15958. const node = this.startNode();
  15959. this.next();
  15960. if (this.match(16)) {
  15961. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  15962. this.next();
  15963. const metaProp = this.parseMetaProperty(node, meta, "target");
  15964. if (!this.scope.allowNewTarget) {
  15965. this.raise(Errors.UnexpectedNewTarget, metaProp);
  15966. }
  15967. return metaProp;
  15968. }
  15969. return this.parseNew(node);
  15970. }
  15971. parseNew(node) {
  15972. this.parseNewCallee(node);
  15973. if (this.eat(10)) {
  15974. const args = this.parseExprList(11);
  15975. this.toReferencedList(args);
  15976. node.arguments = args;
  15977. } else {
  15978. node.arguments = [];
  15979. }
  15980. return this.finishNode(node, "NewExpression");
  15981. }
  15982. parseNewCallee(node) {
  15983. const isImport = this.match(83);
  15984. const callee = this.parseNoCallExpr();
  15985. node.callee = callee;
  15986. if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) {
  15987. this.raise(Errors.ImportCallNotNewExpression, callee);
  15988. }
  15989. }
  15990. parseTemplateElement(isTagged) {
  15991. const {
  15992. start,
  15993. startLoc,
  15994. end,
  15995. value
  15996. } = this.state;
  15997. const elemStart = start + 1;
  15998. const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1));
  15999. if (value === null) {
  16000. if (!isTagged) {
  16001. this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1));
  16002. }
  16003. }
  16004. const isTail = this.match(24);
  16005. const endOffset = isTail ? -1 : -2;
  16006. const elemEnd = end + endOffset;
  16007. elem.value = {
  16008. raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"),
  16009. cooked: value === null ? null : value.slice(1, endOffset)
  16010. };
  16011. elem.tail = isTail;
  16012. this.next();
  16013. const finishedNode = this.finishNode(elem, "TemplateElement");
  16014. this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset));
  16015. return finishedNode;
  16016. }
  16017. parseTemplate(isTagged) {
  16018. const node = this.startNode();
  16019. let curElt = this.parseTemplateElement(isTagged);
  16020. const quasis = [curElt];
  16021. const substitutions = [];
  16022. while (!curElt.tail) {
  16023. substitutions.push(this.parseTemplateSubstitution());
  16024. this.readTemplateContinuation();
  16025. quasis.push(curElt = this.parseTemplateElement(isTagged));
  16026. }
  16027. node.expressions = substitutions;
  16028. node.quasis = quasis;
  16029. return this.finishNode(node, "TemplateLiteral");
  16030. }
  16031. parseTemplateSubstitution() {
  16032. return this.parseExpression();
  16033. }
  16034. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  16035. if (isRecord) {
  16036. this.expectPlugin("recordAndTuple");
  16037. }
  16038. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  16039. this.state.inFSharpPipelineDirectBody = false;
  16040. let sawProto = false;
  16041. let first = true;
  16042. const node = this.startNode();
  16043. node.properties = [];
  16044. this.next();
  16045. while (!this.match(close)) {
  16046. if (first) {
  16047. first = false;
  16048. } else {
  16049. this.expect(12);
  16050. if (this.match(close)) {
  16051. this.addTrailingCommaExtraToNode(node);
  16052. break;
  16053. }
  16054. }
  16055. let prop;
  16056. if (isPattern) {
  16057. prop = this.parseBindingProperty();
  16058. } else {
  16059. prop = this.parsePropertyDefinition(refExpressionErrors);
  16060. sawProto = this.checkProto(prop, isRecord, sawProto, refExpressionErrors);
  16061. }
  16062. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  16063. this.raise(Errors.InvalidRecordProperty, prop);
  16064. }
  16065. if (prop.shorthand) {
  16066. this.addExtra(prop, "shorthand", true);
  16067. }
  16068. node.properties.push(prop);
  16069. }
  16070. this.next();
  16071. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  16072. let type = "ObjectExpression";
  16073. if (isPattern) {
  16074. type = "ObjectPattern";
  16075. } else if (isRecord) {
  16076. type = "RecordExpression";
  16077. }
  16078. return this.finishNode(node, type);
  16079. }
  16080. addTrailingCommaExtraToNode(node) {
  16081. this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index);
  16082. this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false);
  16083. }
  16084. maybeAsyncOrAccessorProp(prop) {
  16085. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55));
  16086. }
  16087. parsePropertyDefinition(refExpressionErrors) {
  16088. let decorators = [];
  16089. if (this.match(26)) {
  16090. if (this.hasPlugin("decorators")) {
  16091. this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc);
  16092. }
  16093. while (this.match(26)) {
  16094. decorators.push(this.parseDecorator());
  16095. }
  16096. }
  16097. const prop = this.startNode();
  16098. let isAsync = false;
  16099. let isAccessor = false;
  16100. let startLoc;
  16101. if (this.match(21)) {
  16102. if (decorators.length) this.unexpected();
  16103. return this.parseSpread();
  16104. }
  16105. if (decorators.length) {
  16106. prop.decorators = decorators;
  16107. decorators = [];
  16108. }
  16109. prop.method = false;
  16110. if (refExpressionErrors) {
  16111. startLoc = this.state.startLoc;
  16112. }
  16113. let isGenerator = this.eat(55);
  16114. this.parsePropertyNamePrefixOperator(prop);
  16115. const containsEsc = this.state.containsEsc;
  16116. this.parsePropertyName(prop, refExpressionErrors);
  16117. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  16118. const {
  16119. key
  16120. } = prop;
  16121. const keyName = key.name;
  16122. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  16123. isAsync = true;
  16124. this.resetPreviousNodeTrailingComments(key);
  16125. isGenerator = this.eat(55);
  16126. this.parsePropertyName(prop);
  16127. }
  16128. if (keyName === "get" || keyName === "set") {
  16129. isAccessor = true;
  16130. this.resetPreviousNodeTrailingComments(key);
  16131. prop.kind = keyName;
  16132. if (this.match(55)) {
  16133. isGenerator = true;
  16134. this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), {
  16135. kind: keyName
  16136. });
  16137. this.next();
  16138. }
  16139. this.parsePropertyName(prop);
  16140. }
  16141. }
  16142. return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  16143. }
  16144. getGetterSetterExpectedParamCount(method) {
  16145. return method.kind === "get" ? 0 : 1;
  16146. }
  16147. getObjectOrClassMethodParams(method) {
  16148. return method.params;
  16149. }
  16150. checkGetterSetterParams(method) {
  16151. var _params;
  16152. const paramCount = this.getGetterSetterExpectedParamCount(method);
  16153. const params = this.getObjectOrClassMethodParams(method);
  16154. if (params.length !== paramCount) {
  16155. this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method);
  16156. }
  16157. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  16158. this.raise(Errors.BadSetterRestParameter, method);
  16159. }
  16160. }
  16161. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  16162. if (isAccessor) {
  16163. const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  16164. this.checkGetterSetterParams(finishedProp);
  16165. return finishedProp;
  16166. }
  16167. if (isAsync || isGenerator || this.match(10)) {
  16168. if (isPattern) this.unexpected();
  16169. prop.kind = "method";
  16170. prop.method = true;
  16171. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  16172. }
  16173. }
  16174. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  16175. prop.shorthand = false;
  16176. if (this.eat(14)) {
  16177. prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowInOrVoidPattern(8, refExpressionErrors);
  16178. return this.finishObjectProperty(prop);
  16179. }
  16180. if (!prop.computed && prop.key.type === "Identifier") {
  16181. this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false);
  16182. if (isPattern) {
  16183. prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key));
  16184. } else if (this.match(29)) {
  16185. const shorthandAssignLoc = this.state.startLoc;
  16186. if (refExpressionErrors != null) {
  16187. if (refExpressionErrors.shorthandAssignLoc === null) {
  16188. refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc;
  16189. }
  16190. } else {
  16191. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  16192. }
  16193. prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key));
  16194. } else {
  16195. prop.value = this.cloneIdentifier(prop.key);
  16196. }
  16197. prop.shorthand = true;
  16198. return this.finishObjectProperty(prop);
  16199. }
  16200. }
  16201. finishObjectProperty(node) {
  16202. return this.finishNode(node, "ObjectProperty");
  16203. }
  16204. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  16205. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  16206. if (!node) this.unexpected();
  16207. return node;
  16208. }
  16209. parsePropertyName(prop, refExpressionErrors) {
  16210. if (this.eat(0)) {
  16211. prop.computed = true;
  16212. prop.key = this.parseMaybeAssignAllowIn();
  16213. this.expect(3);
  16214. } else {
  16215. const {
  16216. type,
  16217. value
  16218. } = this.state;
  16219. let key;
  16220. if (tokenIsKeywordOrIdentifier(type)) {
  16221. key = this.parseIdentifier(true);
  16222. } else {
  16223. switch (type) {
  16224. case 135:
  16225. key = this.parseNumericLiteral(value);
  16226. break;
  16227. case 134:
  16228. key = this.parseStringLiteral(value);
  16229. break;
  16230. case 136:
  16231. key = this.parseBigIntLiteral(value);
  16232. break;
  16233. case 139:
  16234. {
  16235. const privateKeyLoc = this.state.startLoc;
  16236. if (refExpressionErrors != null) {
  16237. if (refExpressionErrors.privateKeyLoc === null) {
  16238. refExpressionErrors.privateKeyLoc = privateKeyLoc;
  16239. }
  16240. } else {
  16241. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  16242. }
  16243. key = this.parsePrivateName();
  16244. break;
  16245. }
  16246. default:
  16247. if (type === 137) {
  16248. key = this.parseDecimalLiteral(value);
  16249. break;
  16250. }
  16251. this.unexpected();
  16252. }
  16253. }
  16254. prop.key = key;
  16255. if (type !== 139) {
  16256. prop.computed = false;
  16257. }
  16258. }
  16259. }
  16260. initFunction(node, isAsync) {
  16261. node.id = null;
  16262. node.generator = false;
  16263. node.async = isAsync;
  16264. }
  16265. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  16266. this.initFunction(node, isAsync);
  16267. node.generator = isGenerator;
  16268. this.scope.enter(514 | 16 | (inClassScope ? 576 : 0) | (allowDirectSuper ? 32 : 0));
  16269. this.prodParam.enter(functionFlags(isAsync, node.generator));
  16270. this.parseFunctionParams(node, isConstructor);
  16271. const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);
  16272. this.prodParam.exit();
  16273. this.scope.exit();
  16274. return finishedNode;
  16275. }
  16276. parseArrayLike(close, isTuple, refExpressionErrors) {
  16277. if (isTuple) {
  16278. this.expectPlugin("recordAndTuple");
  16279. }
  16280. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  16281. this.state.inFSharpPipelineDirectBody = false;
  16282. const node = this.startNode();
  16283. this.next();
  16284. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  16285. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  16286. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  16287. }
  16288. parseArrowExpression(node, params, isAsync, trailingCommaLoc) {
  16289. this.scope.enter(514 | 4);
  16290. let flags = functionFlags(isAsync, false);
  16291. if (!this.match(5) && this.prodParam.hasIn) {
  16292. flags |= 8;
  16293. }
  16294. this.prodParam.enter(flags);
  16295. this.initFunction(node, isAsync);
  16296. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  16297. if (params) {
  16298. this.state.maybeInArrowParameters = true;
  16299. this.setArrowFunctionParameters(node, params, trailingCommaLoc);
  16300. }
  16301. this.state.maybeInArrowParameters = false;
  16302. this.parseFunctionBody(node, true);
  16303. this.prodParam.exit();
  16304. this.scope.exit();
  16305. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  16306. return this.finishNode(node, "ArrowFunctionExpression");
  16307. }
  16308. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  16309. this.toAssignableList(params, trailingCommaLoc, false);
  16310. node.params = params;
  16311. }
  16312. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  16313. this.parseFunctionBody(node, false, isMethod);
  16314. return this.finishNode(node, type);
  16315. }
  16316. parseFunctionBody(node, allowExpression, isMethod = false) {
  16317. const isExpression = allowExpression && !this.match(5);
  16318. this.expressionScope.enter(newExpressionScope());
  16319. if (isExpression) {
  16320. node.body = this.parseMaybeAssign();
  16321. this.checkParams(node, false, allowExpression, false);
  16322. } else {
  16323. const oldStrict = this.state.strict;
  16324. const oldLabels = this.state.labels;
  16325. this.state.labels = [];
  16326. this.prodParam.enter(this.prodParam.currentFlags() | 4);
  16327. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  16328. const nonSimple = !this.isSimpleParamList(node.params);
  16329. if (hasStrictModeDirective && nonSimple) {
  16330. this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node);
  16331. }
  16332. const strictModeChanged = !oldStrict && this.state.strict;
  16333. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  16334. if (this.state.strict && node.id) {
  16335. this.checkIdentifier(node.id, 65, strictModeChanged);
  16336. }
  16337. });
  16338. this.prodParam.exit();
  16339. this.state.labels = oldLabels;
  16340. }
  16341. this.expressionScope.exit();
  16342. }
  16343. isSimpleParameter(node) {
  16344. return node.type === "Identifier";
  16345. }
  16346. isSimpleParamList(params) {
  16347. for (let i = 0, len = params.length; i < len; i++) {
  16348. if (!this.isSimpleParameter(params[i])) return false;
  16349. }
  16350. return true;
  16351. }
  16352. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  16353. const checkClashes = !allowDuplicates && new Set();
  16354. const formalParameters = {
  16355. type: "FormalParameters"
  16356. };
  16357. for (const param of node.params) {
  16358. this.checkLVal(param, formalParameters, 5, checkClashes, strictModeChanged);
  16359. }
  16360. }
  16361. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  16362. const elts = [];
  16363. let first = true;
  16364. while (!this.eat(close)) {
  16365. if (first) {
  16366. first = false;
  16367. } else {
  16368. this.expect(12);
  16369. if (this.match(close)) {
  16370. if (nodeForExtra) {
  16371. this.addTrailingCommaExtraToNode(nodeForExtra);
  16372. }
  16373. this.next();
  16374. break;
  16375. }
  16376. }
  16377. elts.push(this.parseExprListItem(close, allowEmpty, refExpressionErrors));
  16378. }
  16379. return elts;
  16380. }
  16381. parseExprListItem(close, allowEmpty, refExpressionErrors, allowPlaceholder) {
  16382. let elt;
  16383. if (this.match(12)) {
  16384. if (!allowEmpty) {
  16385. this.raise(Errors.UnexpectedToken, this.state.curPosition(), {
  16386. unexpected: ","
  16387. });
  16388. }
  16389. elt = null;
  16390. } else if (this.match(21)) {
  16391. const spreadNodeStartLoc = this.state.startLoc;
  16392. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc);
  16393. } else if (this.match(17)) {
  16394. this.expectPlugin("partialApplication");
  16395. if (!allowPlaceholder) {
  16396. this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc);
  16397. }
  16398. const node = this.startNode();
  16399. this.next();
  16400. elt = this.finishNode(node, "ArgumentPlaceholder");
  16401. } else {
  16402. elt = this.parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, this.parseParenItem);
  16403. }
  16404. return elt;
  16405. }
  16406. parseIdentifier(liberal) {
  16407. const node = this.startNode();
  16408. const name = this.parseIdentifierName(liberal);
  16409. return this.createIdentifier(node, name);
  16410. }
  16411. createIdentifier(node, name) {
  16412. node.name = name;
  16413. node.loc.identifierName = name;
  16414. return this.finishNode(node, "Identifier");
  16415. }
  16416. createIdentifierAt(node, name, endLoc) {
  16417. node.name = name;
  16418. node.loc.identifierName = name;
  16419. return this.finishNodeAt(node, "Identifier", endLoc);
  16420. }
  16421. parseIdentifierName(liberal) {
  16422. let name;
  16423. const {
  16424. startLoc,
  16425. type
  16426. } = this.state;
  16427. if (tokenIsKeywordOrIdentifier(type)) {
  16428. name = this.state.value;
  16429. } else {
  16430. this.unexpected();
  16431. }
  16432. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  16433. if (liberal) {
  16434. if (tokenIsKeyword) {
  16435. this.replaceToken(132);
  16436. }
  16437. } else {
  16438. this.checkReservedWord(name, startLoc, tokenIsKeyword, false);
  16439. }
  16440. this.next();
  16441. return name;
  16442. }
  16443. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  16444. if (word.length > 10) {
  16445. return;
  16446. }
  16447. if (!canBeReservedWord(word)) {
  16448. return;
  16449. }
  16450. if (checkKeywords && isKeyword(word)) {
  16451. this.raise(Errors.UnexpectedKeyword, startLoc, {
  16452. keyword: word
  16453. });
  16454. return;
  16455. }
  16456. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  16457. if (reservedTest(word, this.inModule)) {
  16458. this.raise(Errors.UnexpectedReservedWord, startLoc, {
  16459. reservedWord: word
  16460. });
  16461. return;
  16462. } else if (word === "yield") {
  16463. if (this.prodParam.hasYield) {
  16464. this.raise(Errors.YieldBindingIdentifier, startLoc);
  16465. return;
  16466. }
  16467. } else if (word === "await") {
  16468. if (this.prodParam.hasAwait) {
  16469. this.raise(Errors.AwaitBindingIdentifier, startLoc);
  16470. return;
  16471. }
  16472. if (this.scope.inStaticBlock) {
  16473. this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc);
  16474. return;
  16475. }
  16476. this.expressionScope.recordAsyncArrowParametersError(startLoc);
  16477. } else if (word === "arguments") {
  16478. if (this.scope.inClassAndNotInNonArrowFunction) {
  16479. this.raise(Errors.ArgumentsInClass, startLoc);
  16480. return;
  16481. }
  16482. }
  16483. }
  16484. recordAwaitIfAllowed() {
  16485. const isAwaitAllowed = this.prodParam.hasAwait;
  16486. if (isAwaitAllowed && !this.scope.inFunction) {
  16487. this.state.hasTopLevelAwait = true;
  16488. }
  16489. return isAwaitAllowed;
  16490. }
  16491. parseAwait(startLoc) {
  16492. const node = this.startNodeAt(startLoc);
  16493. this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node);
  16494. if (this.eat(55)) {
  16495. this.raise(Errors.ObsoleteAwaitStar, node);
  16496. }
  16497. if (!this.scope.inFunction && !(this.optionFlags & 1)) {
  16498. if (this.isAmbiguousPrefixOrIdentifier()) {
  16499. this.ambiguousScriptDifferentAst = true;
  16500. } else {
  16501. this.sawUnambiguousESM = true;
  16502. }
  16503. }
  16504. if (!this.state.soloAwait) {
  16505. node.argument = this.parseMaybeUnary(null, true);
  16506. }
  16507. return this.finishNode(node, "AwaitExpression");
  16508. }
  16509. isAmbiguousPrefixOrIdentifier() {
  16510. if (this.hasPrecedingLineBreak()) return true;
  16511. const {
  16512. type
  16513. } = this.state;
  16514. return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 138 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54;
  16515. }
  16516. parseYield(startLoc) {
  16517. const node = this.startNodeAt(startLoc);
  16518. this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node);
  16519. let delegating = false;
  16520. let argument = null;
  16521. if (!this.hasPrecedingLineBreak()) {
  16522. delegating = this.eat(55);
  16523. switch (this.state.type) {
  16524. case 13:
  16525. case 140:
  16526. case 8:
  16527. case 11:
  16528. case 3:
  16529. case 9:
  16530. case 14:
  16531. case 12:
  16532. if (!delegating) break;
  16533. default:
  16534. argument = this.parseMaybeAssign();
  16535. }
  16536. }
  16537. node.delegate = delegating;
  16538. node.argument = argument;
  16539. return this.finishNode(node, "YieldExpression");
  16540. }
  16541. parseImportCall(node) {
  16542. this.next();
  16543. node.source = this.parseMaybeAssignAllowIn();
  16544. node.options = null;
  16545. if (this.eat(12)) {
  16546. if (!this.match(11)) {
  16547. node.options = this.parseMaybeAssignAllowIn();
  16548. if (this.eat(12)) {
  16549. this.addTrailingCommaExtraToNode(node.options);
  16550. if (!this.match(11)) {
  16551. do {
  16552. this.parseMaybeAssignAllowIn();
  16553. } while (this.eat(12) && !this.match(11));
  16554. this.raise(Errors.ImportCallArity, node);
  16555. }
  16556. }
  16557. } else {
  16558. this.addTrailingCommaExtraToNode(node.source);
  16559. }
  16560. }
  16561. this.expect(11);
  16562. return this.finishNode(node, "ImportExpression");
  16563. }
  16564. checkPipelineAtInfixOperator(left, leftStartLoc) {
  16565. if (this.hasPlugin(["pipelineOperator", {
  16566. proposal: "smart"
  16567. }])) {
  16568. if (left.type === "SequenceExpression") {
  16569. this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc);
  16570. }
  16571. }
  16572. }
  16573. parseSmartPipelineBodyInStyle(childExpr, startLoc) {
  16574. if (this.isSimpleReference(childExpr)) {
  16575. const bodyNode = this.startNodeAt(startLoc);
  16576. bodyNode.callee = childExpr;
  16577. return this.finishNode(bodyNode, "PipelineBareFunction");
  16578. } else {
  16579. const bodyNode = this.startNodeAt(startLoc);
  16580. this.checkSmartPipeTopicBodyEarlyErrors(startLoc);
  16581. bodyNode.expression = childExpr;
  16582. return this.finishNode(bodyNode, "PipelineTopicExpression");
  16583. }
  16584. }
  16585. isSimpleReference(expression) {
  16586. switch (expression.type) {
  16587. case "MemberExpression":
  16588. return !expression.computed && this.isSimpleReference(expression.object);
  16589. case "Identifier":
  16590. return true;
  16591. default:
  16592. return false;
  16593. }
  16594. }
  16595. checkSmartPipeTopicBodyEarlyErrors(startLoc) {
  16596. if (this.match(19)) {
  16597. throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc);
  16598. }
  16599. if (!this.topicReferenceWasUsedInCurrentContext()) {
  16600. this.raise(Errors.PipelineTopicUnused, startLoc);
  16601. }
  16602. }
  16603. withTopicBindingContext(callback) {
  16604. const outerContextTopicState = this.state.topicContext;
  16605. this.state.topicContext = {
  16606. maxNumOfResolvableTopics: 1,
  16607. maxTopicIndex: null
  16608. };
  16609. try {
  16610. return callback();
  16611. } finally {
  16612. this.state.topicContext = outerContextTopicState;
  16613. }
  16614. }
  16615. withSmartMixTopicForbiddingContext(callback) {
  16616. if (this.hasPlugin(["pipelineOperator", {
  16617. proposal: "smart"
  16618. }])) {
  16619. const outerContextTopicState = this.state.topicContext;
  16620. this.state.topicContext = {
  16621. maxNumOfResolvableTopics: 0,
  16622. maxTopicIndex: null
  16623. };
  16624. try {
  16625. return callback();
  16626. } finally {
  16627. this.state.topicContext = outerContextTopicState;
  16628. }
  16629. } else {
  16630. return callback();
  16631. }
  16632. }
  16633. withSoloAwaitPermittingContext(callback) {
  16634. const outerContextSoloAwaitState = this.state.soloAwait;
  16635. this.state.soloAwait = true;
  16636. try {
  16637. return callback();
  16638. } finally {
  16639. this.state.soloAwait = outerContextSoloAwaitState;
  16640. }
  16641. }
  16642. allowInAnd(callback) {
  16643. const flags = this.prodParam.currentFlags();
  16644. const prodParamToSet = 8 & ~flags;
  16645. if (prodParamToSet) {
  16646. this.prodParam.enter(flags | 8);
  16647. try {
  16648. return callback();
  16649. } finally {
  16650. this.prodParam.exit();
  16651. }
  16652. }
  16653. return callback();
  16654. }
  16655. disallowInAnd(callback) {
  16656. const flags = this.prodParam.currentFlags();
  16657. const prodParamToClear = 8 & flags;
  16658. if (prodParamToClear) {
  16659. this.prodParam.enter(flags & -9);
  16660. try {
  16661. return callback();
  16662. } finally {
  16663. this.prodParam.exit();
  16664. }
  16665. }
  16666. return callback();
  16667. }
  16668. registerTopicReference() {
  16669. this.state.topicContext.maxTopicIndex = 0;
  16670. }
  16671. topicReferenceIsAllowedInCurrentContext() {
  16672. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  16673. }
  16674. topicReferenceWasUsedInCurrentContext() {
  16675. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  16676. }
  16677. parseFSharpPipelineBody(prec) {
  16678. const startLoc = this.state.startLoc;
  16679. this.state.potentialArrowAt = this.state.start;
  16680. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  16681. this.state.inFSharpPipelineDirectBody = true;
  16682. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec);
  16683. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  16684. return ret;
  16685. }
  16686. parseModuleExpression() {
  16687. this.expectPlugin("moduleBlocks");
  16688. const node = this.startNode();
  16689. this.next();
  16690. if (!this.match(5)) {
  16691. this.unexpected(null, 5);
  16692. }
  16693. const program = this.startNodeAt(this.state.endLoc);
  16694. this.next();
  16695. const revertScopes = this.initializeScopes(true);
  16696. this.enterInitialScopes();
  16697. try {
  16698. node.body = this.parseProgram(program, 8, "module");
  16699. } finally {
  16700. revertScopes();
  16701. }
  16702. return this.finishNode(node, "ModuleExpression");
  16703. }
  16704. parseVoidPattern(refExpressionErrors) {
  16705. this.expectPlugin("discardBinding");
  16706. const node = this.startNode();
  16707. if (refExpressionErrors != null) {
  16708. refExpressionErrors.voidPatternLoc = this.state.startLoc;
  16709. }
  16710. this.next();
  16711. return this.finishNode(node, "VoidPattern");
  16712. }
  16713. parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, afterLeftParse) {
  16714. if (refExpressionErrors != null && this.match(88)) {
  16715. const nextCode = this.lookaheadCharCode();
  16716. if (nextCode === 44 || nextCode === (close === 3 ? 93 : close === 8 ? 125 : 41) || nextCode === 61) {
  16717. return this.parseMaybeDefault(this.state.startLoc, this.parseVoidPattern(refExpressionErrors));
  16718. }
  16719. }
  16720. return this.parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse);
  16721. }
  16722. parsePropertyNamePrefixOperator(prop) {}
  16723. }
  16724. const loopLabel = {
  16725. kind: 1
  16726. },
  16727. switchLabel = {
  16728. kind: 2
  16729. };
  16730. const loneSurrogate = /[\uD800-\uDFFF]/u;
  16731. const keywordRelationalOperator = /in(?:stanceof)?/y;
  16732. function babel7CompatTokens(tokens, input, startIndex) {
  16733. for (let i = 0; i < tokens.length; i++) {
  16734. const token = tokens[i];
  16735. const {
  16736. type
  16737. } = token;
  16738. if (typeof type === "number") {
  16739. if (type === 139) {
  16740. const {
  16741. loc,
  16742. start,
  16743. value,
  16744. end
  16745. } = token;
  16746. const hashEndPos = start + 1;
  16747. const hashEndLoc = createPositionWithColumnOffset(loc.start, 1);
  16748. tokens.splice(i, 1, new Token({
  16749. type: getExportedToken(27),
  16750. value: "#",
  16751. start: start,
  16752. end: hashEndPos,
  16753. startLoc: loc.start,
  16754. endLoc: hashEndLoc
  16755. }), new Token({
  16756. type: getExportedToken(132),
  16757. value: value,
  16758. start: hashEndPos,
  16759. end: end,
  16760. startLoc: hashEndLoc,
  16761. endLoc: loc.end
  16762. }));
  16763. i++;
  16764. continue;
  16765. }
  16766. if (tokenIsTemplate(type)) {
  16767. const {
  16768. loc,
  16769. start,
  16770. value,
  16771. end
  16772. } = token;
  16773. const backquoteEnd = start + 1;
  16774. const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1);
  16775. let startToken;
  16776. if (input.charCodeAt(start - startIndex) === 96) {
  16777. startToken = new Token({
  16778. type: getExportedToken(22),
  16779. value: "`",
  16780. start: start,
  16781. end: backquoteEnd,
  16782. startLoc: loc.start,
  16783. endLoc: backquoteEndLoc
  16784. });
  16785. } else {
  16786. startToken = new Token({
  16787. type: getExportedToken(8),
  16788. value: "}",
  16789. start: start,
  16790. end: backquoteEnd,
  16791. startLoc: loc.start,
  16792. endLoc: backquoteEndLoc
  16793. });
  16794. }
  16795. let templateValue, templateElementEnd, templateElementEndLoc, endToken;
  16796. if (type === 24) {
  16797. templateElementEnd = end - 1;
  16798. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1);
  16799. templateValue = value === null ? null : value.slice(1, -1);
  16800. endToken = new Token({
  16801. type: getExportedToken(22),
  16802. value: "`",
  16803. start: templateElementEnd,
  16804. end: end,
  16805. startLoc: templateElementEndLoc,
  16806. endLoc: loc.end
  16807. });
  16808. } else {
  16809. templateElementEnd = end - 2;
  16810. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2);
  16811. templateValue = value === null ? null : value.slice(1, -2);
  16812. endToken = new Token({
  16813. type: getExportedToken(23),
  16814. value: "${",
  16815. start: templateElementEnd,
  16816. end: end,
  16817. startLoc: templateElementEndLoc,
  16818. endLoc: loc.end
  16819. });
  16820. }
  16821. tokens.splice(i, 1, startToken, new Token({
  16822. type: getExportedToken(20),
  16823. value: templateValue,
  16824. start: backquoteEnd,
  16825. end: templateElementEnd,
  16826. startLoc: backquoteEndLoc,
  16827. endLoc: templateElementEndLoc
  16828. }), endToken);
  16829. i += 2;
  16830. continue;
  16831. }
  16832. token.type = getExportedToken(type);
  16833. }
  16834. }
  16835. return tokens;
  16836. }
  16837. class StatementParser extends ExpressionParser {
  16838. parseTopLevel(file, program) {
  16839. file.program = this.parseProgram(program, 140, this.options.sourceType === "module" ? "module" : "script");
  16840. file.comments = this.comments;
  16841. if (this.optionFlags & 256) {
  16842. file.tokens = babel7CompatTokens(this.tokens, this.input, this.startIndex);
  16843. }
  16844. return this.finishNode(file, "File");
  16845. }
  16846. parseProgram(program, end, sourceType) {
  16847. program.sourceType = sourceType;
  16848. program.interpreter = this.parseInterpreterDirective();
  16849. this.parseBlockBody(program, true, true, end);
  16850. if (this.inModule) {
  16851. if (!(this.optionFlags & 64) && this.scope.undefinedExports.size > 0) {
  16852. for (const [localName, at] of Array.from(this.scope.undefinedExports)) {
  16853. this.raise(Errors.ModuleExportUndefined, at, {
  16854. localName
  16855. });
  16856. }
  16857. }
  16858. this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait);
  16859. }
  16860. let finishedProgram;
  16861. if (end === 140) {
  16862. finishedProgram = this.finishNode(program, "Program");
  16863. } else {
  16864. finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1));
  16865. }
  16866. return finishedProgram;
  16867. }
  16868. stmtToDirective(stmt) {
  16869. const directive = this.castNodeTo(stmt, "Directive");
  16870. const directiveLiteral = this.castNodeTo(stmt.expression, "DirectiveLiteral");
  16871. const expressionValue = directiveLiteral.value;
  16872. const raw = this.input.slice(this.offsetToSourcePos(directiveLiteral.start), this.offsetToSourcePos(directiveLiteral.end));
  16873. const val = directiveLiteral.value = raw.slice(1, -1);
  16874. this.addExtra(directiveLiteral, "raw", raw);
  16875. this.addExtra(directiveLiteral, "rawValue", val);
  16876. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  16877. directive.value = directiveLiteral;
  16878. delete stmt.expression;
  16879. return directive;
  16880. }
  16881. parseInterpreterDirective() {
  16882. if (!this.match(28)) {
  16883. return null;
  16884. }
  16885. const node = this.startNode();
  16886. node.value = this.state.value;
  16887. this.next();
  16888. return this.finishNode(node, "InterpreterDirective");
  16889. }
  16890. isLet() {
  16891. if (!this.isContextual(100)) {
  16892. return false;
  16893. }
  16894. return this.hasFollowingBindingAtom();
  16895. }
  16896. isUsing() {
  16897. if (!this.isContextual(107)) {
  16898. return false;
  16899. }
  16900. return this.nextTokenIsIdentifierOnSameLine();
  16901. }
  16902. isForUsing() {
  16903. if (!this.isContextual(107)) {
  16904. return false;
  16905. }
  16906. const next = this.nextTokenInLineStart();
  16907. const nextCh = this.codePointAtPos(next);
  16908. if (this.isUnparsedContextual(next, "of")) {
  16909. const nextCharAfterOf = this.lookaheadCharCodeSince(next + 2);
  16910. if (nextCharAfterOf !== 61 && nextCharAfterOf !== 58 && nextCharAfterOf !== 59) {
  16911. return false;
  16912. }
  16913. }
  16914. if (this.chStartsBindingIdentifier(nextCh, next) || this.isUnparsedContextual(next, "void")) {
  16915. return true;
  16916. }
  16917. return false;
  16918. }
  16919. nextTokenIsIdentifierOnSameLine() {
  16920. const next = this.nextTokenInLineStart();
  16921. const nextCh = this.codePointAtPos(next);
  16922. return this.chStartsBindingIdentifier(nextCh, next);
  16923. }
  16924. isAwaitUsing() {
  16925. if (!this.isContextual(96)) {
  16926. return false;
  16927. }
  16928. let next = this.nextTokenInLineStart();
  16929. if (this.isUnparsedContextual(next, "using")) {
  16930. next = this.nextTokenInLineStartSince(next + 5);
  16931. const nextCh = this.codePointAtPos(next);
  16932. if (this.chStartsBindingIdentifier(nextCh, next)) {
  16933. return true;
  16934. }
  16935. }
  16936. return false;
  16937. }
  16938. chStartsBindingIdentifier(ch, pos) {
  16939. if (isIdentifierStart(ch)) {
  16940. keywordRelationalOperator.lastIndex = pos;
  16941. if (keywordRelationalOperator.test(this.input)) {
  16942. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  16943. if (!isIdentifierChar(endCh) && endCh !== 92) {
  16944. return false;
  16945. }
  16946. }
  16947. return true;
  16948. } else if (ch === 92) {
  16949. return true;
  16950. } else {
  16951. return false;
  16952. }
  16953. }
  16954. chStartsBindingPattern(ch) {
  16955. return ch === 91 || ch === 123;
  16956. }
  16957. hasFollowingBindingAtom() {
  16958. const next = this.nextTokenStart();
  16959. const nextCh = this.codePointAtPos(next);
  16960. return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next);
  16961. }
  16962. hasInLineFollowingBindingIdentifierOrBrace() {
  16963. const next = this.nextTokenInLineStart();
  16964. const nextCh = this.codePointAtPos(next);
  16965. return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next);
  16966. }
  16967. allowsUsing() {
  16968. return (this.scope.inModule || !this.scope.inTopLevel) && !this.scope.inBareCaseStatement;
  16969. }
  16970. parseModuleItem() {
  16971. return this.parseStatementLike(1 | 2 | 4 | 8);
  16972. }
  16973. parseStatementListItem() {
  16974. return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8));
  16975. }
  16976. parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) {
  16977. let flags = 0;
  16978. if (this.options.annexB && !this.state.strict) {
  16979. flags |= 4;
  16980. if (allowLabeledFunction) {
  16981. flags |= 8;
  16982. }
  16983. }
  16984. return this.parseStatementLike(flags);
  16985. }
  16986. parseStatement() {
  16987. return this.parseStatementLike(0);
  16988. }
  16989. parseStatementLike(flags) {
  16990. let decorators = null;
  16991. if (this.match(26)) {
  16992. decorators = this.parseDecorators(true);
  16993. }
  16994. return this.parseStatementContent(flags, decorators);
  16995. }
  16996. parseStatementContent(flags, decorators) {
  16997. const startType = this.state.type;
  16998. const node = this.startNode();
  16999. const allowDeclaration = !!(flags & 2);
  17000. const allowFunctionDeclaration = !!(flags & 4);
  17001. const topLevel = flags & 1;
  17002. switch (startType) {
  17003. case 60:
  17004. return this.parseBreakContinueStatement(node, true);
  17005. case 63:
  17006. return this.parseBreakContinueStatement(node, false);
  17007. case 64:
  17008. return this.parseDebuggerStatement(node);
  17009. case 90:
  17010. return this.parseDoWhileStatement(node);
  17011. case 91:
  17012. return this.parseForStatement(node);
  17013. case 68:
  17014. if (this.lookaheadCharCode() === 46) break;
  17015. if (!allowFunctionDeclaration) {
  17016. this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc);
  17017. }
  17018. return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration);
  17019. case 80:
  17020. if (!allowDeclaration) this.unexpected();
  17021. return this.parseClass(this.maybeTakeDecorators(decorators, node), true);
  17022. case 69:
  17023. return this.parseIfStatement(node);
  17024. case 70:
  17025. return this.parseReturnStatement(node);
  17026. case 71:
  17027. return this.parseSwitchStatement(node);
  17028. case 72:
  17029. return this.parseThrowStatement(node);
  17030. case 73:
  17031. return this.parseTryStatement(node);
  17032. case 96:
  17033. if (this.isAwaitUsing()) {
  17034. if (!this.allowsUsing()) {
  17035. this.raise(Errors.UnexpectedUsingDeclaration, node);
  17036. } else if (!allowDeclaration) {
  17037. this.raise(Errors.UnexpectedLexicalDeclaration, node);
  17038. } else if (!this.recordAwaitIfAllowed()) {
  17039. this.raise(Errors.AwaitUsingNotInAsyncContext, node);
  17040. }
  17041. this.next();
  17042. return this.parseVarStatement(node, "await using");
  17043. }
  17044. break;
  17045. case 107:
  17046. if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) {
  17047. break;
  17048. }
  17049. if (!this.allowsUsing()) {
  17050. this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc);
  17051. } else if (!allowDeclaration) {
  17052. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  17053. }
  17054. return this.parseVarStatement(node, "using");
  17055. case 100:
  17056. {
  17057. if (this.state.containsEsc) {
  17058. break;
  17059. }
  17060. const next = this.nextTokenStart();
  17061. const nextCh = this.codePointAtPos(next);
  17062. if (nextCh !== 91) {
  17063. if (!allowDeclaration && this.hasFollowingLineBreak()) break;
  17064. if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) {
  17065. break;
  17066. }
  17067. }
  17068. }
  17069. case 75:
  17070. {
  17071. if (!allowDeclaration) {
  17072. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  17073. }
  17074. }
  17075. case 74:
  17076. {
  17077. const kind = this.state.value;
  17078. return this.parseVarStatement(node, kind);
  17079. }
  17080. case 92:
  17081. return this.parseWhileStatement(node);
  17082. case 76:
  17083. return this.parseWithStatement(node);
  17084. case 5:
  17085. return this.parseBlock();
  17086. case 13:
  17087. return this.parseEmptyStatement(node);
  17088. case 83:
  17089. {
  17090. const nextTokenCharCode = this.lookaheadCharCode();
  17091. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  17092. break;
  17093. }
  17094. }
  17095. case 82:
  17096. {
  17097. if (!(this.optionFlags & 8) && !topLevel) {
  17098. this.raise(Errors.UnexpectedImportExport, this.state.startLoc);
  17099. }
  17100. this.next();
  17101. let result;
  17102. if (startType === 83) {
  17103. result = this.parseImport(node);
  17104. } else {
  17105. result = this.parseExport(node, decorators);
  17106. }
  17107. this.assertModuleNodeAllowed(result);
  17108. return result;
  17109. }
  17110. default:
  17111. {
  17112. if (this.isAsyncFunction()) {
  17113. if (!allowDeclaration) {
  17114. this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc);
  17115. }
  17116. this.next();
  17117. return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration);
  17118. }
  17119. }
  17120. }
  17121. const maybeName = this.state.value;
  17122. const expr = this.parseExpression();
  17123. if (tokenIsIdentifier(startType) && expr.type === "Identifier" && this.eat(14)) {
  17124. return this.parseLabeledStatement(node, maybeName, expr, flags);
  17125. } else {
  17126. return this.parseExpressionStatement(node, expr, decorators);
  17127. }
  17128. }
  17129. assertModuleNodeAllowed(node) {
  17130. if (!(this.optionFlags & 8) && !this.inModule) {
  17131. this.raise(Errors.ImportOutsideModule, node);
  17132. }
  17133. }
  17134. decoratorsEnabledBeforeExport() {
  17135. if (this.hasPlugin("decorators-legacy")) return true;
  17136. return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false;
  17137. }
  17138. maybeTakeDecorators(maybeDecorators, classNode, exportNode) {
  17139. if (maybeDecorators) {
  17140. var _classNode$decorators;
  17141. if ((_classNode$decorators = classNode.decorators) != null && _classNode$decorators.length) {
  17142. if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") {
  17143. this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]);
  17144. }
  17145. classNode.decorators.unshift(...maybeDecorators);
  17146. } else {
  17147. classNode.decorators = maybeDecorators;
  17148. }
  17149. this.resetStartLocationFromNode(classNode, maybeDecorators[0]);
  17150. if (exportNode) this.resetStartLocationFromNode(exportNode, classNode);
  17151. }
  17152. return classNode;
  17153. }
  17154. canHaveLeadingDecorator() {
  17155. return this.match(80);
  17156. }
  17157. parseDecorators(allowExport) {
  17158. const decorators = [];
  17159. do {
  17160. decorators.push(this.parseDecorator());
  17161. } while (this.match(26));
  17162. if (this.match(82)) {
  17163. if (!allowExport) {
  17164. this.unexpected();
  17165. }
  17166. if (!this.decoratorsEnabledBeforeExport()) {
  17167. this.raise(Errors.DecoratorExportClass, this.state.startLoc);
  17168. }
  17169. } else if (!this.canHaveLeadingDecorator()) {
  17170. throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc);
  17171. }
  17172. return decorators;
  17173. }
  17174. parseDecorator() {
  17175. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  17176. const node = this.startNode();
  17177. this.next();
  17178. if (this.hasPlugin("decorators")) {
  17179. const startLoc = this.state.startLoc;
  17180. let expr;
  17181. if (this.match(10)) {
  17182. const startLoc = this.state.startLoc;
  17183. this.next();
  17184. expr = this.parseExpression();
  17185. this.expect(11);
  17186. expr = this.wrapParenthesis(startLoc, expr);
  17187. const paramsStartLoc = this.state.startLoc;
  17188. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  17189. if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) {
  17190. this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc);
  17191. }
  17192. } else {
  17193. expr = this.parseIdentifier(false);
  17194. while (this.eat(16)) {
  17195. const node = this.startNodeAt(startLoc);
  17196. node.object = expr;
  17197. if (this.match(139)) {
  17198. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  17199. node.property = this.parsePrivateName();
  17200. } else {
  17201. node.property = this.parseIdentifier(true);
  17202. }
  17203. node.computed = false;
  17204. expr = this.finishNode(node, "MemberExpression");
  17205. }
  17206. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  17207. }
  17208. } else {
  17209. node.expression = this.parseExprSubscripts();
  17210. }
  17211. return this.finishNode(node, "Decorator");
  17212. }
  17213. parseMaybeDecoratorArguments(expr, startLoc) {
  17214. if (this.eat(10)) {
  17215. const node = this.startNodeAt(startLoc);
  17216. node.callee = expr;
  17217. node.arguments = this.parseCallExpressionArguments();
  17218. this.toReferencedList(node.arguments);
  17219. return this.finishNode(node, "CallExpression");
  17220. }
  17221. return expr;
  17222. }
  17223. parseBreakContinueStatement(node, isBreak) {
  17224. this.next();
  17225. if (this.isLineTerminator()) {
  17226. node.label = null;
  17227. } else {
  17228. node.label = this.parseIdentifier();
  17229. this.semicolon();
  17230. }
  17231. this.verifyBreakContinue(node, isBreak);
  17232. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  17233. }
  17234. verifyBreakContinue(node, isBreak) {
  17235. let i;
  17236. for (i = 0; i < this.state.labels.length; ++i) {
  17237. const lab = this.state.labels[i];
  17238. if (node.label == null || lab.name === node.label.name) {
  17239. if (lab.kind != null && (isBreak || lab.kind === 1)) {
  17240. break;
  17241. }
  17242. if (node.label && isBreak) break;
  17243. }
  17244. }
  17245. if (i === this.state.labels.length) {
  17246. const type = isBreak ? "BreakStatement" : "ContinueStatement";
  17247. this.raise(Errors.IllegalBreakContinue, node, {
  17248. type
  17249. });
  17250. }
  17251. }
  17252. parseDebuggerStatement(node) {
  17253. this.next();
  17254. this.semicolon();
  17255. return this.finishNode(node, "DebuggerStatement");
  17256. }
  17257. parseHeaderExpression() {
  17258. this.expect(10);
  17259. const val = this.parseExpression();
  17260. this.expect(11);
  17261. return val;
  17262. }
  17263. parseDoWhileStatement(node) {
  17264. this.next();
  17265. this.state.labels.push(loopLabel);
  17266. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17267. this.state.labels.pop();
  17268. this.expect(92);
  17269. node.test = this.parseHeaderExpression();
  17270. this.eat(13);
  17271. return this.finishNode(node, "DoWhileStatement");
  17272. }
  17273. parseForStatement(node) {
  17274. this.next();
  17275. this.state.labels.push(loopLabel);
  17276. let awaitAt = null;
  17277. if (this.isContextual(96) && this.recordAwaitIfAllowed()) {
  17278. awaitAt = this.state.startLoc;
  17279. this.next();
  17280. }
  17281. this.scope.enter(0);
  17282. this.expect(10);
  17283. if (this.match(13)) {
  17284. if (awaitAt !== null) {
  17285. this.unexpected(awaitAt);
  17286. }
  17287. return this.parseFor(node, null);
  17288. }
  17289. const startsWithLet = this.isContextual(100);
  17290. {
  17291. const startsWithAwaitUsing = this.isAwaitUsing();
  17292. const starsWithUsingDeclaration = startsWithAwaitUsing || this.isForUsing();
  17293. const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration;
  17294. if (this.match(74) || this.match(75) || isLetOrUsing) {
  17295. const initNode = this.startNode();
  17296. let kind;
  17297. if (startsWithAwaitUsing) {
  17298. kind = "await using";
  17299. if (!this.recordAwaitIfAllowed()) {
  17300. this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc);
  17301. }
  17302. this.next();
  17303. } else {
  17304. kind = this.state.value;
  17305. }
  17306. this.next();
  17307. this.parseVar(initNode, true, kind);
  17308. const init = this.finishNode(initNode, "VariableDeclaration");
  17309. const isForIn = this.match(58);
  17310. if (isForIn && starsWithUsingDeclaration) {
  17311. this.raise(Errors.ForInUsing, init);
  17312. }
  17313. if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) {
  17314. return this.parseForIn(node, init, awaitAt);
  17315. }
  17316. if (awaitAt !== null) {
  17317. this.unexpected(awaitAt);
  17318. }
  17319. return this.parseFor(node, init);
  17320. }
  17321. }
  17322. const startsWithAsync = this.isContextual(95);
  17323. const refExpressionErrors = new ExpressionErrors();
  17324. const init = this.parseExpression(true, refExpressionErrors);
  17325. const isForOf = this.isContextual(102);
  17326. if (isForOf) {
  17327. if (startsWithLet) {
  17328. this.raise(Errors.ForOfLet, init);
  17329. }
  17330. if (awaitAt === null && startsWithAsync && init.type === "Identifier") {
  17331. this.raise(Errors.ForOfAsync, init);
  17332. }
  17333. }
  17334. if (isForOf || this.match(58)) {
  17335. this.checkDestructuringPrivate(refExpressionErrors);
  17336. this.toAssignable(init, true);
  17337. const type = isForOf ? "ForOfStatement" : "ForInStatement";
  17338. this.checkLVal(init, {
  17339. type
  17340. });
  17341. return this.parseForIn(node, init, awaitAt);
  17342. } else {
  17343. this.checkExpressionErrors(refExpressionErrors, true);
  17344. }
  17345. if (awaitAt !== null) {
  17346. this.unexpected(awaitAt);
  17347. }
  17348. return this.parseFor(node, init);
  17349. }
  17350. parseFunctionStatement(node, isAsync, isHangingDeclaration) {
  17351. this.next();
  17352. return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0));
  17353. }
  17354. parseIfStatement(node) {
  17355. this.next();
  17356. node.test = this.parseHeaderExpression();
  17357. node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration();
  17358. node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null;
  17359. return this.finishNode(node, "IfStatement");
  17360. }
  17361. parseReturnStatement(node) {
  17362. if (!this.prodParam.hasReturn) {
  17363. this.raise(Errors.IllegalReturn, this.state.startLoc);
  17364. }
  17365. this.next();
  17366. if (this.isLineTerminator()) {
  17367. node.argument = null;
  17368. } else {
  17369. node.argument = this.parseExpression();
  17370. this.semicolon();
  17371. }
  17372. return this.finishNode(node, "ReturnStatement");
  17373. }
  17374. parseSwitchStatement(node) {
  17375. this.next();
  17376. node.discriminant = this.parseHeaderExpression();
  17377. const cases = node.cases = [];
  17378. this.expect(5);
  17379. this.state.labels.push(switchLabel);
  17380. this.scope.enter(256);
  17381. let cur;
  17382. for (let sawDefault; !this.match(8);) {
  17383. if (this.match(61) || this.match(65)) {
  17384. const isCase = this.match(61);
  17385. if (cur) this.finishNode(cur, "SwitchCase");
  17386. cases.push(cur = this.startNode());
  17387. cur.consequent = [];
  17388. this.next();
  17389. if (isCase) {
  17390. cur.test = this.parseExpression();
  17391. } else {
  17392. if (sawDefault) {
  17393. this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc);
  17394. }
  17395. sawDefault = true;
  17396. cur.test = null;
  17397. }
  17398. this.expect(14);
  17399. } else {
  17400. if (cur) {
  17401. cur.consequent.push(this.parseStatementListItem());
  17402. } else {
  17403. this.unexpected();
  17404. }
  17405. }
  17406. }
  17407. this.scope.exit();
  17408. if (cur) this.finishNode(cur, "SwitchCase");
  17409. this.next();
  17410. this.state.labels.pop();
  17411. return this.finishNode(node, "SwitchStatement");
  17412. }
  17413. parseThrowStatement(node) {
  17414. this.next();
  17415. if (this.hasPrecedingLineBreak()) {
  17416. this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc);
  17417. }
  17418. node.argument = this.parseExpression();
  17419. this.semicolon();
  17420. return this.finishNode(node, "ThrowStatement");
  17421. }
  17422. parseCatchClauseParam() {
  17423. const param = this.parseBindingAtom();
  17424. this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0);
  17425. this.checkLVal(param, {
  17426. type: "CatchClause"
  17427. }, 9);
  17428. return param;
  17429. }
  17430. parseTryStatement(node) {
  17431. this.next();
  17432. node.block = this.parseBlock();
  17433. node.handler = null;
  17434. if (this.match(62)) {
  17435. const clause = this.startNode();
  17436. this.next();
  17437. if (this.match(10)) {
  17438. this.expect(10);
  17439. clause.param = this.parseCatchClauseParam();
  17440. this.expect(11);
  17441. } else {
  17442. clause.param = null;
  17443. this.scope.enter(0);
  17444. }
  17445. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  17446. this.scope.exit();
  17447. node.handler = this.finishNode(clause, "CatchClause");
  17448. }
  17449. node.finalizer = this.eat(67) ? this.parseBlock() : null;
  17450. if (!node.handler && !node.finalizer) {
  17451. this.raise(Errors.NoCatchOrFinally, node);
  17452. }
  17453. return this.finishNode(node, "TryStatement");
  17454. }
  17455. parseVarStatement(node, kind, allowMissingInitializer = false) {
  17456. this.next();
  17457. this.parseVar(node, false, kind, allowMissingInitializer);
  17458. this.semicolon();
  17459. return this.finishNode(node, "VariableDeclaration");
  17460. }
  17461. parseWhileStatement(node) {
  17462. this.next();
  17463. node.test = this.parseHeaderExpression();
  17464. this.state.labels.push(loopLabel);
  17465. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17466. this.state.labels.pop();
  17467. return this.finishNode(node, "WhileStatement");
  17468. }
  17469. parseWithStatement(node) {
  17470. if (this.state.strict) {
  17471. this.raise(Errors.StrictWith, this.state.startLoc);
  17472. }
  17473. this.next();
  17474. node.object = this.parseHeaderExpression();
  17475. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17476. return this.finishNode(node, "WithStatement");
  17477. }
  17478. parseEmptyStatement(node) {
  17479. this.next();
  17480. return this.finishNode(node, "EmptyStatement");
  17481. }
  17482. parseLabeledStatement(node, maybeName, expr, flags) {
  17483. for (const label of this.state.labels) {
  17484. if (label.name === maybeName) {
  17485. this.raise(Errors.LabelRedeclaration, expr, {
  17486. labelName: maybeName
  17487. });
  17488. }
  17489. }
  17490. const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null;
  17491. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  17492. const label = this.state.labels[i];
  17493. if (label.statementStart === node.start) {
  17494. label.statementStart = this.sourceToOffsetPos(this.state.start);
  17495. label.kind = kind;
  17496. } else {
  17497. break;
  17498. }
  17499. }
  17500. this.state.labels.push({
  17501. name: maybeName,
  17502. kind: kind,
  17503. statementStart: this.sourceToOffsetPos(this.state.start)
  17504. });
  17505. node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement();
  17506. this.state.labels.pop();
  17507. node.label = expr;
  17508. return this.finishNode(node, "LabeledStatement");
  17509. }
  17510. parseExpressionStatement(node, expr, decorators) {
  17511. node.expression = expr;
  17512. this.semicolon();
  17513. return this.finishNode(node, "ExpressionStatement");
  17514. }
  17515. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  17516. const node = this.startNode();
  17517. if (allowDirectives) {
  17518. this.state.strictErrors.clear();
  17519. }
  17520. this.expect(5);
  17521. if (createNewLexicalScope) {
  17522. this.scope.enter(0);
  17523. }
  17524. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  17525. if (createNewLexicalScope) {
  17526. this.scope.exit();
  17527. }
  17528. return this.finishNode(node, "BlockStatement");
  17529. }
  17530. isValidDirective(stmt) {
  17531. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  17532. }
  17533. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  17534. const body = node.body = [];
  17535. const directives = node.directives = [];
  17536. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  17537. }
  17538. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  17539. const oldStrict = this.state.strict;
  17540. let hasStrictModeDirective = false;
  17541. let parsedNonDirective = false;
  17542. while (!this.match(end)) {
  17543. const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem();
  17544. if (directives && !parsedNonDirective) {
  17545. if (this.isValidDirective(stmt)) {
  17546. const directive = this.stmtToDirective(stmt);
  17547. directives.push(directive);
  17548. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  17549. hasStrictModeDirective = true;
  17550. this.setStrict(true);
  17551. }
  17552. continue;
  17553. }
  17554. parsedNonDirective = true;
  17555. this.state.strictErrors.clear();
  17556. }
  17557. body.push(stmt);
  17558. }
  17559. afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective);
  17560. if (!oldStrict) {
  17561. this.setStrict(false);
  17562. }
  17563. this.next();
  17564. }
  17565. parseFor(node, init) {
  17566. node.init = init;
  17567. this.semicolon(false);
  17568. node.test = this.match(13) ? null : this.parseExpression();
  17569. this.semicolon(false);
  17570. node.update = this.match(11) ? null : this.parseExpression();
  17571. this.expect(11);
  17572. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17573. this.scope.exit();
  17574. this.state.labels.pop();
  17575. return this.finishNode(node, "ForStatement");
  17576. }
  17577. parseForIn(node, init, awaitAt) {
  17578. const isForIn = this.match(58);
  17579. this.next();
  17580. if (isForIn) {
  17581. if (awaitAt !== null) this.unexpected(awaitAt);
  17582. } else {
  17583. node.await = awaitAt !== null;
  17584. }
  17585. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  17586. this.raise(Errors.ForInOfLoopInitializer, init, {
  17587. type: isForIn ? "ForInStatement" : "ForOfStatement"
  17588. });
  17589. }
  17590. if (init.type === "AssignmentPattern") {
  17591. this.raise(Errors.InvalidLhs, init, {
  17592. ancestor: {
  17593. type: "ForStatement"
  17594. }
  17595. });
  17596. }
  17597. node.left = init;
  17598. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  17599. this.expect(11);
  17600. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17601. this.scope.exit();
  17602. this.state.labels.pop();
  17603. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  17604. }
  17605. parseVar(node, isFor, kind, allowMissingInitializer = false) {
  17606. const declarations = node.declarations = [];
  17607. node.kind = kind;
  17608. for (;;) {
  17609. const decl = this.startNode();
  17610. this.parseVarId(decl, kind);
  17611. decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  17612. if (decl.init === null && !allowMissingInitializer) {
  17613. if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) {
  17614. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  17615. kind: "destructuring"
  17616. });
  17617. } else if ((kind === "const" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) {
  17618. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  17619. kind
  17620. });
  17621. }
  17622. }
  17623. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  17624. if (!this.eat(12)) break;
  17625. }
  17626. return node;
  17627. }
  17628. parseVarId(decl, kind) {
  17629. const id = this.parseBindingAtom();
  17630. if (kind === "using" || kind === "await using") {
  17631. if (id.type === "ArrayPattern" || id.type === "ObjectPattern") {
  17632. this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start);
  17633. }
  17634. } else {
  17635. if (id.type === "VoidPattern") {
  17636. this.raise(Errors.UnexpectedVoidPattern, id.loc.start);
  17637. }
  17638. }
  17639. this.checkLVal(id, {
  17640. type: "VariableDeclarator"
  17641. }, kind === "var" ? 5 : 8201);
  17642. decl.id = id;
  17643. }
  17644. parseAsyncFunctionExpression(node) {
  17645. return this.parseFunction(node, 8);
  17646. }
  17647. parseFunction(node, flags = 0) {
  17648. const hangingDeclaration = flags & 2;
  17649. const isDeclaration = !!(flags & 1);
  17650. const requireId = isDeclaration && !(flags & 4);
  17651. const isAsync = !!(flags & 8);
  17652. this.initFunction(node, isAsync);
  17653. if (this.match(55)) {
  17654. if (hangingDeclaration) {
  17655. this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc);
  17656. }
  17657. this.next();
  17658. node.generator = true;
  17659. }
  17660. if (isDeclaration) {
  17661. node.id = this.parseFunctionId(requireId);
  17662. }
  17663. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  17664. this.state.maybeInArrowParameters = false;
  17665. this.scope.enter(514);
  17666. this.prodParam.enter(functionFlags(isAsync, node.generator));
  17667. if (!isDeclaration) {
  17668. node.id = this.parseFunctionId();
  17669. }
  17670. this.parseFunctionParams(node, false);
  17671. this.withSmartMixTopicForbiddingContext(() => {
  17672. this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression");
  17673. });
  17674. this.prodParam.exit();
  17675. this.scope.exit();
  17676. if (isDeclaration && !hangingDeclaration) {
  17677. this.registerFunctionStatementId(node);
  17678. }
  17679. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  17680. return node;
  17681. }
  17682. parseFunctionId(requireId) {
  17683. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  17684. }
  17685. parseFunctionParams(node, isConstructor) {
  17686. this.expect(10);
  17687. this.expressionScope.enter(newParameterDeclarationScope());
  17688. node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0));
  17689. this.expressionScope.exit();
  17690. }
  17691. registerFunctionStatementId(node) {
  17692. if (!node.id) return;
  17693. this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start);
  17694. }
  17695. parseClass(node, isStatement, optionalId) {
  17696. this.next();
  17697. const oldStrict = this.state.strict;
  17698. this.state.strict = true;
  17699. this.parseClassId(node, isStatement, optionalId);
  17700. this.parseClassSuper(node);
  17701. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  17702. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  17703. }
  17704. isClassProperty() {
  17705. return this.match(29) || this.match(13) || this.match(8);
  17706. }
  17707. isClassMethod() {
  17708. return this.match(10);
  17709. }
  17710. nameIsConstructor(key) {
  17711. return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor";
  17712. }
  17713. isNonstaticConstructor(method) {
  17714. return !method.computed && !method.static && this.nameIsConstructor(method.key);
  17715. }
  17716. parseClassBody(hadSuperClass, oldStrict) {
  17717. this.classScope.enter();
  17718. const state = {
  17719. hadConstructor: false,
  17720. hadSuperClass
  17721. };
  17722. let decorators = [];
  17723. const classBody = this.startNode();
  17724. classBody.body = [];
  17725. this.expect(5);
  17726. this.withSmartMixTopicForbiddingContext(() => {
  17727. while (!this.match(8)) {
  17728. if (this.eat(13)) {
  17729. if (decorators.length > 0) {
  17730. throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc);
  17731. }
  17732. continue;
  17733. }
  17734. if (this.match(26)) {
  17735. decorators.push(this.parseDecorator());
  17736. continue;
  17737. }
  17738. const member = this.startNode();
  17739. if (decorators.length) {
  17740. member.decorators = decorators;
  17741. this.resetStartLocationFromNode(member, decorators[0]);
  17742. decorators = [];
  17743. }
  17744. this.parseClassMember(classBody, member, state);
  17745. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  17746. this.raise(Errors.DecoratorConstructor, member);
  17747. }
  17748. }
  17749. });
  17750. this.state.strict = oldStrict;
  17751. this.next();
  17752. if (decorators.length) {
  17753. throw this.raise(Errors.TrailingDecorator, this.state.startLoc);
  17754. }
  17755. this.classScope.exit();
  17756. return this.finishNode(classBody, "ClassBody");
  17757. }
  17758. parseClassMemberFromModifier(classBody, member) {
  17759. const key = this.parseIdentifier(true);
  17760. if (this.isClassMethod()) {
  17761. const method = member;
  17762. method.kind = "method";
  17763. method.computed = false;
  17764. method.key = key;
  17765. method.static = false;
  17766. this.pushClassMethod(classBody, method, false, false, false, false);
  17767. return true;
  17768. } else if (this.isClassProperty()) {
  17769. const prop = member;
  17770. prop.computed = false;
  17771. prop.key = key;
  17772. prop.static = false;
  17773. classBody.body.push(this.parseClassProperty(prop));
  17774. return true;
  17775. }
  17776. this.resetPreviousNodeTrailingComments(key);
  17777. return false;
  17778. }
  17779. parseClassMember(classBody, member, state) {
  17780. const isStatic = this.isContextual(106);
  17781. if (isStatic) {
  17782. if (this.parseClassMemberFromModifier(classBody, member)) {
  17783. return;
  17784. }
  17785. if (this.eat(5)) {
  17786. this.parseClassStaticBlock(classBody, member);
  17787. return;
  17788. }
  17789. }
  17790. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  17791. }
  17792. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  17793. const publicMethod = member;
  17794. const privateMethod = member;
  17795. const publicProp = member;
  17796. const privateProp = member;
  17797. const accessorProp = member;
  17798. const method = publicMethod;
  17799. const publicMember = publicMethod;
  17800. member.static = isStatic;
  17801. this.parsePropertyNamePrefixOperator(member);
  17802. if (this.eat(55)) {
  17803. method.kind = "method";
  17804. const isPrivateName = this.match(139);
  17805. this.parseClassElementName(method);
  17806. this.parsePostMemberNameModifiers(method);
  17807. if (isPrivateName) {
  17808. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  17809. return;
  17810. }
  17811. if (this.isNonstaticConstructor(publicMethod)) {
  17812. this.raise(Errors.ConstructorIsGenerator, publicMethod.key);
  17813. }
  17814. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  17815. return;
  17816. }
  17817. const isContextual = !this.state.containsEsc && tokenIsIdentifier(this.state.type);
  17818. const key = this.parseClassElementName(member);
  17819. const maybeContextualKw = isContextual ? key.name : null;
  17820. const isPrivate = this.isPrivateName(key);
  17821. const maybeQuestionTokenStartLoc = this.state.startLoc;
  17822. this.parsePostMemberNameModifiers(publicMember);
  17823. if (this.isClassMethod()) {
  17824. method.kind = "method";
  17825. if (isPrivate) {
  17826. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  17827. return;
  17828. }
  17829. const isConstructor = this.isNonstaticConstructor(publicMethod);
  17830. let allowsDirectSuper = false;
  17831. if (isConstructor) {
  17832. publicMethod.kind = "constructor";
  17833. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  17834. this.raise(Errors.DuplicateConstructor, key);
  17835. }
  17836. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  17837. this.raise(Errors.OverrideOnConstructor, key);
  17838. }
  17839. state.hadConstructor = true;
  17840. allowsDirectSuper = state.hadSuperClass;
  17841. }
  17842. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  17843. } else if (this.isClassProperty()) {
  17844. if (isPrivate) {
  17845. this.pushClassPrivateProperty(classBody, privateProp);
  17846. } else {
  17847. this.pushClassProperty(classBody, publicProp);
  17848. }
  17849. } else if (maybeContextualKw === "async" && !this.isLineTerminator()) {
  17850. this.resetPreviousNodeTrailingComments(key);
  17851. const isGenerator = this.eat(55);
  17852. if (publicMember.optional) {
  17853. this.unexpected(maybeQuestionTokenStartLoc);
  17854. }
  17855. method.kind = "method";
  17856. const isPrivate = this.match(139);
  17857. this.parseClassElementName(method);
  17858. this.parsePostMemberNameModifiers(publicMember);
  17859. if (isPrivate) {
  17860. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  17861. } else {
  17862. if (this.isNonstaticConstructor(publicMethod)) {
  17863. this.raise(Errors.ConstructorIsAsync, publicMethod.key);
  17864. }
  17865. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  17866. }
  17867. } else if ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) {
  17868. this.resetPreviousNodeTrailingComments(key);
  17869. method.kind = maybeContextualKw;
  17870. const isPrivate = this.match(139);
  17871. this.parseClassElementName(publicMethod);
  17872. if (isPrivate) {
  17873. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  17874. } else {
  17875. if (this.isNonstaticConstructor(publicMethod)) {
  17876. this.raise(Errors.ConstructorIsAccessor, publicMethod.key);
  17877. }
  17878. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  17879. }
  17880. this.checkGetterSetterParams(publicMethod);
  17881. } else if (maybeContextualKw === "accessor" && !this.isLineTerminator()) {
  17882. this.expectPlugin("decoratorAutoAccessors");
  17883. this.resetPreviousNodeTrailingComments(key);
  17884. const isPrivate = this.match(139);
  17885. this.parseClassElementName(publicProp);
  17886. this.pushClassAccessorProperty(classBody, accessorProp, isPrivate);
  17887. } else if (this.isLineTerminator()) {
  17888. if (isPrivate) {
  17889. this.pushClassPrivateProperty(classBody, privateProp);
  17890. } else {
  17891. this.pushClassProperty(classBody, publicProp);
  17892. }
  17893. } else {
  17894. this.unexpected();
  17895. }
  17896. }
  17897. parseClassElementName(member) {
  17898. const {
  17899. type,
  17900. value
  17901. } = this.state;
  17902. if ((type === 132 || type === 134) && member.static && value === "prototype") {
  17903. this.raise(Errors.StaticPrototype, this.state.startLoc);
  17904. }
  17905. if (type === 139) {
  17906. if (value === "constructor") {
  17907. this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc);
  17908. }
  17909. const key = this.parsePrivateName();
  17910. member.key = key;
  17911. return key;
  17912. }
  17913. this.parsePropertyName(member);
  17914. return member.key;
  17915. }
  17916. parseClassStaticBlock(classBody, member) {
  17917. var _member$decorators;
  17918. this.scope.enter(576 | 128 | 16);
  17919. const oldLabels = this.state.labels;
  17920. this.state.labels = [];
  17921. this.prodParam.enter(0);
  17922. const body = member.body = [];
  17923. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  17924. this.prodParam.exit();
  17925. this.scope.exit();
  17926. this.state.labels = oldLabels;
  17927. classBody.body.push(this.finishNode(member, "StaticBlock"));
  17928. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  17929. this.raise(Errors.DecoratorStaticBlock, member);
  17930. }
  17931. }
  17932. pushClassProperty(classBody, prop) {
  17933. if (!prop.computed && this.nameIsConstructor(prop.key)) {
  17934. this.raise(Errors.ConstructorClassField, prop.key);
  17935. }
  17936. classBody.body.push(this.parseClassProperty(prop));
  17937. }
  17938. pushClassPrivateProperty(classBody, prop) {
  17939. const node = this.parseClassPrivateProperty(prop);
  17940. classBody.body.push(node);
  17941. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  17942. }
  17943. pushClassAccessorProperty(classBody, prop, isPrivate) {
  17944. if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) {
  17945. this.raise(Errors.ConstructorClassField, prop.key);
  17946. }
  17947. const node = this.parseClassAccessorProperty(prop);
  17948. classBody.body.push(node);
  17949. if (isPrivate) {
  17950. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  17951. }
  17952. }
  17953. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  17954. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  17955. }
  17956. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  17957. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  17958. classBody.body.push(node);
  17959. const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0;
  17960. this.declareClassPrivateMethodInScope(node, kind);
  17961. }
  17962. declareClassPrivateMethodInScope(node, kind) {
  17963. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start);
  17964. }
  17965. parsePostMemberNameModifiers(methodOrProp) {}
  17966. parseClassPrivateProperty(node) {
  17967. this.parseInitializer(node);
  17968. this.semicolon();
  17969. return this.finishNode(node, "ClassPrivateProperty");
  17970. }
  17971. parseClassProperty(node) {
  17972. this.parseInitializer(node);
  17973. this.semicolon();
  17974. return this.finishNode(node, "ClassProperty");
  17975. }
  17976. parseClassAccessorProperty(node) {
  17977. this.parseInitializer(node);
  17978. this.semicolon();
  17979. return this.finishNode(node, "ClassAccessorProperty");
  17980. }
  17981. parseInitializer(node) {
  17982. this.scope.enter(576 | 16);
  17983. this.expressionScope.enter(newExpressionScope());
  17984. this.prodParam.enter(0);
  17985. node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
  17986. this.expressionScope.exit();
  17987. this.prodParam.exit();
  17988. this.scope.exit();
  17989. }
  17990. parseClassId(node, isStatement, optionalId, bindingType = 8331) {
  17991. if (tokenIsIdentifier(this.state.type)) {
  17992. node.id = this.parseIdentifier();
  17993. if (isStatement) {
  17994. this.declareNameFromIdentifier(node.id, bindingType);
  17995. }
  17996. } else {
  17997. if (optionalId || !isStatement) {
  17998. node.id = null;
  17999. } else {
  18000. throw this.raise(Errors.MissingClassName, this.state.startLoc);
  18001. }
  18002. }
  18003. }
  18004. parseClassSuper(node) {
  18005. node.superClass = this.eat(81) ? this.parseExprSubscripts() : null;
  18006. }
  18007. parseExport(node, decorators) {
  18008. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true);
  18009. const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  18010. const parseAfterDefault = !hasDefault || this.eat(12);
  18011. const hasStar = parseAfterDefault && this.eatExportStar(node);
  18012. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  18013. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  18014. const isFromRequired = hasDefault || hasStar;
  18015. if (hasStar && !hasNamespace) {
  18016. if (hasDefault) this.unexpected();
  18017. if (decorators) {
  18018. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18019. }
  18020. this.parseExportFrom(node, true);
  18021. this.sawUnambiguousESM = true;
  18022. return this.finishNode(node, "ExportAllDeclaration");
  18023. }
  18024. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  18025. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) {
  18026. this.unexpected(null, 5);
  18027. }
  18028. if (hasNamespace && parseAfterNamespace) {
  18029. this.unexpected(null, 98);
  18030. }
  18031. let hasDeclaration;
  18032. if (isFromRequired || hasSpecifiers) {
  18033. hasDeclaration = false;
  18034. if (decorators) {
  18035. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18036. }
  18037. this.parseExportFrom(node, isFromRequired);
  18038. } else {
  18039. hasDeclaration = this.maybeParseExportDeclaration(node);
  18040. }
  18041. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  18042. var _node2$declaration;
  18043. const node2 = node;
  18044. this.checkExport(node2, true, false, !!node2.source);
  18045. if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") {
  18046. this.maybeTakeDecorators(decorators, node2.declaration, node2);
  18047. } else if (decorators) {
  18048. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18049. }
  18050. this.sawUnambiguousESM = true;
  18051. return this.finishNode(node2, "ExportNamedDeclaration");
  18052. }
  18053. if (this.eat(65)) {
  18054. const node2 = node;
  18055. const decl = this.parseExportDefaultExpression();
  18056. node2.declaration = decl;
  18057. if (decl.type === "ClassDeclaration") {
  18058. this.maybeTakeDecorators(decorators, decl, node2);
  18059. } else if (decorators) {
  18060. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18061. }
  18062. this.checkExport(node2, true, true);
  18063. this.sawUnambiguousESM = true;
  18064. return this.finishNode(node2, "ExportDefaultDeclaration");
  18065. }
  18066. throw this.unexpected(null, 5);
  18067. }
  18068. eatExportStar(node) {
  18069. return this.eat(55);
  18070. }
  18071. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  18072. if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) {
  18073. this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start);
  18074. const id = maybeDefaultIdentifier || this.parseIdentifier(true);
  18075. const specifier = this.startNodeAtNode(id);
  18076. specifier.exported = id;
  18077. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  18078. return true;
  18079. }
  18080. return false;
  18081. }
  18082. maybeParseExportNamespaceSpecifier(node) {
  18083. if (this.isContextual(93)) {
  18084. var _ref, _ref$specifiers;
  18085. (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.specifiers = [];
  18086. const specifier = this.startNodeAt(this.state.lastTokStartLoc);
  18087. this.next();
  18088. specifier.exported = this.parseModuleExportName();
  18089. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  18090. return true;
  18091. }
  18092. return false;
  18093. }
  18094. maybeParseExportNamedSpecifiers(node) {
  18095. if (this.match(5)) {
  18096. const node2 = node;
  18097. if (!node2.specifiers) node2.specifiers = [];
  18098. const isTypeExport = node2.exportKind === "type";
  18099. node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  18100. node2.source = null;
  18101. if (this.hasPlugin("importAssertions")) {
  18102. node2.assertions = [];
  18103. } else {
  18104. node2.attributes = [];
  18105. }
  18106. node2.declaration = null;
  18107. return true;
  18108. }
  18109. return false;
  18110. }
  18111. maybeParseExportDeclaration(node) {
  18112. if (this.shouldParseExportDeclaration()) {
  18113. node.specifiers = [];
  18114. node.source = null;
  18115. if (this.hasPlugin("importAssertions")) {
  18116. node.assertions = [];
  18117. } else {
  18118. node.attributes = [];
  18119. }
  18120. node.declaration = this.parseExportDeclaration(node);
  18121. return true;
  18122. }
  18123. return false;
  18124. }
  18125. isAsyncFunction() {
  18126. if (!this.isContextual(95)) return false;
  18127. const next = this.nextTokenInLineStart();
  18128. return this.isUnparsedContextual(next, "function");
  18129. }
  18130. parseExportDefaultExpression() {
  18131. const expr = this.startNode();
  18132. if (this.match(68)) {
  18133. this.next();
  18134. return this.parseFunction(expr, 1 | 4);
  18135. } else if (this.isAsyncFunction()) {
  18136. this.next();
  18137. this.next();
  18138. return this.parseFunction(expr, 1 | 4 | 8);
  18139. }
  18140. if (this.match(80)) {
  18141. return this.parseClass(expr, true, true);
  18142. }
  18143. if (this.match(26)) {
  18144. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  18145. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  18146. }
  18147. return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true);
  18148. }
  18149. if (this.match(75) || this.match(74) || this.isLet() || this.isUsing() || this.isAwaitUsing()) {
  18150. throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc);
  18151. }
  18152. const res = this.parseMaybeAssignAllowIn();
  18153. this.semicolon();
  18154. return res;
  18155. }
  18156. parseExportDeclaration(node) {
  18157. if (this.match(80)) {
  18158. const node = this.parseClass(this.startNode(), true, false);
  18159. return node;
  18160. }
  18161. return this.parseStatementListItem();
  18162. }
  18163. isExportDefaultSpecifier() {
  18164. const {
  18165. type
  18166. } = this.state;
  18167. if (tokenIsIdentifier(type)) {
  18168. if (type === 95 && !this.state.containsEsc || type === 100) {
  18169. return false;
  18170. }
  18171. if ((type === 130 || type === 129) && !this.state.containsEsc) {
  18172. const next = this.nextTokenStart();
  18173. const nextChar = this.input.charCodeAt(next);
  18174. if (nextChar === 123 || this.chStartsBindingIdentifier(nextChar, next) && !this.input.startsWith("from", next)) {
  18175. this.expectOnePlugin(["flow", "typescript"]);
  18176. return false;
  18177. }
  18178. }
  18179. } else if (!this.match(65)) {
  18180. return false;
  18181. }
  18182. const next = this.nextTokenStart();
  18183. const hasFrom = this.isUnparsedContextual(next, "from");
  18184. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  18185. return true;
  18186. }
  18187. if (this.match(65) && hasFrom) {
  18188. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  18189. return nextAfterFrom === 34 || nextAfterFrom === 39;
  18190. }
  18191. return false;
  18192. }
  18193. parseExportFrom(node, expect) {
  18194. if (this.eatContextual(98)) {
  18195. node.source = this.parseImportSource();
  18196. this.checkExport(node);
  18197. this.maybeParseImportAttributes(node);
  18198. this.checkJSONModuleImport(node);
  18199. } else if (expect) {
  18200. this.unexpected();
  18201. }
  18202. this.semicolon();
  18203. }
  18204. shouldParseExportDeclaration() {
  18205. const {
  18206. type
  18207. } = this.state;
  18208. if (type === 26) {
  18209. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  18210. if (this.hasPlugin("decorators")) {
  18211. if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  18212. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  18213. }
  18214. return true;
  18215. }
  18216. }
  18217. if (this.isUsing()) {
  18218. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  18219. return true;
  18220. }
  18221. if (this.isAwaitUsing()) {
  18222. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  18223. return true;
  18224. }
  18225. return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction();
  18226. }
  18227. checkExport(node, checkNames, isDefault, isFrom) {
  18228. if (checkNames) {
  18229. var _node$specifiers;
  18230. if (isDefault) {
  18231. this.checkDuplicateExports(node, "default");
  18232. if (this.hasPlugin("exportDefaultFrom")) {
  18233. var _declaration$extra;
  18234. const declaration = node.declaration;
  18235. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  18236. this.raise(Errors.ExportDefaultFromAsIdentifier, declaration);
  18237. }
  18238. }
  18239. } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
  18240. for (const specifier of node.specifiers) {
  18241. const {
  18242. exported
  18243. } = specifier;
  18244. const exportName = exported.type === "Identifier" ? exported.name : exported.value;
  18245. this.checkDuplicateExports(specifier, exportName);
  18246. if (!isFrom && specifier.local) {
  18247. const {
  18248. local
  18249. } = specifier;
  18250. if (local.type !== "Identifier") {
  18251. this.raise(Errors.ExportBindingIsString, specifier, {
  18252. localName: local.value,
  18253. exportName
  18254. });
  18255. } else {
  18256. this.checkReservedWord(local.name, local.loc.start, true, false);
  18257. this.scope.checkLocalExport(local);
  18258. }
  18259. }
  18260. }
  18261. } else if (node.declaration) {
  18262. const decl = node.declaration;
  18263. if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") {
  18264. const {
  18265. id
  18266. } = decl;
  18267. if (!id) throw new Error("Assertion failure");
  18268. this.checkDuplicateExports(node, id.name);
  18269. } else if (decl.type === "VariableDeclaration") {
  18270. for (const declaration of decl.declarations) {
  18271. this.checkDeclaration(declaration.id);
  18272. }
  18273. }
  18274. }
  18275. }
  18276. }
  18277. checkDeclaration(node) {
  18278. if (node.type === "Identifier") {
  18279. this.checkDuplicateExports(node, node.name);
  18280. } else if (node.type === "ObjectPattern") {
  18281. for (const prop of node.properties) {
  18282. this.checkDeclaration(prop);
  18283. }
  18284. } else if (node.type === "ArrayPattern") {
  18285. for (const elem of node.elements) {
  18286. if (elem) {
  18287. this.checkDeclaration(elem);
  18288. }
  18289. }
  18290. } else if (node.type === "ObjectProperty") {
  18291. this.checkDeclaration(node.value);
  18292. } else if (node.type === "RestElement") {
  18293. this.checkDeclaration(node.argument);
  18294. } else if (node.type === "AssignmentPattern") {
  18295. this.checkDeclaration(node.left);
  18296. }
  18297. }
  18298. checkDuplicateExports(node, exportName) {
  18299. if (this.exportedIdentifiers.has(exportName)) {
  18300. if (exportName === "default") {
  18301. this.raise(Errors.DuplicateDefaultExport, node);
  18302. } else {
  18303. this.raise(Errors.DuplicateExport, node, {
  18304. exportName
  18305. });
  18306. }
  18307. }
  18308. this.exportedIdentifiers.add(exportName);
  18309. }
  18310. parseExportSpecifiers(isInTypeExport) {
  18311. const nodes = [];
  18312. let first = true;
  18313. this.expect(5);
  18314. while (!this.eat(8)) {
  18315. if (first) {
  18316. first = false;
  18317. } else {
  18318. this.expect(12);
  18319. if (this.eat(8)) break;
  18320. }
  18321. const isMaybeTypeOnly = this.isContextual(130);
  18322. const isString = this.match(134);
  18323. const node = this.startNode();
  18324. node.local = this.parseModuleExportName();
  18325. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  18326. }
  18327. return nodes;
  18328. }
  18329. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  18330. if (this.eatContextual(93)) {
  18331. node.exported = this.parseModuleExportName();
  18332. } else if (isString) {
  18333. node.exported = this.cloneStringLiteral(node.local);
  18334. } else if (!node.exported) {
  18335. node.exported = this.cloneIdentifier(node.local);
  18336. }
  18337. return this.finishNode(node, "ExportSpecifier");
  18338. }
  18339. parseModuleExportName() {
  18340. if (this.match(134)) {
  18341. const result = this.parseStringLiteral(this.state.value);
  18342. const surrogate = loneSurrogate.exec(result.value);
  18343. if (surrogate) {
  18344. this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, {
  18345. surrogateCharCode: surrogate[0].charCodeAt(0)
  18346. });
  18347. }
  18348. return result;
  18349. }
  18350. return this.parseIdentifier(true);
  18351. }
  18352. isJSONModuleImport(node) {
  18353. if (node.assertions != null) {
  18354. return node.assertions.some(({
  18355. key,
  18356. value
  18357. }) => {
  18358. return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type");
  18359. });
  18360. }
  18361. return false;
  18362. }
  18363. checkImportReflection(node) {
  18364. const {
  18365. specifiers
  18366. } = node;
  18367. const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null;
  18368. if (node.phase === "source") {
  18369. if (singleBindingType !== "ImportDefaultSpecifier") {
  18370. this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start);
  18371. }
  18372. } else if (node.phase === "defer") {
  18373. if (singleBindingType !== "ImportNamespaceSpecifier") {
  18374. this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start);
  18375. }
  18376. } else if (node.module) {
  18377. var _node$assertions;
  18378. if (singleBindingType !== "ImportDefaultSpecifier") {
  18379. this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start);
  18380. }
  18381. if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) {
  18382. this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start);
  18383. }
  18384. }
  18385. }
  18386. checkJSONModuleImport(node) {
  18387. if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") {
  18388. const {
  18389. specifiers
  18390. } = node;
  18391. if (specifiers != null) {
  18392. const nonDefaultNamedSpecifier = specifiers.find(specifier => {
  18393. let imported;
  18394. if (specifier.type === "ExportSpecifier") {
  18395. imported = specifier.local;
  18396. } else if (specifier.type === "ImportSpecifier") {
  18397. imported = specifier.imported;
  18398. }
  18399. if (imported !== undefined) {
  18400. return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default";
  18401. }
  18402. });
  18403. if (nonDefaultNamedSpecifier !== undefined) {
  18404. this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start);
  18405. }
  18406. }
  18407. }
  18408. }
  18409. isPotentialImportPhase(isExport) {
  18410. if (isExport) return false;
  18411. return this.isContextual(105) || this.isContextual(97) || this.isContextual(127);
  18412. }
  18413. applyImportPhase(node, isExport, phase, loc) {
  18414. if (isExport) {
  18415. return;
  18416. }
  18417. if (phase === "module") {
  18418. this.expectPlugin("importReflection", loc);
  18419. node.module = true;
  18420. } else if (this.hasPlugin("importReflection")) {
  18421. node.module = false;
  18422. }
  18423. if (phase === "source") {
  18424. this.expectPlugin("sourcePhaseImports", loc);
  18425. node.phase = "source";
  18426. } else if (phase === "defer") {
  18427. this.expectPlugin("deferredImportEvaluation", loc);
  18428. node.phase = "defer";
  18429. } else if (this.hasPlugin("sourcePhaseImports")) {
  18430. node.phase = null;
  18431. }
  18432. }
  18433. parseMaybeImportPhase(node, isExport) {
  18434. if (!this.isPotentialImportPhase(isExport)) {
  18435. this.applyImportPhase(node, isExport, null);
  18436. return null;
  18437. }
  18438. const phaseIdentifier = this.startNode();
  18439. const phaseIdentifierName = this.parseIdentifierName(true);
  18440. const {
  18441. type
  18442. } = this.state;
  18443. const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  18444. if (isImportPhase) {
  18445. this.applyImportPhase(node, isExport, phaseIdentifierName, phaseIdentifier.loc.start);
  18446. return null;
  18447. } else {
  18448. this.applyImportPhase(node, isExport, null);
  18449. return this.createIdentifier(phaseIdentifier, phaseIdentifierName);
  18450. }
  18451. }
  18452. isPrecedingIdImportPhase(phase) {
  18453. const {
  18454. type
  18455. } = this.state;
  18456. return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  18457. }
  18458. parseImport(node) {
  18459. if (this.match(134)) {
  18460. return this.parseImportSourceAndAttributes(node);
  18461. }
  18462. return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false));
  18463. }
  18464. parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) {
  18465. node.specifiers = [];
  18466. const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier);
  18467. const parseNext = !hasDefault || this.eat(12);
  18468. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  18469. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  18470. this.expectContextual(98);
  18471. return this.parseImportSourceAndAttributes(node);
  18472. }
  18473. parseImportSourceAndAttributes(node) {
  18474. var _node$specifiers2;
  18475. (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = [];
  18476. node.source = this.parseImportSource();
  18477. this.maybeParseImportAttributes(node);
  18478. this.checkImportReflection(node);
  18479. this.checkJSONModuleImport(node);
  18480. this.semicolon();
  18481. this.sawUnambiguousESM = true;
  18482. return this.finishNode(node, "ImportDeclaration");
  18483. }
  18484. parseImportSource() {
  18485. if (!this.match(134)) this.unexpected();
  18486. return this.parseExprAtom();
  18487. }
  18488. parseImportSpecifierLocal(node, specifier, type) {
  18489. specifier.local = this.parseIdentifier();
  18490. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  18491. }
  18492. finishImportSpecifier(specifier, type, bindingType = 8201) {
  18493. this.checkLVal(specifier.local, {
  18494. type
  18495. }, bindingType);
  18496. return this.finishNode(specifier, type);
  18497. }
  18498. parseImportAttributes() {
  18499. this.expect(5);
  18500. const attrs = [];
  18501. const attrNames = new Set();
  18502. do {
  18503. if (this.match(8)) {
  18504. break;
  18505. }
  18506. const node = this.startNode();
  18507. const keyName = this.state.value;
  18508. if (attrNames.has(keyName)) {
  18509. this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, {
  18510. key: keyName
  18511. });
  18512. }
  18513. attrNames.add(keyName);
  18514. if (this.match(134)) {
  18515. node.key = this.parseStringLiteral(keyName);
  18516. } else {
  18517. node.key = this.parseIdentifier(true);
  18518. }
  18519. this.expect(14);
  18520. if (!this.match(134)) {
  18521. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  18522. }
  18523. node.value = this.parseStringLiteral(this.state.value);
  18524. attrs.push(this.finishNode(node, "ImportAttribute"));
  18525. } while (this.eat(12));
  18526. this.expect(8);
  18527. return attrs;
  18528. }
  18529. parseModuleAttributes() {
  18530. const attrs = [];
  18531. const attributes = new Set();
  18532. do {
  18533. const node = this.startNode();
  18534. node.key = this.parseIdentifier(true);
  18535. if (node.key.name !== "type") {
  18536. this.raise(Errors.ModuleAttributeDifferentFromType, node.key);
  18537. }
  18538. if (attributes.has(node.key.name)) {
  18539. this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, {
  18540. key: node.key.name
  18541. });
  18542. }
  18543. attributes.add(node.key.name);
  18544. this.expect(14);
  18545. if (!this.match(134)) {
  18546. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  18547. }
  18548. node.value = this.parseStringLiteral(this.state.value);
  18549. attrs.push(this.finishNode(node, "ImportAttribute"));
  18550. } while (this.eat(12));
  18551. return attrs;
  18552. }
  18553. maybeParseImportAttributes(node) {
  18554. let attributes;
  18555. var useWith = false;
  18556. if (this.match(76)) {
  18557. if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) {
  18558. return;
  18559. }
  18560. this.next();
  18561. if (this.hasPlugin("moduleAttributes")) {
  18562. attributes = this.parseModuleAttributes();
  18563. this.addExtra(node, "deprecatedWithLegacySyntax", true);
  18564. } else {
  18565. attributes = this.parseImportAttributes();
  18566. }
  18567. useWith = true;
  18568. } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) {
  18569. if (!this.hasPlugin("deprecatedImportAssert") && !this.hasPlugin("importAssertions")) {
  18570. this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc);
  18571. }
  18572. if (!this.hasPlugin("importAssertions")) {
  18573. this.addExtra(node, "deprecatedAssertSyntax", true);
  18574. }
  18575. this.next();
  18576. attributes = this.parseImportAttributes();
  18577. } else {
  18578. attributes = [];
  18579. }
  18580. if (!useWith && this.hasPlugin("importAssertions")) {
  18581. node.assertions = attributes;
  18582. } else {
  18583. node.attributes = attributes;
  18584. }
  18585. }
  18586. maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) {
  18587. if (maybeDefaultIdentifier) {
  18588. const specifier = this.startNodeAtNode(maybeDefaultIdentifier);
  18589. specifier.local = maybeDefaultIdentifier;
  18590. node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier"));
  18591. return true;
  18592. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  18593. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier");
  18594. return true;
  18595. }
  18596. return false;
  18597. }
  18598. maybeParseStarImportSpecifier(node) {
  18599. if (this.match(55)) {
  18600. const specifier = this.startNode();
  18601. this.next();
  18602. this.expectContextual(93);
  18603. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier");
  18604. return true;
  18605. }
  18606. return false;
  18607. }
  18608. parseNamedImportSpecifiers(node) {
  18609. let first = true;
  18610. this.expect(5);
  18611. while (!this.eat(8)) {
  18612. if (first) {
  18613. first = false;
  18614. } else {
  18615. if (this.eat(14)) {
  18616. throw this.raise(Errors.DestructureNamedImport, this.state.startLoc);
  18617. }
  18618. this.expect(12);
  18619. if (this.eat(8)) break;
  18620. }
  18621. const specifier = this.startNode();
  18622. const importedIsString = this.match(134);
  18623. const isMaybeTypeOnly = this.isContextual(130);
  18624. specifier.imported = this.parseModuleExportName();
  18625. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined);
  18626. node.specifiers.push(importSpecifier);
  18627. }
  18628. }
  18629. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  18630. if (this.eatContextual(93)) {
  18631. specifier.local = this.parseIdentifier();
  18632. } else {
  18633. const {
  18634. imported
  18635. } = specifier;
  18636. if (importedIsString) {
  18637. throw this.raise(Errors.ImportBindingIsString, specifier, {
  18638. importName: imported.value
  18639. });
  18640. }
  18641. this.checkReservedWord(imported.name, specifier.loc.start, true, true);
  18642. if (!specifier.local) {
  18643. specifier.local = this.cloneIdentifier(imported);
  18644. }
  18645. }
  18646. return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType);
  18647. }
  18648. isThisParam(param) {
  18649. return param.type === "Identifier" && param.name === "this";
  18650. }
  18651. }
  18652. class Parser extends StatementParser {
  18653. constructor(options, input, pluginsMap) {
  18654. const normalizedOptions = getOptions(options);
  18655. super(normalizedOptions, input);
  18656. this.options = normalizedOptions;
  18657. this.initializeScopes();
  18658. this.plugins = pluginsMap;
  18659. this.filename = normalizedOptions.sourceFilename;
  18660. this.startIndex = normalizedOptions.startIndex;
  18661. let optionFlags = 0;
  18662. if (normalizedOptions.allowAwaitOutsideFunction) {
  18663. optionFlags |= 1;
  18664. }
  18665. if (normalizedOptions.allowReturnOutsideFunction) {
  18666. optionFlags |= 2;
  18667. }
  18668. if (normalizedOptions.allowImportExportEverywhere) {
  18669. optionFlags |= 8;
  18670. }
  18671. if (normalizedOptions.allowSuperOutsideMethod) {
  18672. optionFlags |= 16;
  18673. }
  18674. if (normalizedOptions.allowUndeclaredExports) {
  18675. optionFlags |= 64;
  18676. }
  18677. if (normalizedOptions.allowNewTargetOutsideFunction) {
  18678. optionFlags |= 4;
  18679. }
  18680. if (normalizedOptions.allowYieldOutsideFunction) {
  18681. optionFlags |= 32;
  18682. }
  18683. if (normalizedOptions.ranges) {
  18684. optionFlags |= 128;
  18685. }
  18686. if (normalizedOptions.tokens) {
  18687. optionFlags |= 256;
  18688. }
  18689. if (normalizedOptions.createImportExpressions) {
  18690. optionFlags |= 512;
  18691. }
  18692. if (normalizedOptions.createParenthesizedExpressions) {
  18693. optionFlags |= 1024;
  18694. }
  18695. if (normalizedOptions.errorRecovery) {
  18696. optionFlags |= 2048;
  18697. }
  18698. if (normalizedOptions.attachComment) {
  18699. optionFlags |= 4096;
  18700. }
  18701. if (normalizedOptions.annexB) {
  18702. optionFlags |= 8192;
  18703. }
  18704. this.optionFlags = optionFlags;
  18705. }
  18706. getScopeHandler() {
  18707. return ScopeHandler;
  18708. }
  18709. parse() {
  18710. this.enterInitialScopes();
  18711. const file = this.startNode();
  18712. const program = this.startNode();
  18713. this.nextToken();
  18714. file.errors = null;
  18715. const result = this.parseTopLevel(file, program);
  18716. result.errors = this.state.errors;
  18717. result.comments.length = this.state.commentsLen;
  18718. return result;
  18719. }
  18720. }
  18721. function parse(input, options) {
  18722. var _options;
  18723. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  18724. options = Object.assign({}, options);
  18725. try {
  18726. options.sourceType = "module";
  18727. const parser = getParser(options, input);
  18728. const ast = parser.parse();
  18729. if (parser.sawUnambiguousESM) {
  18730. return ast;
  18731. }
  18732. if (parser.ambiguousScriptDifferentAst) {
  18733. try {
  18734. options.sourceType = "script";
  18735. return getParser(options, input).parse();
  18736. } catch (_unused) {}
  18737. } else {
  18738. ast.program.sourceType = "script";
  18739. }
  18740. return ast;
  18741. } catch (moduleError) {
  18742. try {
  18743. options.sourceType = "script";
  18744. return getParser(options, input).parse();
  18745. } catch (_unused2) {}
  18746. throw moduleError;
  18747. }
  18748. } else {
  18749. return getParser(options, input).parse();
  18750. }
  18751. }
  18752. function parseExpression(input, options) {
  18753. const parser = getParser(options, input);
  18754. if (parser.options.strictMode) {
  18755. parser.state.strict = true;
  18756. }
  18757. return parser.getExpression();
  18758. }
  18759. function generateExportedTokenTypes(internalTokenTypes) {
  18760. const tokenTypes = {};
  18761. for (const typeName of Object.keys(internalTokenTypes)) {
  18762. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  18763. }
  18764. return tokenTypes;
  18765. }
  18766. const tokTypes = generateExportedTokenTypes(tt);
  18767. function getParser(options, input) {
  18768. let cls = Parser;
  18769. const pluginsMap = new Map();
  18770. if (options != null && options.plugins) {
  18771. for (const plugin of options.plugins) {
  18772. let name, opts;
  18773. if (typeof plugin === "string") {
  18774. name = plugin;
  18775. } else {
  18776. [name, opts] = plugin;
  18777. }
  18778. if (!pluginsMap.has(name)) {
  18779. pluginsMap.set(name, opts || {});
  18780. }
  18781. }
  18782. validatePlugins(pluginsMap);
  18783. cls = getParserClass(pluginsMap);
  18784. }
  18785. return new cls(options, input, pluginsMap);
  18786. }
  18787. const parserClassCache = new Map();
  18788. function getParserClass(pluginsMap) {
  18789. const pluginList = [];
  18790. for (const name of mixinPluginNames) {
  18791. if (pluginsMap.has(name)) {
  18792. pluginList.push(name);
  18793. }
  18794. }
  18795. const key = pluginList.join("|");
  18796. let cls = parserClassCache.get(key);
  18797. if (!cls) {
  18798. cls = Parser;
  18799. for (const plugin of pluginList) {
  18800. cls = mixinPlugins[plugin](cls);
  18801. }
  18802. parserClassCache.set(key, cls);
  18803. }
  18804. return cls;
  18805. }
  18806. lib.parse = parse;
  18807. lib.parseExpression = parseExpression;
  18808. lib.tokTypes = tokTypes;
  18809. return lib;
  18810. }
  18811. var libExports = /*@__PURE__*/ requireLib();
  18812. // @ts-check
  18813. /** @typedef { import('estree').BaseNode} BaseNode */
  18814. /** @typedef {{
  18815. skip: () => void;
  18816. remove: () => void;
  18817. replace: (node: BaseNode) => void;
  18818. }} WalkerContext */
  18819. class WalkerBase {
  18820. constructor() {
  18821. /** @type {boolean} */
  18822. this.should_skip = false;
  18823. /** @type {boolean} */
  18824. this.should_remove = false;
  18825. /** @type {BaseNode | null} */
  18826. this.replacement = null;
  18827. /** @type {WalkerContext} */
  18828. this.context = {
  18829. skip: () => (this.should_skip = true),
  18830. remove: () => (this.should_remove = true),
  18831. replace: (node) => (this.replacement = node)
  18832. };
  18833. }
  18834. /**
  18835. *
  18836. * @param {any} parent
  18837. * @param {string} prop
  18838. * @param {number} index
  18839. * @param {BaseNode} node
  18840. */
  18841. replace(parent, prop, index, node) {
  18842. if (parent) {
  18843. if (index !== null) {
  18844. parent[prop][index] = node;
  18845. } else {
  18846. parent[prop] = node;
  18847. }
  18848. }
  18849. }
  18850. /**
  18851. *
  18852. * @param {any} parent
  18853. * @param {string} prop
  18854. * @param {number} index
  18855. */
  18856. remove(parent, prop, index) {
  18857. if (parent) {
  18858. if (index !== null) {
  18859. parent[prop].splice(index, 1);
  18860. } else {
  18861. delete parent[prop];
  18862. }
  18863. }
  18864. }
  18865. }
  18866. // @ts-check
  18867. /** @typedef { import('estree').BaseNode} BaseNode */
  18868. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  18869. /** @typedef {(
  18870. * this: WalkerContext,
  18871. * node: BaseNode,
  18872. * parent: BaseNode,
  18873. * key: string,
  18874. * index: number
  18875. * ) => void} SyncHandler */
  18876. class SyncWalker extends WalkerBase {
  18877. /**
  18878. *
  18879. * @param {SyncHandler} enter
  18880. * @param {SyncHandler} leave
  18881. */
  18882. constructor(enter, leave) {
  18883. super();
  18884. /** @type {SyncHandler} */
  18885. this.enter = enter;
  18886. /** @type {SyncHandler} */
  18887. this.leave = leave;
  18888. }
  18889. /**
  18890. *
  18891. * @param {BaseNode} node
  18892. * @param {BaseNode} parent
  18893. * @param {string} [prop]
  18894. * @param {number} [index]
  18895. * @returns {BaseNode}
  18896. */
  18897. visit(node, parent, prop, index) {
  18898. if (node) {
  18899. if (this.enter) {
  18900. const _should_skip = this.should_skip;
  18901. const _should_remove = this.should_remove;
  18902. const _replacement = this.replacement;
  18903. this.should_skip = false;
  18904. this.should_remove = false;
  18905. this.replacement = null;
  18906. this.enter.call(this.context, node, parent, prop, index);
  18907. if (this.replacement) {
  18908. node = this.replacement;
  18909. this.replace(parent, prop, index, node);
  18910. }
  18911. if (this.should_remove) {
  18912. this.remove(parent, prop, index);
  18913. }
  18914. const skipped = this.should_skip;
  18915. const removed = this.should_remove;
  18916. this.should_skip = _should_skip;
  18917. this.should_remove = _should_remove;
  18918. this.replacement = _replacement;
  18919. if (skipped) return node;
  18920. if (removed) return null;
  18921. }
  18922. for (const key in node) {
  18923. const value = node[key];
  18924. if (typeof value !== "object") {
  18925. continue;
  18926. } else if (Array.isArray(value)) {
  18927. for (let i = 0; i < value.length; i += 1) {
  18928. if (value[i] !== null && typeof value[i].type === 'string') {
  18929. if (!this.visit(value[i], node, key, i)) {
  18930. // removed
  18931. i--;
  18932. }
  18933. }
  18934. }
  18935. } else if (value !== null && typeof value.type === "string") {
  18936. this.visit(value, node, key, null);
  18937. }
  18938. }
  18939. if (this.leave) {
  18940. const _replacement = this.replacement;
  18941. const _should_remove = this.should_remove;
  18942. this.replacement = null;
  18943. this.should_remove = false;
  18944. this.leave.call(this.context, node, parent, prop, index);
  18945. if (this.replacement) {
  18946. node = this.replacement;
  18947. this.replace(parent, prop, index, node);
  18948. }
  18949. if (this.should_remove) {
  18950. this.remove(parent, prop, index);
  18951. }
  18952. const removed = this.should_remove;
  18953. this.replacement = _replacement;
  18954. this.should_remove = _should_remove;
  18955. if (removed) return null;
  18956. }
  18957. }
  18958. return node;
  18959. }
  18960. }
  18961. // @ts-check
  18962. /** @typedef { import('estree').BaseNode} BaseNode */
  18963. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  18964. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  18965. /**
  18966. *
  18967. * @param {BaseNode} ast
  18968. * @param {{
  18969. * enter?: SyncHandler
  18970. * leave?: SyncHandler
  18971. * }} walker
  18972. * @returns {BaseNode}
  18973. */
  18974. function walk$2(ast, { enter, leave }) {
  18975. const instance = new SyncWalker(enter, leave);
  18976. return instance.visit(ast, null);
  18977. }
  18978. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = /* @__PURE__ */ Object.create(null)) {
  18979. const rootExp = root.type === "Program" ? root.body[0].type === "ExpressionStatement" && root.body[0].expression : root;
  18980. walk$2(root, {
  18981. enter(node, parent) {
  18982. parent && parentStack.push(parent);
  18983. if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
  18984. return this.skip();
  18985. }
  18986. if (node.type === "Identifier") {
  18987. const isLocal = !!knownIds[node.name];
  18988. const isRefed = isReferencedIdentifier(node, parent, parentStack);
  18989. if (includeAll || isRefed && !isLocal) {
  18990. onIdentifier(node, parent, parentStack, isRefed, isLocal);
  18991. }
  18992. } else if (node.type === "ObjectProperty" && // eslint-disable-next-line no-restricted-syntax
  18993. (parent == null ? void 0 : parent.type) === "ObjectPattern") {
  18994. node.inPattern = true;
  18995. } else if (isFunctionType(node)) {
  18996. if (node.scopeIds) {
  18997. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  18998. } else {
  18999. walkFunctionParams(
  19000. node,
  19001. (id) => markScopeIdentifier(node, id, knownIds)
  19002. );
  19003. }
  19004. } else if (node.type === "BlockStatement") {
  19005. if (node.scopeIds) {
  19006. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19007. } else {
  19008. walkBlockDeclarations(
  19009. node,
  19010. (id) => markScopeIdentifier(node, id, knownIds)
  19011. );
  19012. }
  19013. } else if (node.type === "SwitchStatement") {
  19014. if (node.scopeIds) {
  19015. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19016. } else {
  19017. walkSwitchStatement(
  19018. node,
  19019. false,
  19020. (id) => markScopeIdentifier(node, id, knownIds)
  19021. );
  19022. }
  19023. } else if (node.type === "CatchClause" && node.param) {
  19024. if (node.scopeIds) {
  19025. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19026. } else {
  19027. for (const id of extractIdentifiers$1(node.param)) {
  19028. markScopeIdentifier(node, id, knownIds);
  19029. }
  19030. }
  19031. } else if (isForStatement(node)) {
  19032. if (node.scopeIds) {
  19033. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19034. } else {
  19035. walkForStatement(
  19036. node,
  19037. false,
  19038. (id) => markScopeIdentifier(node, id, knownIds)
  19039. );
  19040. }
  19041. }
  19042. },
  19043. leave(node, parent) {
  19044. parent && parentStack.pop();
  19045. if (node !== rootExp && node.scopeIds) {
  19046. for (const id of node.scopeIds) {
  19047. knownIds[id]--;
  19048. if (knownIds[id] === 0) {
  19049. delete knownIds[id];
  19050. }
  19051. }
  19052. }
  19053. }
  19054. });
  19055. }
  19056. function isReferencedIdentifier(id, parent, parentStack) {
  19057. if (!parent) {
  19058. return true;
  19059. }
  19060. if (id.name === "arguments") {
  19061. return false;
  19062. }
  19063. if (isReferenced(id, parent, parentStack[parentStack.length - 2])) {
  19064. return true;
  19065. }
  19066. switch (parent.type) {
  19067. case "AssignmentExpression":
  19068. case "AssignmentPattern":
  19069. return true;
  19070. case "ObjectProperty":
  19071. return parent.key !== id && isInDestructureAssignment(parent, parentStack);
  19072. case "ArrayPattern":
  19073. return isInDestructureAssignment(parent, parentStack);
  19074. }
  19075. return false;
  19076. }
  19077. function isInDestructureAssignment(parent, parentStack) {
  19078. if (parent && (parent.type === "ObjectProperty" || parent.type === "ArrayPattern")) {
  19079. let i = parentStack.length;
  19080. while (i--) {
  19081. const p = parentStack[i];
  19082. if (p.type === "AssignmentExpression") {
  19083. return true;
  19084. } else if (p.type !== "ObjectProperty" && !p.type.endsWith("Pattern")) {
  19085. break;
  19086. }
  19087. }
  19088. }
  19089. return false;
  19090. }
  19091. function isInNewExpression(parentStack) {
  19092. let i = parentStack.length;
  19093. while (i--) {
  19094. const p = parentStack[i];
  19095. if (p.type === "NewExpression") {
  19096. return true;
  19097. } else if (p.type !== "MemberExpression") {
  19098. break;
  19099. }
  19100. }
  19101. return false;
  19102. }
  19103. function walkFunctionParams(node, onIdent) {
  19104. for (const p of node.params) {
  19105. for (const id of extractIdentifiers$1(p)) {
  19106. onIdent(id);
  19107. }
  19108. }
  19109. }
  19110. function walkBlockDeclarations(block, onIdent) {
  19111. const body = block.type === "SwitchCase" ? block.consequent : block.body;
  19112. for (const stmt of body) {
  19113. if (stmt.type === "VariableDeclaration") {
  19114. if (stmt.declare) continue;
  19115. for (const decl of stmt.declarations) {
  19116. for (const id of extractIdentifiers$1(decl.id)) {
  19117. onIdent(id);
  19118. }
  19119. }
  19120. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  19121. if (stmt.declare || !stmt.id) continue;
  19122. onIdent(stmt.id);
  19123. } else if (isForStatement(stmt)) {
  19124. walkForStatement(stmt, true, onIdent);
  19125. } else if (stmt.type === "SwitchStatement") {
  19126. walkSwitchStatement(stmt, true, onIdent);
  19127. }
  19128. }
  19129. }
  19130. function isForStatement(stmt) {
  19131. return stmt.type === "ForOfStatement" || stmt.type === "ForInStatement" || stmt.type === "ForStatement";
  19132. }
  19133. function walkForStatement(stmt, isVar, onIdent) {
  19134. const variable = stmt.type === "ForStatement" ? stmt.init : stmt.left;
  19135. if (variable && variable.type === "VariableDeclaration" && (variable.kind === "var" ? isVar : !isVar)) {
  19136. for (const decl of variable.declarations) {
  19137. for (const id of extractIdentifiers$1(decl.id)) {
  19138. onIdent(id);
  19139. }
  19140. }
  19141. }
  19142. }
  19143. function walkSwitchStatement(stmt, isVar, onIdent) {
  19144. for (const cs of stmt.cases) {
  19145. for (const stmt2 of cs.consequent) {
  19146. if (stmt2.type === "VariableDeclaration" && (stmt2.kind === "var" ? isVar : !isVar)) {
  19147. for (const decl of stmt2.declarations) {
  19148. for (const id of extractIdentifiers$1(decl.id)) {
  19149. onIdent(id);
  19150. }
  19151. }
  19152. }
  19153. }
  19154. walkBlockDeclarations(cs, onIdent);
  19155. }
  19156. }
  19157. function extractIdentifiers$1(param, nodes = []) {
  19158. switch (param.type) {
  19159. case "Identifier":
  19160. nodes.push(param);
  19161. break;
  19162. case "MemberExpression":
  19163. let object = param;
  19164. while (object.type === "MemberExpression") {
  19165. object = object.object;
  19166. }
  19167. nodes.push(object);
  19168. break;
  19169. case "ObjectPattern":
  19170. for (const prop of param.properties) {
  19171. if (prop.type === "RestElement") {
  19172. extractIdentifiers$1(prop.argument, nodes);
  19173. } else {
  19174. extractIdentifiers$1(prop.value, nodes);
  19175. }
  19176. }
  19177. break;
  19178. case "ArrayPattern":
  19179. param.elements.forEach((element) => {
  19180. if (element) extractIdentifiers$1(element, nodes);
  19181. });
  19182. break;
  19183. case "RestElement":
  19184. extractIdentifiers$1(param.argument, nodes);
  19185. break;
  19186. case "AssignmentPattern":
  19187. extractIdentifiers$1(param.left, nodes);
  19188. break;
  19189. }
  19190. return nodes;
  19191. }
  19192. function markKnownIds(name, knownIds) {
  19193. if (name in knownIds) {
  19194. knownIds[name]++;
  19195. } else {
  19196. knownIds[name] = 1;
  19197. }
  19198. }
  19199. function markScopeIdentifier(node, child, knownIds) {
  19200. const { name } = child;
  19201. if (node.scopeIds && node.scopeIds.has(name)) {
  19202. return;
  19203. }
  19204. markKnownIds(name, knownIds);
  19205. (node.scopeIds || (node.scopeIds = /* @__PURE__ */ new Set())).add(name);
  19206. }
  19207. const isFunctionType = (node) => {
  19208. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  19209. };
  19210. const isStaticProperty = (node) => node && (node.type === "ObjectProperty" || node.type === "ObjectMethod") && !node.computed;
  19211. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  19212. function isReferenced(node, parent, grandparent) {
  19213. switch (parent.type) {
  19214. // yes: PARENT[NODE]
  19215. // yes: NODE.child
  19216. // no: parent.NODE
  19217. case "MemberExpression":
  19218. case "OptionalMemberExpression":
  19219. if (parent.property === node) {
  19220. return !!parent.computed;
  19221. }
  19222. return parent.object === node;
  19223. case "JSXMemberExpression":
  19224. return parent.object === node;
  19225. // no: let NODE = init;
  19226. // yes: let id = NODE;
  19227. case "VariableDeclarator":
  19228. return parent.init === node;
  19229. // yes: () => NODE
  19230. // no: (NODE) => {}
  19231. case "ArrowFunctionExpression":
  19232. return parent.body === node;
  19233. // no: class { #NODE; }
  19234. // no: class { get #NODE() {} }
  19235. // no: class { #NODE() {} }
  19236. // no: class { fn() { return this.#NODE; } }
  19237. case "PrivateName":
  19238. return false;
  19239. // no: class { NODE() {} }
  19240. // yes: class { [NODE]() {} }
  19241. // no: class { foo(NODE) {} }
  19242. case "ClassMethod":
  19243. case "ClassPrivateMethod":
  19244. case "ObjectMethod":
  19245. if (parent.key === node) {
  19246. return !!parent.computed;
  19247. }
  19248. return false;
  19249. // yes: { [NODE]: "" }
  19250. // no: { NODE: "" }
  19251. // depends: { NODE }
  19252. // depends: { key: NODE }
  19253. case "ObjectProperty":
  19254. if (parent.key === node) {
  19255. return !!parent.computed;
  19256. }
  19257. return !grandparent || grandparent.type !== "ObjectPattern";
  19258. // no: class { NODE = value; }
  19259. // yes: class { [NODE] = value; }
  19260. // yes: class { key = NODE; }
  19261. case "ClassProperty":
  19262. if (parent.key === node) {
  19263. return !!parent.computed;
  19264. }
  19265. return true;
  19266. case "ClassPrivateProperty":
  19267. return parent.key !== node;
  19268. // no: class NODE {}
  19269. // yes: class Foo extends NODE {}
  19270. case "ClassDeclaration":
  19271. case "ClassExpression":
  19272. return parent.superClass === node;
  19273. // yes: left = NODE;
  19274. // no: NODE = right;
  19275. case "AssignmentExpression":
  19276. return parent.right === node;
  19277. // no: [NODE = foo] = [];
  19278. // yes: [foo = NODE] = [];
  19279. case "AssignmentPattern":
  19280. return parent.right === node;
  19281. // no: NODE: for (;;) {}
  19282. case "LabeledStatement":
  19283. return false;
  19284. // no: try {} catch (NODE) {}
  19285. case "CatchClause":
  19286. return false;
  19287. // no: function foo(...NODE) {}
  19288. case "RestElement":
  19289. return false;
  19290. case "BreakStatement":
  19291. case "ContinueStatement":
  19292. return false;
  19293. // no: function NODE() {}
  19294. // no: function foo(NODE) {}
  19295. case "FunctionDeclaration":
  19296. case "FunctionExpression":
  19297. return false;
  19298. // no: export NODE from "foo";
  19299. // no: export * as NODE from "foo";
  19300. case "ExportNamespaceSpecifier":
  19301. case "ExportDefaultSpecifier":
  19302. return false;
  19303. // no: export { foo as NODE };
  19304. // yes: export { NODE as foo };
  19305. // no: export { NODE as foo } from "foo";
  19306. case "ExportSpecifier":
  19307. if (grandparent == null ? void 0 : grandparent.source) {
  19308. return false;
  19309. }
  19310. return parent.local === node;
  19311. // no: import NODE from "foo";
  19312. // no: import * as NODE from "foo";
  19313. // no: import { NODE as foo } from "foo";
  19314. // no: import { foo as NODE } from "foo";
  19315. // no: import NODE from "bar";
  19316. case "ImportDefaultSpecifier":
  19317. case "ImportNamespaceSpecifier":
  19318. case "ImportSpecifier":
  19319. return false;
  19320. // no: import "foo" assert { NODE: "json" }
  19321. case "ImportAttribute":
  19322. return false;
  19323. // no: <div NODE="foo" />
  19324. case "JSXAttribute":
  19325. return false;
  19326. // no: [NODE] = [];
  19327. // no: ({ NODE }) = [];
  19328. case "ObjectPattern":
  19329. case "ArrayPattern":
  19330. return false;
  19331. // no: new.NODE
  19332. // no: NODE.target
  19333. case "MetaProperty":
  19334. return false;
  19335. // yes: type X = { someProperty: NODE }
  19336. // no: type X = { NODE: OtherType }
  19337. case "ObjectTypeProperty":
  19338. return parent.key !== node;
  19339. // yes: enum X { Foo = NODE }
  19340. // no: enum X { NODE }
  19341. case "TSEnumMember":
  19342. return parent.id !== node;
  19343. // yes: { [NODE]: value }
  19344. // no: { NODE: value }
  19345. case "TSPropertySignature":
  19346. if (parent.key === node) {
  19347. return !!parent.computed;
  19348. }
  19349. return true;
  19350. }
  19351. return true;
  19352. }
  19353. const TS_NODE_TYPES = [
  19354. "TSAsExpression",
  19355. // foo as number
  19356. "TSTypeAssertion",
  19357. // (<number>foo)
  19358. "TSNonNullExpression",
  19359. // foo!
  19360. "TSInstantiationExpression",
  19361. // foo<string>
  19362. "TSSatisfiesExpression"
  19363. // foo satisfies T
  19364. ];
  19365. function unwrapTSNode(node) {
  19366. if (TS_NODE_TYPES.includes(node.type)) {
  19367. return unwrapTSNode(node.expression);
  19368. } else {
  19369. return node;
  19370. }
  19371. }
  19372. const isStaticExp = (p) => p.type === 4 && p.isStatic;
  19373. function isCoreComponent(tag) {
  19374. switch (tag) {
  19375. case "Teleport":
  19376. case "teleport":
  19377. return TELEPORT;
  19378. case "Suspense":
  19379. case "suspense":
  19380. return SUSPENSE;
  19381. case "KeepAlive":
  19382. case "keep-alive":
  19383. return KEEP_ALIVE;
  19384. case "BaseTransition":
  19385. case "base-transition":
  19386. return BASE_TRANSITION;
  19387. }
  19388. }
  19389. const nonIdentifierRE = /^$|^\d|[^\$\w\xA0-\uFFFF]/;
  19390. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  19391. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  19392. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  19393. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  19394. const getExpSource = (exp) => exp.type === 4 ? exp.content : exp.loc.source;
  19395. const isMemberExpressionBrowser = (exp) => {
  19396. const path = getExpSource(exp).trim().replace(whitespaceRE, (s) => s.trim());
  19397. let state = 0 /* inMemberExp */;
  19398. let stateStack = [];
  19399. let currentOpenBracketCount = 0;
  19400. let currentOpenParensCount = 0;
  19401. let currentStringType = null;
  19402. for (let i = 0; i < path.length; i++) {
  19403. const char = path.charAt(i);
  19404. switch (state) {
  19405. case 0 /* inMemberExp */:
  19406. if (char === "[") {
  19407. stateStack.push(state);
  19408. state = 1 /* inBrackets */;
  19409. currentOpenBracketCount++;
  19410. } else if (char === "(") {
  19411. stateStack.push(state);
  19412. state = 2 /* inParens */;
  19413. currentOpenParensCount++;
  19414. } else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  19415. return false;
  19416. }
  19417. break;
  19418. case 1 /* inBrackets */:
  19419. if (char === `'` || char === `"` || char === "`") {
  19420. stateStack.push(state);
  19421. state = 3 /* inString */;
  19422. currentStringType = char;
  19423. } else if (char === `[`) {
  19424. currentOpenBracketCount++;
  19425. } else if (char === `]`) {
  19426. if (!--currentOpenBracketCount) {
  19427. state = stateStack.pop();
  19428. }
  19429. }
  19430. break;
  19431. case 2 /* inParens */:
  19432. if (char === `'` || char === `"` || char === "`") {
  19433. stateStack.push(state);
  19434. state = 3 /* inString */;
  19435. currentStringType = char;
  19436. } else if (char === `(`) {
  19437. currentOpenParensCount++;
  19438. } else if (char === `)`) {
  19439. if (i === path.length - 1) {
  19440. return false;
  19441. }
  19442. if (!--currentOpenParensCount) {
  19443. state = stateStack.pop();
  19444. }
  19445. }
  19446. break;
  19447. case 3 /* inString */:
  19448. if (char === currentStringType) {
  19449. state = stateStack.pop();
  19450. currentStringType = null;
  19451. }
  19452. break;
  19453. }
  19454. }
  19455. return !currentOpenBracketCount && !currentOpenParensCount;
  19456. };
  19457. const isMemberExpressionNode = (exp, context) => {
  19458. try {
  19459. let ret = exp.ast || libExports.parseExpression(getExpSource(exp), {
  19460. plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"]
  19461. });
  19462. ret = unwrapTSNode(ret);
  19463. return ret.type === "MemberExpression" || ret.type === "OptionalMemberExpression" || ret.type === "Identifier" && ret.name !== "undefined";
  19464. } catch (e) {
  19465. return false;
  19466. }
  19467. };
  19468. const isMemberExpression = isMemberExpressionNode;
  19469. const fnExpRE = /^\s*(?:async\s*)?(?:\([^)]*?\)|[\w$_]+)\s*(?::[^=]+)?=>|^\s*(?:async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  19470. const isFnExpressionBrowser = (exp) => fnExpRE.test(getExpSource(exp));
  19471. const isFnExpressionNode = (exp, context) => {
  19472. try {
  19473. let ret = exp.ast || libExports.parseExpression(getExpSource(exp), {
  19474. plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"]
  19475. });
  19476. if (ret.type === "Program") {
  19477. ret = ret.body[0];
  19478. if (ret.type === "ExpressionStatement") {
  19479. ret = ret.expression;
  19480. }
  19481. }
  19482. ret = unwrapTSNode(ret);
  19483. return ret.type === "FunctionExpression" || ret.type === "ArrowFunctionExpression";
  19484. } catch (e) {
  19485. return false;
  19486. }
  19487. };
  19488. const isFnExpression = isFnExpressionNode;
  19489. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  19490. return advancePositionWithMutation(
  19491. {
  19492. offset: pos.offset,
  19493. line: pos.line,
  19494. column: pos.column
  19495. },
  19496. source,
  19497. numberOfCharacters
  19498. );
  19499. }
  19500. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  19501. let linesCount = 0;
  19502. let lastNewLinePos = -1;
  19503. for (let i = 0; i < numberOfCharacters; i++) {
  19504. if (source.charCodeAt(i) === 10) {
  19505. linesCount++;
  19506. lastNewLinePos = i;
  19507. }
  19508. }
  19509. pos.offset += numberOfCharacters;
  19510. pos.line += linesCount;
  19511. pos.column = lastNewLinePos === -1 ? pos.column + numberOfCharacters : numberOfCharacters - lastNewLinePos;
  19512. return pos;
  19513. }
  19514. function assert(condition, msg) {
  19515. if (!condition) {
  19516. throw new Error(msg || `unexpected compiler condition`);
  19517. }
  19518. }
  19519. function findDir(node, name, allowEmpty = false) {
  19520. for (let i = 0; i < node.props.length; i++) {
  19521. const p = node.props[i];
  19522. if (p.type === 7 && (allowEmpty || p.exp) && (isString$1(name) ? p.name === name : name.test(p.name))) {
  19523. return p;
  19524. }
  19525. }
  19526. }
  19527. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  19528. for (let i = 0; i < node.props.length; i++) {
  19529. const p = node.props[i];
  19530. if (p.type === 6) {
  19531. if (dynamicOnly) continue;
  19532. if (p.name === name && (p.value || allowEmpty)) {
  19533. return p;
  19534. }
  19535. } else if (p.name === "bind" && (p.exp || allowEmpty) && isStaticArgOf(p.arg, name)) {
  19536. return p;
  19537. }
  19538. }
  19539. }
  19540. function isStaticArgOf(arg, name) {
  19541. return !!(arg && isStaticExp(arg) && arg.content === name);
  19542. }
  19543. function hasDynamicKeyVBind(node) {
  19544. return node.props.some(
  19545. (p) => p.type === 7 && p.name === "bind" && (!p.arg || // v-bind="obj"
  19546. p.arg.type !== 4 || // v-bind:[_ctx.foo]
  19547. !p.arg.isStatic)
  19548. // v-bind:[foo]
  19549. );
  19550. }
  19551. function isText$1(node) {
  19552. return node.type === 5 || node.type === 2;
  19553. }
  19554. function isVPre(p) {
  19555. return p.type === 7 && p.name === "pre";
  19556. }
  19557. function isVSlot(p) {
  19558. return p.type === 7 && p.name === "slot";
  19559. }
  19560. function isTemplateNode(node) {
  19561. return node.type === 1 && node.tagType === 3;
  19562. }
  19563. function isSlotOutlet(node) {
  19564. return node.type === 1 && node.tagType === 2;
  19565. }
  19566. const propsHelperSet = /* @__PURE__ */ new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  19567. function getUnnormalizedProps(props, callPath = []) {
  19568. if (props && !isString$1(props) && props.type === 14) {
  19569. const callee = props.callee;
  19570. if (!isString$1(callee) && propsHelperSet.has(callee)) {
  19571. return getUnnormalizedProps(
  19572. props.arguments[0],
  19573. callPath.concat(props)
  19574. );
  19575. }
  19576. }
  19577. return [props, callPath];
  19578. }
  19579. function injectProp(node, prop, context) {
  19580. let propsWithInjection;
  19581. let props = node.type === 13 ? node.props : node.arguments[2];
  19582. let callPath = [];
  19583. let parentCall;
  19584. if (props && !isString$1(props) && props.type === 14) {
  19585. const ret = getUnnormalizedProps(props);
  19586. props = ret[0];
  19587. callPath = ret[1];
  19588. parentCall = callPath[callPath.length - 1];
  19589. }
  19590. if (props == null || isString$1(props)) {
  19591. propsWithInjection = createObjectExpression([prop]);
  19592. } else if (props.type === 14) {
  19593. const first = props.arguments[0];
  19594. if (!isString$1(first) && first.type === 15) {
  19595. if (!hasProp(prop, first)) {
  19596. first.properties.unshift(prop);
  19597. }
  19598. } else {
  19599. if (props.callee === TO_HANDLERS) {
  19600. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  19601. createObjectExpression([prop]),
  19602. props
  19603. ]);
  19604. } else {
  19605. props.arguments.unshift(createObjectExpression([prop]));
  19606. }
  19607. }
  19608. !propsWithInjection && (propsWithInjection = props);
  19609. } else if (props.type === 15) {
  19610. if (!hasProp(prop, props)) {
  19611. props.properties.unshift(prop);
  19612. }
  19613. propsWithInjection = props;
  19614. } else {
  19615. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  19616. createObjectExpression([prop]),
  19617. props
  19618. ]);
  19619. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  19620. parentCall = callPath[callPath.length - 2];
  19621. }
  19622. }
  19623. if (node.type === 13) {
  19624. if (parentCall) {
  19625. parentCall.arguments[0] = propsWithInjection;
  19626. } else {
  19627. node.props = propsWithInjection;
  19628. }
  19629. } else {
  19630. if (parentCall) {
  19631. parentCall.arguments[0] = propsWithInjection;
  19632. } else {
  19633. node.arguments[2] = propsWithInjection;
  19634. }
  19635. }
  19636. }
  19637. function hasProp(prop, props) {
  19638. let result = false;
  19639. if (prop.key.type === 4) {
  19640. const propKeyName = prop.key.content;
  19641. result = props.properties.some(
  19642. (p) => p.key.type === 4 && p.key.content === propKeyName
  19643. );
  19644. }
  19645. return result;
  19646. }
  19647. function toValidAssetId(name, type) {
  19648. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  19649. return searchValue === "-" ? "_" : name.charCodeAt(replaceValue).toString();
  19650. })}`;
  19651. }
  19652. function hasScopeRef(node, ids) {
  19653. if (!node || Object.keys(ids).length === 0) {
  19654. return false;
  19655. }
  19656. switch (node.type) {
  19657. case 1:
  19658. for (let i = 0; i < node.props.length; i++) {
  19659. const p = node.props[i];
  19660. if (p.type === 7 && (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  19661. return true;
  19662. }
  19663. }
  19664. return node.children.some((c) => hasScopeRef(c, ids));
  19665. case 11:
  19666. if (hasScopeRef(node.source, ids)) {
  19667. return true;
  19668. }
  19669. return node.children.some((c) => hasScopeRef(c, ids));
  19670. case 9:
  19671. return node.branches.some((b) => hasScopeRef(b, ids));
  19672. case 10:
  19673. if (hasScopeRef(node.condition, ids)) {
  19674. return true;
  19675. }
  19676. return node.children.some((c) => hasScopeRef(c, ids));
  19677. case 4:
  19678. return !node.isStatic && isSimpleIdentifier(node.content) && !!ids[node.content];
  19679. case 8:
  19680. return node.children.some((c) => isObject$2(c) && hasScopeRef(c, ids));
  19681. case 5:
  19682. case 12:
  19683. return hasScopeRef(node.content, ids);
  19684. case 2:
  19685. case 3:
  19686. case 20:
  19687. return false;
  19688. default:
  19689. return false;
  19690. }
  19691. }
  19692. function getMemoedVNodeCall(node) {
  19693. if (node.type === 14 && node.callee === WITH_MEMO) {
  19694. return node.arguments[1].returns;
  19695. } else {
  19696. return node;
  19697. }
  19698. }
  19699. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/;
  19700. function isAllWhitespace(str) {
  19701. for (let i = 0; i < str.length; i++) {
  19702. if (!isWhitespace(str.charCodeAt(i))) {
  19703. return false;
  19704. }
  19705. }
  19706. return true;
  19707. }
  19708. function isWhitespaceText(node) {
  19709. return node.type === 2 && isAllWhitespace(node.content) || node.type === 12 && isWhitespaceText(node.content);
  19710. }
  19711. function isCommentOrWhitespace(node) {
  19712. return node.type === 3 || isWhitespaceText(node);
  19713. }
  19714. const defaultParserOptions = {
  19715. parseMode: "base",
  19716. ns: 0,
  19717. delimiters: [`{{`, `}}`],
  19718. getNamespace: () => 0,
  19719. isVoidTag: NO,
  19720. isPreTag: NO,
  19721. isIgnoreNewlineTag: NO,
  19722. isCustomElement: NO,
  19723. onError: defaultOnError,
  19724. onWarn: defaultOnWarn,
  19725. comments: true,
  19726. prefixIdentifiers: false
  19727. };
  19728. let currentOptions = defaultParserOptions;
  19729. let currentRoot = null;
  19730. let currentInput = "";
  19731. let currentOpenTag = null;
  19732. let currentProp = null;
  19733. let currentAttrValue = "";
  19734. let currentAttrStartIndex = -1;
  19735. let currentAttrEndIndex = -1;
  19736. let inPre = 0;
  19737. let inVPre = false;
  19738. let currentVPreBoundary = null;
  19739. const stack = [];
  19740. const tokenizer = new Tokenizer(stack, {
  19741. onerr: emitError,
  19742. ontext(start, end) {
  19743. onText(getSlice(start, end), start, end);
  19744. },
  19745. ontextentity(char, start, end) {
  19746. onText(char, start, end);
  19747. },
  19748. oninterpolation(start, end) {
  19749. if (inVPre) {
  19750. return onText(getSlice(start, end), start, end);
  19751. }
  19752. let innerStart = start + tokenizer.delimiterOpen.length;
  19753. let innerEnd = end - tokenizer.delimiterClose.length;
  19754. while (isWhitespace(currentInput.charCodeAt(innerStart))) {
  19755. innerStart++;
  19756. }
  19757. while (isWhitespace(currentInput.charCodeAt(innerEnd - 1))) {
  19758. innerEnd--;
  19759. }
  19760. let exp = getSlice(innerStart, innerEnd);
  19761. if (exp.includes("&")) {
  19762. {
  19763. exp = decodeHTML(exp);
  19764. }
  19765. }
  19766. addNode({
  19767. type: 5,
  19768. content: createExp(exp, false, getLoc(innerStart, innerEnd)),
  19769. loc: getLoc(start, end)
  19770. });
  19771. },
  19772. onopentagname(start, end) {
  19773. const name = getSlice(start, end);
  19774. currentOpenTag = {
  19775. type: 1,
  19776. tag: name,
  19777. ns: currentOptions.getNamespace(name, stack[0], currentOptions.ns),
  19778. tagType: 0,
  19779. // will be refined on tag close
  19780. props: [],
  19781. children: [],
  19782. loc: getLoc(start - 1, end),
  19783. codegenNode: void 0
  19784. };
  19785. },
  19786. onopentagend(end) {
  19787. endOpenTag(end);
  19788. },
  19789. onclosetag(start, end) {
  19790. const name = getSlice(start, end);
  19791. if (!currentOptions.isVoidTag(name)) {
  19792. let found = false;
  19793. for (let i = 0; i < stack.length; i++) {
  19794. const e = stack[i];
  19795. if (e.tag.toLowerCase() === name.toLowerCase()) {
  19796. found = true;
  19797. if (i > 0) {
  19798. emitError(24, stack[0].loc.start.offset);
  19799. }
  19800. for (let j = 0; j <= i; j++) {
  19801. const el = stack.shift();
  19802. onCloseTag(el, end, j < i);
  19803. }
  19804. break;
  19805. }
  19806. }
  19807. if (!found) {
  19808. emitError(23, backTrack(start, 60));
  19809. }
  19810. }
  19811. },
  19812. onselfclosingtag(end) {
  19813. const name = currentOpenTag.tag;
  19814. currentOpenTag.isSelfClosing = true;
  19815. endOpenTag(end);
  19816. if (stack[0] && stack[0].tag === name) {
  19817. onCloseTag(stack.shift(), end);
  19818. }
  19819. },
  19820. onattribname(start, end) {
  19821. currentProp = {
  19822. type: 6,
  19823. name: getSlice(start, end),
  19824. nameLoc: getLoc(start, end),
  19825. value: void 0,
  19826. loc: getLoc(start)
  19827. };
  19828. },
  19829. ondirname(start, end) {
  19830. const raw = getSlice(start, end);
  19831. const name = raw === "." || raw === ":" ? "bind" : raw === "@" ? "on" : raw === "#" ? "slot" : raw.slice(2);
  19832. if (!inVPre && name === "") {
  19833. emitError(26, start);
  19834. }
  19835. if (inVPre || name === "") {
  19836. currentProp = {
  19837. type: 6,
  19838. name: raw,
  19839. nameLoc: getLoc(start, end),
  19840. value: void 0,
  19841. loc: getLoc(start)
  19842. };
  19843. } else {
  19844. currentProp = {
  19845. type: 7,
  19846. name,
  19847. rawName: raw,
  19848. exp: void 0,
  19849. arg: void 0,
  19850. modifiers: raw === "." ? [createSimpleExpression("prop")] : [],
  19851. loc: getLoc(start)
  19852. };
  19853. if (name === "pre") {
  19854. inVPre = tokenizer.inVPre = true;
  19855. currentVPreBoundary = currentOpenTag;
  19856. const props = currentOpenTag.props;
  19857. for (let i = 0; i < props.length; i++) {
  19858. if (props[i].type === 7) {
  19859. props[i] = dirToAttr(props[i]);
  19860. }
  19861. }
  19862. }
  19863. }
  19864. },
  19865. ondirarg(start, end) {
  19866. if (start === end) return;
  19867. const arg = getSlice(start, end);
  19868. if (inVPre && !isVPre(currentProp)) {
  19869. currentProp.name += arg;
  19870. setLocEnd(currentProp.nameLoc, end);
  19871. } else {
  19872. const isStatic = arg[0] !== `[`;
  19873. currentProp.arg = createExp(
  19874. isStatic ? arg : arg.slice(1, -1),
  19875. isStatic,
  19876. getLoc(start, end),
  19877. isStatic ? 3 : 0
  19878. );
  19879. }
  19880. },
  19881. ondirmodifier(start, end) {
  19882. const mod = getSlice(start, end);
  19883. if (inVPre && !isVPre(currentProp)) {
  19884. currentProp.name += "." + mod;
  19885. setLocEnd(currentProp.nameLoc, end);
  19886. } else if (currentProp.name === "slot") {
  19887. const arg = currentProp.arg;
  19888. if (arg) {
  19889. arg.content += "." + mod;
  19890. setLocEnd(arg.loc, end);
  19891. }
  19892. } else {
  19893. const exp = createSimpleExpression(mod, true, getLoc(start, end));
  19894. currentProp.modifiers.push(exp);
  19895. }
  19896. },
  19897. onattribdata(start, end) {
  19898. currentAttrValue += getSlice(start, end);
  19899. if (currentAttrStartIndex < 0) currentAttrStartIndex = start;
  19900. currentAttrEndIndex = end;
  19901. },
  19902. onattribentity(char, start, end) {
  19903. currentAttrValue += char;
  19904. if (currentAttrStartIndex < 0) currentAttrStartIndex = start;
  19905. currentAttrEndIndex = end;
  19906. },
  19907. onattribnameend(end) {
  19908. const start = currentProp.loc.start.offset;
  19909. const name = getSlice(start, end);
  19910. if (currentProp.type === 7) {
  19911. currentProp.rawName = name;
  19912. }
  19913. if (currentOpenTag.props.some(
  19914. (p) => (p.type === 7 ? p.rawName : p.name) === name
  19915. )) {
  19916. emitError(2, start);
  19917. }
  19918. },
  19919. onattribend(quote, end) {
  19920. if (currentOpenTag && currentProp) {
  19921. setLocEnd(currentProp.loc, end);
  19922. if (quote !== 0) {
  19923. if (currentProp.type === 6) {
  19924. if (currentProp.name === "class") {
  19925. currentAttrValue = condense(currentAttrValue).trim();
  19926. }
  19927. if (quote === 1 && !currentAttrValue) {
  19928. emitError(13, end);
  19929. }
  19930. currentProp.value = {
  19931. type: 2,
  19932. content: currentAttrValue,
  19933. loc: quote === 1 ? getLoc(currentAttrStartIndex, currentAttrEndIndex) : getLoc(currentAttrStartIndex - 1, currentAttrEndIndex + 1)
  19934. };
  19935. if (tokenizer.inSFCRoot && currentOpenTag.tag === "template" && currentProp.name === "lang" && currentAttrValue && currentAttrValue !== "html") {
  19936. tokenizer.enterRCDATA(toCharCodes(`</template`), 0);
  19937. }
  19938. } else {
  19939. let expParseMode = 0 /* Normal */;
  19940. {
  19941. if (currentProp.name === "for") {
  19942. expParseMode = 3 /* Skip */;
  19943. } else if (currentProp.name === "slot") {
  19944. expParseMode = 1 /* Params */;
  19945. } else if (currentProp.name === "on" && currentAttrValue.includes(";")) {
  19946. expParseMode = 2 /* Statements */;
  19947. }
  19948. }
  19949. currentProp.exp = createExp(
  19950. currentAttrValue,
  19951. false,
  19952. getLoc(currentAttrStartIndex, currentAttrEndIndex),
  19953. 0,
  19954. expParseMode
  19955. );
  19956. if (currentProp.name === "for") {
  19957. currentProp.forParseResult = parseForExpression(currentProp.exp);
  19958. }
  19959. }
  19960. }
  19961. if (currentProp.type !== 7 || currentProp.name !== "pre") {
  19962. currentOpenTag.props.push(currentProp);
  19963. }
  19964. }
  19965. currentAttrValue = "";
  19966. currentAttrStartIndex = currentAttrEndIndex = -1;
  19967. },
  19968. oncomment(start, end) {
  19969. if (currentOptions.comments) {
  19970. addNode({
  19971. type: 3,
  19972. content: getSlice(start, end),
  19973. loc: getLoc(start - 4, end + 3)
  19974. });
  19975. }
  19976. },
  19977. onend() {
  19978. const end = currentInput.length;
  19979. if (tokenizer.state !== 1) {
  19980. switch (tokenizer.state) {
  19981. case 5:
  19982. case 8:
  19983. emitError(5, end);
  19984. break;
  19985. case 3:
  19986. case 4:
  19987. emitError(
  19988. 25,
  19989. tokenizer.sectionStart
  19990. );
  19991. break;
  19992. case 28:
  19993. if (tokenizer.currentSequence === Sequences.CdataEnd) {
  19994. emitError(6, end);
  19995. } else {
  19996. emitError(7, end);
  19997. }
  19998. break;
  19999. case 6:
  20000. case 7:
  20001. case 9:
  20002. case 11:
  20003. case 12:
  20004. case 13:
  20005. case 14:
  20006. case 15:
  20007. case 16:
  20008. case 17:
  20009. case 18:
  20010. case 19:
  20011. // "
  20012. case 20:
  20013. // '
  20014. case 21:
  20015. emitError(9, end);
  20016. break;
  20017. }
  20018. }
  20019. for (let index = 0; index < stack.length; index++) {
  20020. onCloseTag(stack[index], end - 1);
  20021. emitError(24, stack[index].loc.start.offset);
  20022. }
  20023. },
  20024. oncdata(start, end) {
  20025. if ((stack[0] ? stack[0].ns : currentOptions.ns) !== 0) {
  20026. onText(getSlice(start, end), start, end);
  20027. } else {
  20028. emitError(1, start - 9);
  20029. }
  20030. },
  20031. onprocessinginstruction(start) {
  20032. if ((stack[0] ? stack[0].ns : currentOptions.ns) === 0) {
  20033. emitError(
  20034. 21,
  20035. start - 1
  20036. );
  20037. }
  20038. }
  20039. });
  20040. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  20041. const stripParensRE = /^\(|\)$/g;
  20042. function parseForExpression(input) {
  20043. const loc = input.loc;
  20044. const exp = input.content;
  20045. const inMatch = exp.match(forAliasRE);
  20046. if (!inMatch) return;
  20047. const [, LHS, RHS] = inMatch;
  20048. const createAliasExpression = (content, offset, asParam = false) => {
  20049. const start = loc.start.offset + offset;
  20050. const end = start + content.length;
  20051. return createExp(
  20052. content,
  20053. false,
  20054. getLoc(start, end),
  20055. 0,
  20056. asParam ? 1 /* Params */ : 0 /* Normal */
  20057. );
  20058. };
  20059. const result = {
  20060. source: createAliasExpression(RHS.trim(), exp.indexOf(RHS, LHS.length)),
  20061. value: void 0,
  20062. key: void 0,
  20063. index: void 0,
  20064. finalized: false
  20065. };
  20066. let valueContent = LHS.trim().replace(stripParensRE, "").trim();
  20067. const trimmedOffset = LHS.indexOf(valueContent);
  20068. const iteratorMatch = valueContent.match(forIteratorRE);
  20069. if (iteratorMatch) {
  20070. valueContent = valueContent.replace(forIteratorRE, "").trim();
  20071. const keyContent = iteratorMatch[1].trim();
  20072. let keyOffset;
  20073. if (keyContent) {
  20074. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  20075. result.key = createAliasExpression(keyContent, keyOffset, true);
  20076. }
  20077. if (iteratorMatch[2]) {
  20078. const indexContent = iteratorMatch[2].trim();
  20079. if (indexContent) {
  20080. result.index = createAliasExpression(
  20081. indexContent,
  20082. exp.indexOf(
  20083. indexContent,
  20084. result.key ? keyOffset + keyContent.length : trimmedOffset + valueContent.length
  20085. ),
  20086. true
  20087. );
  20088. }
  20089. }
  20090. }
  20091. if (valueContent) {
  20092. result.value = createAliasExpression(valueContent, trimmedOffset, true);
  20093. }
  20094. return result;
  20095. }
  20096. function getSlice(start, end) {
  20097. return currentInput.slice(start, end);
  20098. }
  20099. function endOpenTag(end) {
  20100. if (tokenizer.inSFCRoot) {
  20101. currentOpenTag.innerLoc = getLoc(end + 1, end + 1);
  20102. }
  20103. addNode(currentOpenTag);
  20104. const { tag, ns } = currentOpenTag;
  20105. if (ns === 0 && currentOptions.isPreTag(tag)) {
  20106. inPre++;
  20107. }
  20108. if (currentOptions.isVoidTag(tag)) {
  20109. onCloseTag(currentOpenTag, end);
  20110. } else {
  20111. stack.unshift(currentOpenTag);
  20112. if (ns === 1 || ns === 2) {
  20113. tokenizer.inXML = true;
  20114. }
  20115. }
  20116. currentOpenTag = null;
  20117. }
  20118. function onText(content, start, end) {
  20119. const parent = stack[0] || currentRoot;
  20120. const lastNode = parent.children[parent.children.length - 1];
  20121. if (lastNode && lastNode.type === 2) {
  20122. lastNode.content += content;
  20123. setLocEnd(lastNode.loc, end);
  20124. } else {
  20125. parent.children.push({
  20126. type: 2,
  20127. content,
  20128. loc: getLoc(start, end)
  20129. });
  20130. }
  20131. }
  20132. function onCloseTag(el, end, isImplied = false) {
  20133. if (isImplied) {
  20134. setLocEnd(el.loc, backTrack(end, 60));
  20135. } else {
  20136. setLocEnd(el.loc, lookAhead(end, 62) + 1);
  20137. }
  20138. if (tokenizer.inSFCRoot) {
  20139. if (el.children.length) {
  20140. el.innerLoc.end = extend({}, el.children[el.children.length - 1].loc.end);
  20141. } else {
  20142. el.innerLoc.end = extend({}, el.innerLoc.start);
  20143. }
  20144. el.innerLoc.source = getSlice(
  20145. el.innerLoc.start.offset,
  20146. el.innerLoc.end.offset
  20147. );
  20148. }
  20149. const { tag, ns, children } = el;
  20150. if (!inVPre) {
  20151. if (tag === "slot") {
  20152. el.tagType = 2;
  20153. } else if (isFragmentTemplate(el)) {
  20154. el.tagType = 3;
  20155. } else if (isComponent(el)) {
  20156. el.tagType = 1;
  20157. }
  20158. }
  20159. if (!tokenizer.inRCDATA) {
  20160. el.children = condenseWhitespace(children);
  20161. }
  20162. if (ns === 0 && currentOptions.isIgnoreNewlineTag(tag)) {
  20163. const first = children[0];
  20164. if (first && first.type === 2) {
  20165. first.content = first.content.replace(/^\r?\n/, "");
  20166. }
  20167. }
  20168. if (ns === 0 && currentOptions.isPreTag(tag)) {
  20169. inPre--;
  20170. }
  20171. if (currentVPreBoundary === el) {
  20172. inVPre = tokenizer.inVPre = false;
  20173. currentVPreBoundary = null;
  20174. }
  20175. if (tokenizer.inXML && (stack[0] ? stack[0].ns : currentOptions.ns) === 0) {
  20176. tokenizer.inXML = false;
  20177. }
  20178. }
  20179. function lookAhead(index, c) {
  20180. let i = index;
  20181. while (currentInput.charCodeAt(i) !== c && i < currentInput.length - 1) i++;
  20182. return i;
  20183. }
  20184. function backTrack(index, c) {
  20185. let i = index;
  20186. while (currentInput.charCodeAt(i) !== c && i >= 0) i--;
  20187. return i;
  20188. }
  20189. const specialTemplateDir = /* @__PURE__ */ new Set(["if", "else", "else-if", "for", "slot"]);
  20190. function isFragmentTemplate({ tag, props }) {
  20191. if (tag === "template") {
  20192. for (let i = 0; i < props.length; i++) {
  20193. if (props[i].type === 7 && specialTemplateDir.has(props[i].name)) {
  20194. return true;
  20195. }
  20196. }
  20197. }
  20198. return false;
  20199. }
  20200. function isComponent({ tag, props }) {
  20201. if (currentOptions.isCustomElement(tag)) {
  20202. return false;
  20203. }
  20204. if (tag === "component" || isUpperCase(tag.charCodeAt(0)) || isCoreComponent(tag) || currentOptions.isBuiltInComponent && currentOptions.isBuiltInComponent(tag) || currentOptions.isNativeTag && !currentOptions.isNativeTag(tag)) {
  20205. return true;
  20206. }
  20207. for (let i = 0; i < props.length; i++) {
  20208. const p = props[i];
  20209. if (p.type === 6) {
  20210. if (p.name === "is" && p.value) {
  20211. if (p.value.content.startsWith("vue:")) {
  20212. return true;
  20213. }
  20214. }
  20215. }
  20216. }
  20217. return false;
  20218. }
  20219. function isUpperCase(c) {
  20220. return c > 64 && c < 91;
  20221. }
  20222. const windowsNewlineRE = /\r\n/g;
  20223. function condenseWhitespace(nodes) {
  20224. const shouldCondense = currentOptions.whitespace !== "preserve";
  20225. let removedWhitespace = false;
  20226. for (let i = 0; i < nodes.length; i++) {
  20227. const node = nodes[i];
  20228. if (node.type === 2) {
  20229. if (!inPre) {
  20230. if (isAllWhitespace(node.content)) {
  20231. const prev = nodes[i - 1] && nodes[i - 1].type;
  20232. const next = nodes[i + 1] && nodes[i + 1].type;
  20233. if (!prev || !next || shouldCondense && (prev === 3 && (next === 3 || next === 1) || prev === 1 && (next === 3 || next === 1 && hasNewlineChar(node.content)))) {
  20234. removedWhitespace = true;
  20235. nodes[i] = null;
  20236. } else {
  20237. node.content = " ";
  20238. }
  20239. } else if (shouldCondense) {
  20240. node.content = condense(node.content);
  20241. }
  20242. } else {
  20243. node.content = node.content.replace(windowsNewlineRE, "\n");
  20244. }
  20245. }
  20246. }
  20247. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  20248. }
  20249. function hasNewlineChar(str) {
  20250. for (let i = 0; i < str.length; i++) {
  20251. const c = str.charCodeAt(i);
  20252. if (c === 10 || c === 13) {
  20253. return true;
  20254. }
  20255. }
  20256. return false;
  20257. }
  20258. function condense(str) {
  20259. let ret = "";
  20260. let prevCharIsWhitespace = false;
  20261. for (let i = 0; i < str.length; i++) {
  20262. if (isWhitespace(str.charCodeAt(i))) {
  20263. if (!prevCharIsWhitespace) {
  20264. ret += " ";
  20265. prevCharIsWhitespace = true;
  20266. }
  20267. } else {
  20268. ret += str[i];
  20269. prevCharIsWhitespace = false;
  20270. }
  20271. }
  20272. return ret;
  20273. }
  20274. function addNode(node) {
  20275. (stack[0] || currentRoot).children.push(node);
  20276. }
  20277. function getLoc(start, end) {
  20278. return {
  20279. start: tokenizer.getPos(start),
  20280. // @ts-expect-error allow late attachment
  20281. end: end == null ? end : tokenizer.getPos(end),
  20282. // @ts-expect-error allow late attachment
  20283. source: end == null ? end : getSlice(start, end)
  20284. };
  20285. }
  20286. function cloneLoc(loc) {
  20287. return getLoc(loc.start.offset, loc.end.offset);
  20288. }
  20289. function setLocEnd(loc, end) {
  20290. loc.end = tokenizer.getPos(end);
  20291. loc.source = getSlice(loc.start.offset, end);
  20292. }
  20293. function dirToAttr(dir) {
  20294. const attr = {
  20295. type: 6,
  20296. name: dir.rawName,
  20297. nameLoc: getLoc(
  20298. dir.loc.start.offset,
  20299. dir.loc.start.offset + dir.rawName.length
  20300. ),
  20301. value: void 0,
  20302. loc: dir.loc
  20303. };
  20304. if (dir.exp) {
  20305. const loc = dir.exp.loc;
  20306. if (loc.end.offset < dir.loc.end.offset) {
  20307. loc.start.offset--;
  20308. loc.start.column--;
  20309. loc.end.offset++;
  20310. loc.end.column++;
  20311. }
  20312. attr.value = {
  20313. type: 2,
  20314. content: dir.exp.content,
  20315. loc
  20316. };
  20317. }
  20318. return attr;
  20319. }
  20320. function createExp(content, isStatic = false, loc, constType = 0, parseMode = 0 /* Normal */) {
  20321. const exp = createSimpleExpression(content, isStatic, loc, constType);
  20322. if (!isStatic && currentOptions.prefixIdentifiers && parseMode !== 3 /* Skip */ && content.trim()) {
  20323. if (isSimpleIdentifier(content)) {
  20324. exp.ast = null;
  20325. return exp;
  20326. }
  20327. try {
  20328. const plugins = currentOptions.expressionPlugins;
  20329. const options = {
  20330. plugins: plugins ? [...plugins, "typescript"] : ["typescript"]
  20331. };
  20332. if (parseMode === 2 /* Statements */) {
  20333. exp.ast = libExports.parse(` ${content} `, options).program;
  20334. } else if (parseMode === 1 /* Params */) {
  20335. exp.ast = libExports.parseExpression(`(${content})=>{}`, options);
  20336. } else {
  20337. exp.ast = libExports.parseExpression(`(${content})`, options);
  20338. }
  20339. } catch (e) {
  20340. exp.ast = false;
  20341. emitError(46, loc.start.offset, e.message);
  20342. }
  20343. }
  20344. return exp;
  20345. }
  20346. function emitError(code, index, message) {
  20347. currentOptions.onError(
  20348. createCompilerError(code, getLoc(index, index), void 0, message)
  20349. );
  20350. }
  20351. function reset() {
  20352. tokenizer.reset();
  20353. currentOpenTag = null;
  20354. currentProp = null;
  20355. currentAttrValue = "";
  20356. currentAttrStartIndex = -1;
  20357. currentAttrEndIndex = -1;
  20358. stack.length = 0;
  20359. }
  20360. function baseParse(input, options) {
  20361. reset();
  20362. currentInput = input;
  20363. currentOptions = extend({}, defaultParserOptions);
  20364. if (options) {
  20365. let key;
  20366. for (key in options) {
  20367. if (options[key] != null) {
  20368. currentOptions[key] = options[key];
  20369. }
  20370. }
  20371. }
  20372. {
  20373. if (currentOptions.decodeEntities) {
  20374. console.warn(
  20375. `[@vue/compiler-core] decodeEntities option is passed but will be ignored in non-browser builds.`
  20376. );
  20377. }
  20378. }
  20379. tokenizer.mode = currentOptions.parseMode === "html" ? 1 : currentOptions.parseMode === "sfc" ? 2 : 0;
  20380. tokenizer.inXML = currentOptions.ns === 1 || currentOptions.ns === 2;
  20381. const delimiters = options && options.delimiters;
  20382. if (delimiters) {
  20383. tokenizer.delimiterOpen = toCharCodes(delimiters[0]);
  20384. tokenizer.delimiterClose = toCharCodes(delimiters[1]);
  20385. }
  20386. const root = currentRoot = createRoot([], input);
  20387. tokenizer.parse(currentInput);
  20388. root.loc = getLoc(0, input.length);
  20389. root.children = condenseWhitespace(root.children);
  20390. currentRoot = null;
  20391. return root;
  20392. }
  20393. function cacheStatic(root, context) {
  20394. walk$1(
  20395. root,
  20396. void 0,
  20397. context,
  20398. // Root node is unfortunately non-hoistable due to potential parent
  20399. // fallthrough attributes.
  20400. !!getSingleElementRoot(root)
  20401. );
  20402. }
  20403. function getSingleElementRoot(root) {
  20404. const children = root.children.filter((x) => x.type !== 3);
  20405. return children.length === 1 && children[0].type === 1 && !isSlotOutlet(children[0]) ? children[0] : null;
  20406. }
  20407. function walk$1(node, parent, context, doNotHoistNode = false, inFor = false) {
  20408. const { children } = node;
  20409. const toCache = [];
  20410. for (let i = 0; i < children.length; i++) {
  20411. const child = children[i];
  20412. if (child.type === 1 && child.tagType === 0) {
  20413. const constantType = doNotHoistNode ? 0 : getConstantType(child, context);
  20414. if (constantType > 0) {
  20415. if (constantType >= 2) {
  20416. child.codegenNode.patchFlag = -1;
  20417. toCache.push(child);
  20418. continue;
  20419. }
  20420. } else {
  20421. const codegenNode = child.codegenNode;
  20422. if (codegenNode.type === 13) {
  20423. const flag = codegenNode.patchFlag;
  20424. if ((flag === void 0 || flag === 512 || flag === 1) && getGeneratedPropsConstantType(child, context) >= 2) {
  20425. const props = getNodeProps(child);
  20426. if (props) {
  20427. codegenNode.props = context.hoist(props);
  20428. }
  20429. }
  20430. if (codegenNode.dynamicProps) {
  20431. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  20432. }
  20433. }
  20434. }
  20435. } else if (child.type === 12) {
  20436. const constantType = doNotHoistNode ? 0 : getConstantType(child, context);
  20437. if (constantType >= 2) {
  20438. if (child.codegenNode.type === 14 && child.codegenNode.arguments.length > 0) {
  20439. child.codegenNode.arguments.push(
  20440. -1 + (` /* ${PatchFlagNames[-1]} */` )
  20441. );
  20442. }
  20443. toCache.push(child);
  20444. continue;
  20445. }
  20446. }
  20447. if (child.type === 1) {
  20448. const isComponent = child.tagType === 1;
  20449. if (isComponent) {
  20450. context.scopes.vSlot++;
  20451. }
  20452. walk$1(child, node, context, false, inFor);
  20453. if (isComponent) {
  20454. context.scopes.vSlot--;
  20455. }
  20456. } else if (child.type === 11) {
  20457. walk$1(child, node, context, child.children.length === 1, true);
  20458. } else if (child.type === 9) {
  20459. for (let i2 = 0; i2 < child.branches.length; i2++) {
  20460. walk$1(
  20461. child.branches[i2],
  20462. node,
  20463. context,
  20464. child.branches[i2].children.length === 1,
  20465. inFor
  20466. );
  20467. }
  20468. }
  20469. }
  20470. let cachedAsArray = false;
  20471. if (toCache.length === children.length && node.type === 1) {
  20472. if (node.tagType === 0 && node.codegenNode && node.codegenNode.type === 13 && isArray$3(node.codegenNode.children)) {
  20473. node.codegenNode.children = getCacheExpression(
  20474. createArrayExpression(node.codegenNode.children)
  20475. );
  20476. cachedAsArray = true;
  20477. } else if (node.tagType === 1 && node.codegenNode && node.codegenNode.type === 13 && node.codegenNode.children && !isArray$3(node.codegenNode.children) && node.codegenNode.children.type === 15) {
  20478. const slot = getSlotNode(node.codegenNode, "default");
  20479. if (slot) {
  20480. slot.returns = getCacheExpression(
  20481. createArrayExpression(slot.returns)
  20482. );
  20483. cachedAsArray = true;
  20484. }
  20485. } else if (node.tagType === 3 && parent && parent.type === 1 && parent.tagType === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !isArray$3(parent.codegenNode.children) && parent.codegenNode.children.type === 15) {
  20486. const slotName = findDir(node, "slot", true);
  20487. const slot = slotName && slotName.arg && getSlotNode(parent.codegenNode, slotName.arg);
  20488. if (slot) {
  20489. slot.returns = getCacheExpression(
  20490. createArrayExpression(slot.returns)
  20491. );
  20492. cachedAsArray = true;
  20493. }
  20494. }
  20495. }
  20496. if (!cachedAsArray) {
  20497. for (const child of toCache) {
  20498. child.codegenNode = context.cache(child.codegenNode);
  20499. }
  20500. }
  20501. function getCacheExpression(value) {
  20502. const exp = context.cache(value);
  20503. exp.needArraySpread = true;
  20504. return exp;
  20505. }
  20506. function getSlotNode(node2, name) {
  20507. if (node2.children && !isArray$3(node2.children) && node2.children.type === 15) {
  20508. const slot = node2.children.properties.find(
  20509. (p) => p.key === name || p.key.content === name
  20510. );
  20511. return slot && slot.value;
  20512. }
  20513. }
  20514. if (toCache.length && context.transformHoist) {
  20515. context.transformHoist(children, context, node);
  20516. }
  20517. }
  20518. function getConstantType(node, context) {
  20519. const { constantCache } = context;
  20520. switch (node.type) {
  20521. case 1:
  20522. if (node.tagType !== 0) {
  20523. return 0;
  20524. }
  20525. const cached = constantCache.get(node);
  20526. if (cached !== void 0) {
  20527. return cached;
  20528. }
  20529. const codegenNode = node.codegenNode;
  20530. if (codegenNode.type !== 13) {
  20531. return 0;
  20532. }
  20533. if (codegenNode.isBlock && node.tag !== "svg" && node.tag !== "foreignObject" && node.tag !== "math") {
  20534. return 0;
  20535. }
  20536. if (codegenNode.patchFlag === void 0) {
  20537. let returnType2 = 3;
  20538. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  20539. if (generatedPropsType === 0) {
  20540. constantCache.set(node, 0);
  20541. return 0;
  20542. }
  20543. if (generatedPropsType < returnType2) {
  20544. returnType2 = generatedPropsType;
  20545. }
  20546. for (let i = 0; i < node.children.length; i++) {
  20547. const childType = getConstantType(node.children[i], context);
  20548. if (childType === 0) {
  20549. constantCache.set(node, 0);
  20550. return 0;
  20551. }
  20552. if (childType < returnType2) {
  20553. returnType2 = childType;
  20554. }
  20555. }
  20556. if (returnType2 > 1) {
  20557. for (let i = 0; i < node.props.length; i++) {
  20558. const p = node.props[i];
  20559. if (p.type === 7 && p.name === "bind" && p.exp) {
  20560. const expType = getConstantType(p.exp, context);
  20561. if (expType === 0) {
  20562. constantCache.set(node, 0);
  20563. return 0;
  20564. }
  20565. if (expType < returnType2) {
  20566. returnType2 = expType;
  20567. }
  20568. }
  20569. }
  20570. }
  20571. if (codegenNode.isBlock) {
  20572. for (let i = 0; i < node.props.length; i++) {
  20573. const p = node.props[i];
  20574. if (p.type === 7) {
  20575. constantCache.set(node, 0);
  20576. return 0;
  20577. }
  20578. }
  20579. context.removeHelper(OPEN_BLOCK);
  20580. context.removeHelper(
  20581. getVNodeBlockHelper(context.inSSR, codegenNode.isComponent)
  20582. );
  20583. codegenNode.isBlock = false;
  20584. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  20585. }
  20586. constantCache.set(node, returnType2);
  20587. return returnType2;
  20588. } else {
  20589. constantCache.set(node, 0);
  20590. return 0;
  20591. }
  20592. case 2:
  20593. case 3:
  20594. return 3;
  20595. case 9:
  20596. case 11:
  20597. case 10:
  20598. return 0;
  20599. case 5:
  20600. case 12:
  20601. return getConstantType(node.content, context);
  20602. case 4:
  20603. return node.constType;
  20604. case 8:
  20605. let returnType = 3;
  20606. for (let i = 0; i < node.children.length; i++) {
  20607. const child = node.children[i];
  20608. if (isString$1(child) || isSymbol$1(child)) {
  20609. continue;
  20610. }
  20611. const childType = getConstantType(child, context);
  20612. if (childType === 0) {
  20613. return 0;
  20614. } else if (childType < returnType) {
  20615. returnType = childType;
  20616. }
  20617. }
  20618. return returnType;
  20619. case 20:
  20620. return 2;
  20621. default:
  20622. return 0;
  20623. }
  20624. }
  20625. const allowHoistedHelperSet = /* @__PURE__ */ new Set([
  20626. NORMALIZE_CLASS,
  20627. NORMALIZE_STYLE,
  20628. NORMALIZE_PROPS,
  20629. GUARD_REACTIVE_PROPS
  20630. ]);
  20631. function getConstantTypeOfHelperCall(value, context) {
  20632. if (value.type === 14 && !isString$1(value.callee) && allowHoistedHelperSet.has(value.callee)) {
  20633. const arg = value.arguments[0];
  20634. if (arg.type === 4) {
  20635. return getConstantType(arg, context);
  20636. } else if (arg.type === 14) {
  20637. return getConstantTypeOfHelperCall(arg, context);
  20638. }
  20639. }
  20640. return 0;
  20641. }
  20642. function getGeneratedPropsConstantType(node, context) {
  20643. let returnType = 3;
  20644. const props = getNodeProps(node);
  20645. if (props && props.type === 15) {
  20646. const { properties } = props;
  20647. for (let i = 0; i < properties.length; i++) {
  20648. const { key, value } = properties[i];
  20649. const keyType = getConstantType(key, context);
  20650. if (keyType === 0) {
  20651. return keyType;
  20652. }
  20653. if (keyType < returnType) {
  20654. returnType = keyType;
  20655. }
  20656. let valueType;
  20657. if (value.type === 4) {
  20658. valueType = getConstantType(value, context);
  20659. } else if (value.type === 14) {
  20660. valueType = getConstantTypeOfHelperCall(value, context);
  20661. } else {
  20662. valueType = 0;
  20663. }
  20664. if (valueType === 0) {
  20665. return valueType;
  20666. }
  20667. if (valueType < returnType) {
  20668. returnType = valueType;
  20669. }
  20670. }
  20671. }
  20672. return returnType;
  20673. }
  20674. function getNodeProps(node) {
  20675. const codegenNode = node.codegenNode;
  20676. if (codegenNode.type === 13) {
  20677. return codegenNode.props;
  20678. }
  20679. }
  20680. function createTransformContext(root, {
  20681. filename = "",
  20682. prefixIdentifiers = false,
  20683. hoistStatic = false,
  20684. hmr = false,
  20685. cacheHandlers = false,
  20686. nodeTransforms = [],
  20687. directiveTransforms = {},
  20688. transformHoist = null,
  20689. isBuiltInComponent = NOOP,
  20690. isCustomElement = NOOP,
  20691. expressionPlugins = [],
  20692. scopeId = null,
  20693. slotted = true,
  20694. ssr = false,
  20695. inSSR = false,
  20696. ssrCssVars = ``,
  20697. bindingMetadata = EMPTY_OBJ,
  20698. inline = false,
  20699. isTS = false,
  20700. onError = defaultOnError,
  20701. onWarn = defaultOnWarn,
  20702. compatConfig
  20703. }) {
  20704. const nameMatch = filename.replace(/\?.*$/, "").match(/([^/\\]+)\.\w+$/);
  20705. const context = {
  20706. // options
  20707. filename,
  20708. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  20709. prefixIdentifiers,
  20710. hoistStatic,
  20711. hmr,
  20712. cacheHandlers,
  20713. nodeTransforms,
  20714. directiveTransforms,
  20715. transformHoist,
  20716. isBuiltInComponent,
  20717. isCustomElement,
  20718. expressionPlugins,
  20719. scopeId,
  20720. slotted,
  20721. ssr,
  20722. inSSR,
  20723. ssrCssVars,
  20724. bindingMetadata,
  20725. inline,
  20726. isTS,
  20727. onError,
  20728. onWarn,
  20729. compatConfig,
  20730. // state
  20731. root,
  20732. helpers: /* @__PURE__ */ new Map(),
  20733. components: /* @__PURE__ */ new Set(),
  20734. directives: /* @__PURE__ */ new Set(),
  20735. hoists: [],
  20736. imports: [],
  20737. cached: [],
  20738. constantCache: /* @__PURE__ */ new WeakMap(),
  20739. vForMemoKeyedNodes: /* @__PURE__ */ new WeakSet(),
  20740. temps: 0,
  20741. identifiers: /* @__PURE__ */ Object.create(null),
  20742. scopes: {
  20743. vFor: 0,
  20744. vSlot: 0,
  20745. vPre: 0,
  20746. vOnce: 0
  20747. },
  20748. parent: null,
  20749. grandParent: null,
  20750. currentNode: root,
  20751. childIndex: 0,
  20752. inVOnce: false,
  20753. // methods
  20754. helper(name) {
  20755. const count = context.helpers.get(name) || 0;
  20756. context.helpers.set(name, count + 1);
  20757. return name;
  20758. },
  20759. removeHelper(name) {
  20760. const count = context.helpers.get(name);
  20761. if (count) {
  20762. const currentCount = count - 1;
  20763. if (!currentCount) {
  20764. context.helpers.delete(name);
  20765. } else {
  20766. context.helpers.set(name, currentCount);
  20767. }
  20768. }
  20769. },
  20770. helperString(name) {
  20771. return `_${helperNameMap[context.helper(name)]}`;
  20772. },
  20773. replaceNode(node) {
  20774. {
  20775. if (!context.currentNode) {
  20776. throw new Error(`Node being replaced is already removed.`);
  20777. }
  20778. if (!context.parent) {
  20779. throw new Error(`Cannot replace root node.`);
  20780. }
  20781. }
  20782. context.parent.children[context.childIndex] = context.currentNode = node;
  20783. },
  20784. removeNode(node) {
  20785. if (!context.parent) {
  20786. throw new Error(`Cannot remove root node.`);
  20787. }
  20788. const list = context.parent.children;
  20789. const removalIndex = node ? list.indexOf(node) : context.currentNode ? context.childIndex : -1;
  20790. if (removalIndex < 0) {
  20791. throw new Error(`node being removed is not a child of current parent`);
  20792. }
  20793. if (!node || node === context.currentNode) {
  20794. context.currentNode = null;
  20795. context.onNodeRemoved();
  20796. } else {
  20797. if (context.childIndex > removalIndex) {
  20798. context.childIndex--;
  20799. context.onNodeRemoved();
  20800. }
  20801. }
  20802. context.parent.children.splice(removalIndex, 1);
  20803. },
  20804. onNodeRemoved: NOOP,
  20805. addIdentifiers(exp) {
  20806. {
  20807. if (isString$1(exp)) {
  20808. addId(exp);
  20809. } else if (exp.identifiers) {
  20810. exp.identifiers.forEach(addId);
  20811. } else if (exp.type === 4) {
  20812. addId(exp.content);
  20813. }
  20814. }
  20815. },
  20816. removeIdentifiers(exp) {
  20817. {
  20818. if (isString$1(exp)) {
  20819. removeId(exp);
  20820. } else if (exp.identifiers) {
  20821. exp.identifiers.forEach(removeId);
  20822. } else if (exp.type === 4) {
  20823. removeId(exp.content);
  20824. }
  20825. }
  20826. },
  20827. hoist(exp) {
  20828. if (isString$1(exp)) exp = createSimpleExpression(exp);
  20829. context.hoists.push(exp);
  20830. const identifier = createSimpleExpression(
  20831. `_hoisted_${context.hoists.length}`,
  20832. false,
  20833. exp.loc,
  20834. 2
  20835. );
  20836. identifier.hoisted = exp;
  20837. return identifier;
  20838. },
  20839. cache(exp, isVNode = false, inVOnce = false) {
  20840. const cacheExp = createCacheExpression(
  20841. context.cached.length,
  20842. exp,
  20843. isVNode,
  20844. inVOnce
  20845. );
  20846. context.cached.push(cacheExp);
  20847. return cacheExp;
  20848. }
  20849. };
  20850. function addId(id) {
  20851. const { identifiers } = context;
  20852. if (identifiers[id] === void 0) {
  20853. identifiers[id] = 0;
  20854. }
  20855. identifiers[id]++;
  20856. }
  20857. function removeId(id) {
  20858. context.identifiers[id]--;
  20859. }
  20860. return context;
  20861. }
  20862. function transform(root, options) {
  20863. const context = createTransformContext(root, options);
  20864. traverseNode(root, context);
  20865. if (options.hoistStatic) {
  20866. cacheStatic(root, context);
  20867. }
  20868. if (!options.ssr) {
  20869. createRootCodegen(root, context);
  20870. }
  20871. root.helpers = /* @__PURE__ */ new Set([...context.helpers.keys()]);
  20872. root.components = [...context.components];
  20873. root.directives = [...context.directives];
  20874. root.imports = context.imports;
  20875. root.hoists = context.hoists;
  20876. root.temps = context.temps;
  20877. root.cached = context.cached;
  20878. root.transformed = true;
  20879. }
  20880. function createRootCodegen(root, context) {
  20881. const { helper } = context;
  20882. const { children } = root;
  20883. if (children.length === 1) {
  20884. const singleElementRootChild = getSingleElementRoot(root);
  20885. if (singleElementRootChild && singleElementRootChild.codegenNode) {
  20886. const codegenNode = singleElementRootChild.codegenNode;
  20887. if (codegenNode.type === 13) {
  20888. convertToBlock(codegenNode, context);
  20889. }
  20890. root.codegenNode = codegenNode;
  20891. } else {
  20892. root.codegenNode = children[0];
  20893. }
  20894. } else if (children.length > 1) {
  20895. let patchFlag = 64;
  20896. if (children.filter((c) => c.type !== 3).length === 1) {
  20897. patchFlag |= 2048;
  20898. }
  20899. root.codegenNode = createVNodeCall(
  20900. context,
  20901. helper(FRAGMENT),
  20902. void 0,
  20903. root.children,
  20904. patchFlag,
  20905. void 0,
  20906. void 0,
  20907. true,
  20908. void 0,
  20909. false
  20910. );
  20911. } else ;
  20912. }
  20913. function traverseChildren(parent, context) {
  20914. let i = 0;
  20915. const nodeRemoved = () => {
  20916. i--;
  20917. };
  20918. for (; i < parent.children.length; i++) {
  20919. const child = parent.children[i];
  20920. if (isString$1(child)) continue;
  20921. context.grandParent = context.parent;
  20922. context.parent = parent;
  20923. context.childIndex = i;
  20924. context.onNodeRemoved = nodeRemoved;
  20925. traverseNode(child, context);
  20926. }
  20927. }
  20928. function traverseNode(node, context) {
  20929. context.currentNode = node;
  20930. const { nodeTransforms } = context;
  20931. const exitFns = [];
  20932. for (let i2 = 0; i2 < nodeTransforms.length; i2++) {
  20933. const onExit = nodeTransforms[i2](node, context);
  20934. if (onExit) {
  20935. if (isArray$3(onExit)) {
  20936. exitFns.push(...onExit);
  20937. } else {
  20938. exitFns.push(onExit);
  20939. }
  20940. }
  20941. if (!context.currentNode) {
  20942. return;
  20943. } else {
  20944. node = context.currentNode;
  20945. }
  20946. }
  20947. switch (node.type) {
  20948. case 3:
  20949. if (!context.ssr) {
  20950. context.helper(CREATE_COMMENT);
  20951. }
  20952. break;
  20953. case 5:
  20954. if (!context.ssr) {
  20955. context.helper(TO_DISPLAY_STRING);
  20956. }
  20957. break;
  20958. // for container types, further traverse downwards
  20959. case 9:
  20960. for (let i2 = 0; i2 < node.branches.length; i2++) {
  20961. traverseNode(node.branches[i2], context);
  20962. }
  20963. break;
  20964. case 10:
  20965. case 11:
  20966. case 1:
  20967. case 0:
  20968. traverseChildren(node, context);
  20969. break;
  20970. }
  20971. context.currentNode = node;
  20972. let i = exitFns.length;
  20973. while (i--) {
  20974. exitFns[i]();
  20975. }
  20976. }
  20977. function createStructuralDirectiveTransform(name, fn) {
  20978. const matches = isString$1(name) ? (n) => n === name : (n) => name.test(n);
  20979. return (node, context) => {
  20980. if (node.type === 1) {
  20981. const { props } = node;
  20982. if (node.tagType === 3 && props.some(isVSlot)) {
  20983. return;
  20984. }
  20985. const exitFns = [];
  20986. for (let i = 0; i < props.length; i++) {
  20987. const prop = props[i];
  20988. if (prop.type === 7 && matches(prop.name)) {
  20989. props.splice(i, 1);
  20990. i--;
  20991. const onExit = fn(node, prop, context);
  20992. if (onExit) exitFns.push(onExit);
  20993. }
  20994. }
  20995. return exitFns;
  20996. }
  20997. };
  20998. }
  20999. var sourceMap$1 = {};
  21000. var sourceMapGenerator$1 = {};
  21001. var base64Vlq$1 = {};
  21002. var base64$1 = {};
  21003. /* -*- Mode: js; js-indent-level: 2; -*- */
  21004. var hasRequiredBase64$1;
  21005. function requireBase64$1 () {
  21006. if (hasRequiredBase64$1) return base64$1;
  21007. hasRequiredBase64$1 = 1;
  21008. /*
  21009. * Copyright 2011 Mozilla Foundation and contributors
  21010. * Licensed under the New BSD license. See LICENSE or:
  21011. * http://opensource.org/licenses/BSD-3-Clause
  21012. */
  21013. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  21014. /**
  21015. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  21016. */
  21017. base64$1.encode = function (number) {
  21018. if (0 <= number && number < intToCharMap.length) {
  21019. return intToCharMap[number];
  21020. }
  21021. throw new TypeError("Must be between 0 and 63: " + number);
  21022. };
  21023. /**
  21024. * Decode a single base 64 character code digit to an integer. Returns -1 on
  21025. * failure.
  21026. */
  21027. base64$1.decode = function (charCode) {
  21028. var bigA = 65; // 'A'
  21029. var bigZ = 90; // 'Z'
  21030. var littleA = 97; // 'a'
  21031. var littleZ = 122; // 'z'
  21032. var zero = 48; // '0'
  21033. var nine = 57; // '9'
  21034. var plus = 43; // '+'
  21035. var slash = 47; // '/'
  21036. var littleOffset = 26;
  21037. var numberOffset = 52;
  21038. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  21039. if (bigA <= charCode && charCode <= bigZ) {
  21040. return (charCode - bigA);
  21041. }
  21042. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  21043. if (littleA <= charCode && charCode <= littleZ) {
  21044. return (charCode - littleA + littleOffset);
  21045. }
  21046. // 52 - 61: 0123456789
  21047. if (zero <= charCode && charCode <= nine) {
  21048. return (charCode - zero + numberOffset);
  21049. }
  21050. // 62: +
  21051. if (charCode == plus) {
  21052. return 62;
  21053. }
  21054. // 63: /
  21055. if (charCode == slash) {
  21056. return 63;
  21057. }
  21058. // Invalid base64 digit.
  21059. return -1;
  21060. };
  21061. return base64$1;
  21062. }
  21063. /* -*- Mode: js; js-indent-level: 2; -*- */
  21064. var hasRequiredBase64Vlq$1;
  21065. function requireBase64Vlq$1 () {
  21066. if (hasRequiredBase64Vlq$1) return base64Vlq$1;
  21067. hasRequiredBase64Vlq$1 = 1;
  21068. /*
  21069. * Copyright 2011 Mozilla Foundation and contributors
  21070. * Licensed under the New BSD license. See LICENSE or:
  21071. * http://opensource.org/licenses/BSD-3-Clause
  21072. *
  21073. * Based on the Base 64 VLQ implementation in Closure Compiler:
  21074. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  21075. *
  21076. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  21077. * Redistribution and use in source and binary forms, with or without
  21078. * modification, are permitted provided that the following conditions are
  21079. * met:
  21080. *
  21081. * * Redistributions of source code must retain the above copyright
  21082. * notice, this list of conditions and the following disclaimer.
  21083. * * Redistributions in binary form must reproduce the above
  21084. * copyright notice, this list of conditions and the following
  21085. * disclaimer in the documentation and/or other materials provided
  21086. * with the distribution.
  21087. * * Neither the name of Google Inc. nor the names of its
  21088. * contributors may be used to endorse or promote products derived
  21089. * from this software without specific prior written permission.
  21090. *
  21091. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21092. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21093. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21094. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21095. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  21096. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  21097. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21098. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21099. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  21100. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  21101. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  21102. */
  21103. var base64 = /*@__PURE__*/ requireBase64$1();
  21104. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  21105. // length quantities we use in the source map spec, the first bit is the sign,
  21106. // the next four bits are the actual value, and the 6th bit is the
  21107. // continuation bit. The continuation bit tells us whether there are more
  21108. // digits in this value following this digit.
  21109. //
  21110. // Continuation
  21111. // | Sign
  21112. // | |
  21113. // V V
  21114. // 101011
  21115. var VLQ_BASE_SHIFT = 5;
  21116. // binary: 100000
  21117. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  21118. // binary: 011111
  21119. var VLQ_BASE_MASK = VLQ_BASE - 1;
  21120. // binary: 100000
  21121. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  21122. /**
  21123. * Converts from a two-complement value to a value where the sign bit is
  21124. * placed in the least significant bit. For example, as decimals:
  21125. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  21126. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  21127. */
  21128. function toVLQSigned(aValue) {
  21129. return aValue < 0
  21130. ? ((-aValue) << 1) + 1
  21131. : (aValue << 1) + 0;
  21132. }
  21133. /**
  21134. * Converts to a two-complement value from a value where the sign bit is
  21135. * placed in the least significant bit. For example, as decimals:
  21136. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  21137. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  21138. */
  21139. function fromVLQSigned(aValue) {
  21140. var isNegative = (aValue & 1) === 1;
  21141. var shifted = aValue >> 1;
  21142. return isNegative
  21143. ? -shifted
  21144. : shifted;
  21145. }
  21146. /**
  21147. * Returns the base 64 VLQ encoded value.
  21148. */
  21149. base64Vlq$1.encode = function base64VLQ_encode(aValue) {
  21150. var encoded = "";
  21151. var digit;
  21152. var vlq = toVLQSigned(aValue);
  21153. do {
  21154. digit = vlq & VLQ_BASE_MASK;
  21155. vlq >>>= VLQ_BASE_SHIFT;
  21156. if (vlq > 0) {
  21157. // There are still more digits in this value, so we must make sure the
  21158. // continuation bit is marked.
  21159. digit |= VLQ_CONTINUATION_BIT;
  21160. }
  21161. encoded += base64.encode(digit);
  21162. } while (vlq > 0);
  21163. return encoded;
  21164. };
  21165. /**
  21166. * Decodes the next base 64 VLQ value from the given string and returns the
  21167. * value and the rest of the string via the out parameter.
  21168. */
  21169. base64Vlq$1.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  21170. var strLen = aStr.length;
  21171. var result = 0;
  21172. var shift = 0;
  21173. var continuation, digit;
  21174. do {
  21175. if (aIndex >= strLen) {
  21176. throw new Error("Expected more digits in base 64 VLQ value.");
  21177. }
  21178. digit = base64.decode(aStr.charCodeAt(aIndex++));
  21179. if (digit === -1) {
  21180. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  21181. }
  21182. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  21183. digit &= VLQ_BASE_MASK;
  21184. result = result + (digit << shift);
  21185. shift += VLQ_BASE_SHIFT;
  21186. } while (continuation);
  21187. aOutParam.value = fromVLQSigned(result);
  21188. aOutParam.rest = aIndex;
  21189. };
  21190. return base64Vlq$1;
  21191. }
  21192. var util$2 = {};
  21193. /* -*- Mode: js; js-indent-level: 2; -*- */
  21194. var hasRequiredUtil$2;
  21195. function requireUtil$2 () {
  21196. if (hasRequiredUtil$2) return util$2;
  21197. hasRequiredUtil$2 = 1;
  21198. (function (exports) {
  21199. /*
  21200. * Copyright 2011 Mozilla Foundation and contributors
  21201. * Licensed under the New BSD license. See LICENSE or:
  21202. * http://opensource.org/licenses/BSD-3-Clause
  21203. */
  21204. /**
  21205. * This is a helper function for getting values from parameter/options
  21206. * objects.
  21207. *
  21208. * @param args The object we are extracting values from
  21209. * @param name The name of the property we are getting.
  21210. * @param defaultValue An optional value to return if the property is missing
  21211. * from the object. If this is not specified and the property is missing, an
  21212. * error will be thrown.
  21213. */
  21214. function getArg(aArgs, aName, aDefaultValue) {
  21215. if (aName in aArgs) {
  21216. return aArgs[aName];
  21217. } else if (arguments.length === 3) {
  21218. return aDefaultValue;
  21219. } else {
  21220. throw new Error('"' + aName + '" is a required argument.');
  21221. }
  21222. }
  21223. exports.getArg = getArg;
  21224. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  21225. var dataUrlRegexp = /^data:.+\,.+$/;
  21226. function urlParse(aUrl) {
  21227. var match = aUrl.match(urlRegexp);
  21228. if (!match) {
  21229. return null;
  21230. }
  21231. return {
  21232. scheme: match[1],
  21233. auth: match[2],
  21234. host: match[3],
  21235. port: match[4],
  21236. path: match[5]
  21237. };
  21238. }
  21239. exports.urlParse = urlParse;
  21240. function urlGenerate(aParsedUrl) {
  21241. var url = '';
  21242. if (aParsedUrl.scheme) {
  21243. url += aParsedUrl.scheme + ':';
  21244. }
  21245. url += '//';
  21246. if (aParsedUrl.auth) {
  21247. url += aParsedUrl.auth + '@';
  21248. }
  21249. if (aParsedUrl.host) {
  21250. url += aParsedUrl.host;
  21251. }
  21252. if (aParsedUrl.port) {
  21253. url += ":" + aParsedUrl.port;
  21254. }
  21255. if (aParsedUrl.path) {
  21256. url += aParsedUrl.path;
  21257. }
  21258. return url;
  21259. }
  21260. exports.urlGenerate = urlGenerate;
  21261. var MAX_CACHED_INPUTS = 32;
  21262. /**
  21263. * Takes some function `f(input) -> result` and returns a memoized version of
  21264. * `f`.
  21265. *
  21266. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  21267. * memoization is a dumb-simple, linear least-recently-used cache.
  21268. */
  21269. function lruMemoize(f) {
  21270. var cache = [];
  21271. return function(input) {
  21272. for (var i = 0; i < cache.length; i++) {
  21273. if (cache[i].input === input) {
  21274. var temp = cache[0];
  21275. cache[0] = cache[i];
  21276. cache[i] = temp;
  21277. return cache[0].result;
  21278. }
  21279. }
  21280. var result = f(input);
  21281. cache.unshift({
  21282. input,
  21283. result,
  21284. });
  21285. if (cache.length > MAX_CACHED_INPUTS) {
  21286. cache.pop();
  21287. }
  21288. return result;
  21289. };
  21290. }
  21291. /**
  21292. * Normalizes a path, or the path portion of a URL:
  21293. *
  21294. * - Replaces consecutive slashes with one slash.
  21295. * - Removes unnecessary '.' parts.
  21296. * - Removes unnecessary '<dir>/..' parts.
  21297. *
  21298. * Based on code in the Node.js 'path' core module.
  21299. *
  21300. * @param aPath The path or url to normalize.
  21301. */
  21302. var normalize = lruMemoize(function normalize(aPath) {
  21303. var path = aPath;
  21304. var url = urlParse(aPath);
  21305. if (url) {
  21306. if (!url.path) {
  21307. return aPath;
  21308. }
  21309. path = url.path;
  21310. }
  21311. var isAbsolute = exports.isAbsolute(path);
  21312. // Split the path into parts between `/` characters. This is much faster than
  21313. // using `.split(/\/+/g)`.
  21314. var parts = [];
  21315. var start = 0;
  21316. var i = 0;
  21317. while (true) {
  21318. start = i;
  21319. i = path.indexOf("/", start);
  21320. if (i === -1) {
  21321. parts.push(path.slice(start));
  21322. break;
  21323. } else {
  21324. parts.push(path.slice(start, i));
  21325. while (i < path.length && path[i] === "/") {
  21326. i++;
  21327. }
  21328. }
  21329. }
  21330. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  21331. part = parts[i];
  21332. if (part === '.') {
  21333. parts.splice(i, 1);
  21334. } else if (part === '..') {
  21335. up++;
  21336. } else if (up > 0) {
  21337. if (part === '') {
  21338. // The first part is blank if the path is absolute. Trying to go
  21339. // above the root is a no-op. Therefore we can remove all '..' parts
  21340. // directly after the root.
  21341. parts.splice(i + 1, up);
  21342. up = 0;
  21343. } else {
  21344. parts.splice(i, 2);
  21345. up--;
  21346. }
  21347. }
  21348. }
  21349. path = parts.join('/');
  21350. if (path === '') {
  21351. path = isAbsolute ? '/' : '.';
  21352. }
  21353. if (url) {
  21354. url.path = path;
  21355. return urlGenerate(url);
  21356. }
  21357. return path;
  21358. });
  21359. exports.normalize = normalize;
  21360. /**
  21361. * Joins two paths/URLs.
  21362. *
  21363. * @param aRoot The root path or URL.
  21364. * @param aPath The path or URL to be joined with the root.
  21365. *
  21366. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  21367. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  21368. * first.
  21369. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  21370. * is updated with the result and aRoot is returned. Otherwise the result
  21371. * is returned.
  21372. * - If aPath is absolute, the result is aPath.
  21373. * - Otherwise the two paths are joined with a slash.
  21374. * - Joining for example 'http://' and 'www.example.com' is also supported.
  21375. */
  21376. function join(aRoot, aPath) {
  21377. if (aRoot === "") {
  21378. aRoot = ".";
  21379. }
  21380. if (aPath === "") {
  21381. aPath = ".";
  21382. }
  21383. var aPathUrl = urlParse(aPath);
  21384. var aRootUrl = urlParse(aRoot);
  21385. if (aRootUrl) {
  21386. aRoot = aRootUrl.path || '/';
  21387. }
  21388. // `join(foo, '//www.example.org')`
  21389. if (aPathUrl && !aPathUrl.scheme) {
  21390. if (aRootUrl) {
  21391. aPathUrl.scheme = aRootUrl.scheme;
  21392. }
  21393. return urlGenerate(aPathUrl);
  21394. }
  21395. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  21396. return aPath;
  21397. }
  21398. // `join('http://', 'www.example.com')`
  21399. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  21400. aRootUrl.host = aPath;
  21401. return urlGenerate(aRootUrl);
  21402. }
  21403. var joined = aPath.charAt(0) === '/'
  21404. ? aPath
  21405. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  21406. if (aRootUrl) {
  21407. aRootUrl.path = joined;
  21408. return urlGenerate(aRootUrl);
  21409. }
  21410. return joined;
  21411. }
  21412. exports.join = join;
  21413. exports.isAbsolute = function (aPath) {
  21414. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  21415. };
  21416. /**
  21417. * Make a path relative to a URL or another path.
  21418. *
  21419. * @param aRoot The root path or URL.
  21420. * @param aPath The path or URL to be made relative to aRoot.
  21421. */
  21422. function relative(aRoot, aPath) {
  21423. if (aRoot === "") {
  21424. aRoot = ".";
  21425. }
  21426. aRoot = aRoot.replace(/\/$/, '');
  21427. // It is possible for the path to be above the root. In this case, simply
  21428. // checking whether the root is a prefix of the path won't work. Instead, we
  21429. // need to remove components from the root one by one, until either we find
  21430. // a prefix that fits, or we run out of components to remove.
  21431. var level = 0;
  21432. while (aPath.indexOf(aRoot + '/') !== 0) {
  21433. var index = aRoot.lastIndexOf("/");
  21434. if (index < 0) {
  21435. return aPath;
  21436. }
  21437. // If the only part of the root that is left is the scheme (i.e. http://,
  21438. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  21439. // have exhausted all components, so the path is not relative to the root.
  21440. aRoot = aRoot.slice(0, index);
  21441. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  21442. return aPath;
  21443. }
  21444. ++level;
  21445. }
  21446. // Make sure we add a "../" for each component we removed from the root.
  21447. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  21448. }
  21449. exports.relative = relative;
  21450. var supportsNullProto = (function () {
  21451. var obj = Object.create(null);
  21452. return !('__proto__' in obj);
  21453. }());
  21454. function identity (s) {
  21455. return s;
  21456. }
  21457. /**
  21458. * Because behavior goes wacky when you set `__proto__` on objects, we
  21459. * have to prefix all the strings in our set with an arbitrary character.
  21460. *
  21461. * See https://github.com/mozilla/source-map/pull/31 and
  21462. * https://github.com/mozilla/source-map/issues/30
  21463. *
  21464. * @param String aStr
  21465. */
  21466. function toSetString(aStr) {
  21467. if (isProtoString(aStr)) {
  21468. return '$' + aStr;
  21469. }
  21470. return aStr;
  21471. }
  21472. exports.toSetString = supportsNullProto ? identity : toSetString;
  21473. function fromSetString(aStr) {
  21474. if (isProtoString(aStr)) {
  21475. return aStr.slice(1);
  21476. }
  21477. return aStr;
  21478. }
  21479. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  21480. function isProtoString(s) {
  21481. if (!s) {
  21482. return false;
  21483. }
  21484. var length = s.length;
  21485. if (length < 9 /* "__proto__".length */) {
  21486. return false;
  21487. }
  21488. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  21489. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  21490. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  21491. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  21492. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  21493. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  21494. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  21495. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  21496. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  21497. return false;
  21498. }
  21499. for (var i = length - 10; i >= 0; i--) {
  21500. if (s.charCodeAt(i) !== 36 /* '$' */) {
  21501. return false;
  21502. }
  21503. }
  21504. return true;
  21505. }
  21506. /**
  21507. * Comparator between two mappings where the original positions are compared.
  21508. *
  21509. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  21510. * mappings with the same original source/line/column, but different generated
  21511. * line and column the same. Useful when searching for a mapping with a
  21512. * stubbed out mapping.
  21513. */
  21514. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  21515. var cmp = strcmp(mappingA.source, mappingB.source);
  21516. if (cmp !== 0) {
  21517. return cmp;
  21518. }
  21519. cmp = mappingA.originalLine - mappingB.originalLine;
  21520. if (cmp !== 0) {
  21521. return cmp;
  21522. }
  21523. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21524. if (cmp !== 0 || onlyCompareOriginal) {
  21525. return cmp;
  21526. }
  21527. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21528. if (cmp !== 0) {
  21529. return cmp;
  21530. }
  21531. cmp = mappingA.generatedLine - mappingB.generatedLine;
  21532. if (cmp !== 0) {
  21533. return cmp;
  21534. }
  21535. return strcmp(mappingA.name, mappingB.name);
  21536. }
  21537. exports.compareByOriginalPositions = compareByOriginalPositions;
  21538. function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
  21539. var cmp;
  21540. cmp = mappingA.originalLine - mappingB.originalLine;
  21541. if (cmp !== 0) {
  21542. return cmp;
  21543. }
  21544. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21545. if (cmp !== 0 || onlyCompareOriginal) {
  21546. return cmp;
  21547. }
  21548. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21549. if (cmp !== 0) {
  21550. return cmp;
  21551. }
  21552. cmp = mappingA.generatedLine - mappingB.generatedLine;
  21553. if (cmp !== 0) {
  21554. return cmp;
  21555. }
  21556. return strcmp(mappingA.name, mappingB.name);
  21557. }
  21558. exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
  21559. /**
  21560. * Comparator between two mappings with deflated source and name indices where
  21561. * the generated positions are compared.
  21562. *
  21563. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  21564. * mappings with the same generated line and column, but different
  21565. * source/name/original line and column the same. Useful when searching for a
  21566. * mapping with a stubbed out mapping.
  21567. */
  21568. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  21569. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  21570. if (cmp !== 0) {
  21571. return cmp;
  21572. }
  21573. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21574. if (cmp !== 0 || onlyCompareGenerated) {
  21575. return cmp;
  21576. }
  21577. cmp = strcmp(mappingA.source, mappingB.source);
  21578. if (cmp !== 0) {
  21579. return cmp;
  21580. }
  21581. cmp = mappingA.originalLine - mappingB.originalLine;
  21582. if (cmp !== 0) {
  21583. return cmp;
  21584. }
  21585. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21586. if (cmp !== 0) {
  21587. return cmp;
  21588. }
  21589. return strcmp(mappingA.name, mappingB.name);
  21590. }
  21591. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  21592. function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
  21593. var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21594. if (cmp !== 0 || onlyCompareGenerated) {
  21595. return cmp;
  21596. }
  21597. cmp = strcmp(mappingA.source, mappingB.source);
  21598. if (cmp !== 0) {
  21599. return cmp;
  21600. }
  21601. cmp = mappingA.originalLine - mappingB.originalLine;
  21602. if (cmp !== 0) {
  21603. return cmp;
  21604. }
  21605. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21606. if (cmp !== 0) {
  21607. return cmp;
  21608. }
  21609. return strcmp(mappingA.name, mappingB.name);
  21610. }
  21611. exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
  21612. function strcmp(aStr1, aStr2) {
  21613. if (aStr1 === aStr2) {
  21614. return 0;
  21615. }
  21616. if (aStr1 === null) {
  21617. return 1; // aStr2 !== null
  21618. }
  21619. if (aStr2 === null) {
  21620. return -1; // aStr1 !== null
  21621. }
  21622. if (aStr1 > aStr2) {
  21623. return 1;
  21624. }
  21625. return -1;
  21626. }
  21627. /**
  21628. * Comparator between two mappings with inflated source and name strings where
  21629. * the generated positions are compared.
  21630. */
  21631. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  21632. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  21633. if (cmp !== 0) {
  21634. return cmp;
  21635. }
  21636. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21637. if (cmp !== 0) {
  21638. return cmp;
  21639. }
  21640. cmp = strcmp(mappingA.source, mappingB.source);
  21641. if (cmp !== 0) {
  21642. return cmp;
  21643. }
  21644. cmp = mappingA.originalLine - mappingB.originalLine;
  21645. if (cmp !== 0) {
  21646. return cmp;
  21647. }
  21648. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21649. if (cmp !== 0) {
  21650. return cmp;
  21651. }
  21652. return strcmp(mappingA.name, mappingB.name);
  21653. }
  21654. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  21655. /**
  21656. * Strip any JSON XSSI avoidance prefix from the string (as documented
  21657. * in the source maps specification), and then parse the string as
  21658. * JSON.
  21659. */
  21660. function parseSourceMapInput(str) {
  21661. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  21662. }
  21663. exports.parseSourceMapInput = parseSourceMapInput;
  21664. /**
  21665. * Compute the URL of a source given the the source root, the source's
  21666. * URL, and the source map's URL.
  21667. */
  21668. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  21669. sourceURL = sourceURL || '';
  21670. if (sourceRoot) {
  21671. // This follows what Chrome does.
  21672. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  21673. sourceRoot += '/';
  21674. }
  21675. // The spec says:
  21676. // Line 4: An optional source root, useful for relocating source
  21677. // files on a server or removing repeated values in the
  21678. // “sources” entry. This value is prepended to the individual
  21679. // entries in the “source” field.
  21680. sourceURL = sourceRoot + sourceURL;
  21681. }
  21682. // Historically, SourceMapConsumer did not take the sourceMapURL as
  21683. // a parameter. This mode is still somewhat supported, which is why
  21684. // this code block is conditional. However, it's preferable to pass
  21685. // the source map URL to SourceMapConsumer, so that this function
  21686. // can implement the source URL resolution algorithm as outlined in
  21687. // the spec. This block is basically the equivalent of:
  21688. // new URL(sourceURL, sourceMapURL).toString()
  21689. // ... except it avoids using URL, which wasn't available in the
  21690. // older releases of node still supported by this library.
  21691. //
  21692. // The spec says:
  21693. // If the sources are not absolute URLs after prepending of the
  21694. // “sourceRoot”, the sources are resolved relative to the
  21695. // SourceMap (like resolving script src in a html document).
  21696. if (sourceMapURL) {
  21697. var parsed = urlParse(sourceMapURL);
  21698. if (!parsed) {
  21699. throw new Error("sourceMapURL could not be parsed");
  21700. }
  21701. if (parsed.path) {
  21702. // Strip the last path component, but keep the "/".
  21703. var index = parsed.path.lastIndexOf('/');
  21704. if (index >= 0) {
  21705. parsed.path = parsed.path.substring(0, index + 1);
  21706. }
  21707. }
  21708. sourceURL = join(urlGenerate(parsed), sourceURL);
  21709. }
  21710. return normalize(sourceURL);
  21711. }
  21712. exports.computeSourceURL = computeSourceURL;
  21713. } (util$2));
  21714. return util$2;
  21715. }
  21716. var arraySet$1 = {};
  21717. /* -*- Mode: js; js-indent-level: 2; -*- */
  21718. var hasRequiredArraySet$1;
  21719. function requireArraySet$1 () {
  21720. if (hasRequiredArraySet$1) return arraySet$1;
  21721. hasRequiredArraySet$1 = 1;
  21722. /*
  21723. * Copyright 2011 Mozilla Foundation and contributors
  21724. * Licensed under the New BSD license. See LICENSE or:
  21725. * http://opensource.org/licenses/BSD-3-Clause
  21726. */
  21727. var util = /*@__PURE__*/ requireUtil$2();
  21728. var has = Object.prototype.hasOwnProperty;
  21729. var hasNativeMap = typeof Map !== "undefined";
  21730. /**
  21731. * A data structure which is a combination of an array and a set. Adding a new
  21732. * member is O(1), testing for membership is O(1), and finding the index of an
  21733. * element is O(1). Removing elements from the set is not supported. Only
  21734. * strings are supported for membership.
  21735. */
  21736. function ArraySet() {
  21737. this._array = [];
  21738. this._set = hasNativeMap ? new Map() : Object.create(null);
  21739. }
  21740. /**
  21741. * Static method for creating ArraySet instances from an existing array.
  21742. */
  21743. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  21744. var set = new ArraySet();
  21745. for (var i = 0, len = aArray.length; i < len; i++) {
  21746. set.add(aArray[i], aAllowDuplicates);
  21747. }
  21748. return set;
  21749. };
  21750. /**
  21751. * Return how many unique items are in this ArraySet. If duplicates have been
  21752. * added, than those do not count towards the size.
  21753. *
  21754. * @returns Number
  21755. */
  21756. ArraySet.prototype.size = function ArraySet_size() {
  21757. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  21758. };
  21759. /**
  21760. * Add the given string to this set.
  21761. *
  21762. * @param String aStr
  21763. */
  21764. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  21765. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  21766. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  21767. var idx = this._array.length;
  21768. if (!isDuplicate || aAllowDuplicates) {
  21769. this._array.push(aStr);
  21770. }
  21771. if (!isDuplicate) {
  21772. if (hasNativeMap) {
  21773. this._set.set(aStr, idx);
  21774. } else {
  21775. this._set[sStr] = idx;
  21776. }
  21777. }
  21778. };
  21779. /**
  21780. * Is the given string a member of this set?
  21781. *
  21782. * @param String aStr
  21783. */
  21784. ArraySet.prototype.has = function ArraySet_has(aStr) {
  21785. if (hasNativeMap) {
  21786. return this._set.has(aStr);
  21787. } else {
  21788. var sStr = util.toSetString(aStr);
  21789. return has.call(this._set, sStr);
  21790. }
  21791. };
  21792. /**
  21793. * What is the index of the given string in the array?
  21794. *
  21795. * @param String aStr
  21796. */
  21797. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  21798. if (hasNativeMap) {
  21799. var idx = this._set.get(aStr);
  21800. if (idx >= 0) {
  21801. return idx;
  21802. }
  21803. } else {
  21804. var sStr = util.toSetString(aStr);
  21805. if (has.call(this._set, sStr)) {
  21806. return this._set[sStr];
  21807. }
  21808. }
  21809. throw new Error('"' + aStr + '" is not in the set.');
  21810. };
  21811. /**
  21812. * What is the element at the given index?
  21813. *
  21814. * @param Number aIdx
  21815. */
  21816. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  21817. if (aIdx >= 0 && aIdx < this._array.length) {
  21818. return this._array[aIdx];
  21819. }
  21820. throw new Error('No element indexed by ' + aIdx);
  21821. };
  21822. /**
  21823. * Returns the array representation of this set (which has the proper indices
  21824. * indicated by indexOf). Note that this is a copy of the internal array used
  21825. * for storing the members so that no one can mess with internal state.
  21826. */
  21827. ArraySet.prototype.toArray = function ArraySet_toArray() {
  21828. return this._array.slice();
  21829. };
  21830. arraySet$1.ArraySet = ArraySet;
  21831. return arraySet$1;
  21832. }
  21833. var mappingList$1 = {};
  21834. /* -*- Mode: js; js-indent-level: 2; -*- */
  21835. var hasRequiredMappingList$1;
  21836. function requireMappingList$1 () {
  21837. if (hasRequiredMappingList$1) return mappingList$1;
  21838. hasRequiredMappingList$1 = 1;
  21839. /*
  21840. * Copyright 2014 Mozilla Foundation and contributors
  21841. * Licensed under the New BSD license. See LICENSE or:
  21842. * http://opensource.org/licenses/BSD-3-Clause
  21843. */
  21844. var util = /*@__PURE__*/ requireUtil$2();
  21845. /**
  21846. * Determine whether mappingB is after mappingA with respect to generated
  21847. * position.
  21848. */
  21849. function generatedPositionAfter(mappingA, mappingB) {
  21850. // Optimized for most common case
  21851. var lineA = mappingA.generatedLine;
  21852. var lineB = mappingB.generatedLine;
  21853. var columnA = mappingA.generatedColumn;
  21854. var columnB = mappingB.generatedColumn;
  21855. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  21856. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  21857. }
  21858. /**
  21859. * A data structure to provide a sorted view of accumulated mappings in a
  21860. * performance conscious manner. It trades a neglibable overhead in general
  21861. * case for a large speedup in case of mappings being added in order.
  21862. */
  21863. function MappingList() {
  21864. this._array = [];
  21865. this._sorted = true;
  21866. // Serves as infimum
  21867. this._last = {generatedLine: -1, generatedColumn: 0};
  21868. }
  21869. /**
  21870. * Iterate through internal items. This method takes the same arguments that
  21871. * `Array.prototype.forEach` takes.
  21872. *
  21873. * NOTE: The order of the mappings is NOT guaranteed.
  21874. */
  21875. MappingList.prototype.unsortedForEach =
  21876. function MappingList_forEach(aCallback, aThisArg) {
  21877. this._array.forEach(aCallback, aThisArg);
  21878. };
  21879. /**
  21880. * Add the given source mapping.
  21881. *
  21882. * @param Object aMapping
  21883. */
  21884. MappingList.prototype.add = function MappingList_add(aMapping) {
  21885. if (generatedPositionAfter(this._last, aMapping)) {
  21886. this._last = aMapping;
  21887. this._array.push(aMapping);
  21888. } else {
  21889. this._sorted = false;
  21890. this._array.push(aMapping);
  21891. }
  21892. };
  21893. /**
  21894. * Returns the flat, sorted array of mappings. The mappings are sorted by
  21895. * generated position.
  21896. *
  21897. * WARNING: This method returns internal data without copying, for
  21898. * performance. The return value must NOT be mutated, and should be treated as
  21899. * an immutable borrow. If you want to take ownership, you must make your own
  21900. * copy.
  21901. */
  21902. MappingList.prototype.toArray = function MappingList_toArray() {
  21903. if (!this._sorted) {
  21904. this._array.sort(util.compareByGeneratedPositionsInflated);
  21905. this._sorted = true;
  21906. }
  21907. return this._array;
  21908. };
  21909. mappingList$1.MappingList = MappingList;
  21910. return mappingList$1;
  21911. }
  21912. /* -*- Mode: js; js-indent-level: 2; -*- */
  21913. var hasRequiredSourceMapGenerator$1;
  21914. function requireSourceMapGenerator$1 () {
  21915. if (hasRequiredSourceMapGenerator$1) return sourceMapGenerator$1;
  21916. hasRequiredSourceMapGenerator$1 = 1;
  21917. /*
  21918. * Copyright 2011 Mozilla Foundation and contributors
  21919. * Licensed under the New BSD license. See LICENSE or:
  21920. * http://opensource.org/licenses/BSD-3-Clause
  21921. */
  21922. var base64VLQ = /*@__PURE__*/ requireBase64Vlq$1();
  21923. var util = /*@__PURE__*/ requireUtil$2();
  21924. var ArraySet = /*@__PURE__*/ requireArraySet$1().ArraySet;
  21925. var MappingList = /*@__PURE__*/ requireMappingList$1().MappingList;
  21926. /**
  21927. * An instance of the SourceMapGenerator represents a source map which is
  21928. * being built incrementally. You may pass an object with the following
  21929. * properties:
  21930. *
  21931. * - file: The filename of the generated source.
  21932. * - sourceRoot: A root for all relative URLs in this source map.
  21933. */
  21934. function SourceMapGenerator(aArgs) {
  21935. if (!aArgs) {
  21936. aArgs = {};
  21937. }
  21938. this._file = util.getArg(aArgs, 'file', null);
  21939. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  21940. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  21941. this._ignoreInvalidMapping = util.getArg(aArgs, 'ignoreInvalidMapping', false);
  21942. this._sources = new ArraySet();
  21943. this._names = new ArraySet();
  21944. this._mappings = new MappingList();
  21945. this._sourcesContents = null;
  21946. }
  21947. SourceMapGenerator.prototype._version = 3;
  21948. /**
  21949. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  21950. *
  21951. * @param aSourceMapConsumer The SourceMap.
  21952. */
  21953. SourceMapGenerator.fromSourceMap =
  21954. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) {
  21955. var sourceRoot = aSourceMapConsumer.sourceRoot;
  21956. var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, {
  21957. file: aSourceMapConsumer.file,
  21958. sourceRoot: sourceRoot
  21959. }));
  21960. aSourceMapConsumer.eachMapping(function (mapping) {
  21961. var newMapping = {
  21962. generated: {
  21963. line: mapping.generatedLine,
  21964. column: mapping.generatedColumn
  21965. }
  21966. };
  21967. if (mapping.source != null) {
  21968. newMapping.source = mapping.source;
  21969. if (sourceRoot != null) {
  21970. newMapping.source = util.relative(sourceRoot, newMapping.source);
  21971. }
  21972. newMapping.original = {
  21973. line: mapping.originalLine,
  21974. column: mapping.originalColumn
  21975. };
  21976. if (mapping.name != null) {
  21977. newMapping.name = mapping.name;
  21978. }
  21979. }
  21980. generator.addMapping(newMapping);
  21981. });
  21982. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  21983. var sourceRelative = sourceFile;
  21984. if (sourceRoot !== null) {
  21985. sourceRelative = util.relative(sourceRoot, sourceFile);
  21986. }
  21987. if (!generator._sources.has(sourceRelative)) {
  21988. generator._sources.add(sourceRelative);
  21989. }
  21990. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  21991. if (content != null) {
  21992. generator.setSourceContent(sourceFile, content);
  21993. }
  21994. });
  21995. return generator;
  21996. };
  21997. /**
  21998. * Add a single mapping from original source line and column to the generated
  21999. * source's line and column for this source map being created. The mapping
  22000. * object should have the following properties:
  22001. *
  22002. * - generated: An object with the generated line and column positions.
  22003. * - original: An object with the original line and column positions.
  22004. * - source: The original source file (relative to the sourceRoot).
  22005. * - name: An optional original token name for this mapping.
  22006. */
  22007. SourceMapGenerator.prototype.addMapping =
  22008. function SourceMapGenerator_addMapping(aArgs) {
  22009. var generated = util.getArg(aArgs, 'generated');
  22010. var original = util.getArg(aArgs, 'original', null);
  22011. var source = util.getArg(aArgs, 'source', null);
  22012. var name = util.getArg(aArgs, 'name', null);
  22013. if (!this._skipValidation) {
  22014. if (this._validateMapping(generated, original, source, name) === false) {
  22015. return;
  22016. }
  22017. }
  22018. if (source != null) {
  22019. source = String(source);
  22020. if (!this._sources.has(source)) {
  22021. this._sources.add(source);
  22022. }
  22023. }
  22024. if (name != null) {
  22025. name = String(name);
  22026. if (!this._names.has(name)) {
  22027. this._names.add(name);
  22028. }
  22029. }
  22030. this._mappings.add({
  22031. generatedLine: generated.line,
  22032. generatedColumn: generated.column,
  22033. originalLine: original != null && original.line,
  22034. originalColumn: original != null && original.column,
  22035. source: source,
  22036. name: name
  22037. });
  22038. };
  22039. /**
  22040. * Set the source content for a source file.
  22041. */
  22042. SourceMapGenerator.prototype.setSourceContent =
  22043. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  22044. var source = aSourceFile;
  22045. if (this._sourceRoot != null) {
  22046. source = util.relative(this._sourceRoot, source);
  22047. }
  22048. if (aSourceContent != null) {
  22049. // Add the source content to the _sourcesContents map.
  22050. // Create a new _sourcesContents map if the property is null.
  22051. if (!this._sourcesContents) {
  22052. this._sourcesContents = Object.create(null);
  22053. }
  22054. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  22055. } else if (this._sourcesContents) {
  22056. // Remove the source file from the _sourcesContents map.
  22057. // If the _sourcesContents map is empty, set the property to null.
  22058. delete this._sourcesContents[util.toSetString(source)];
  22059. if (Object.keys(this._sourcesContents).length === 0) {
  22060. this._sourcesContents = null;
  22061. }
  22062. }
  22063. };
  22064. /**
  22065. * Applies the mappings of a sub-source-map for a specific source file to the
  22066. * source map being generated. Each mapping to the supplied source file is
  22067. * rewritten using the supplied source map. Note: The resolution for the
  22068. * resulting mappings is the minimium of this map and the supplied map.
  22069. *
  22070. * @param aSourceMapConsumer The source map to be applied.
  22071. * @param aSourceFile Optional. The filename of the source file.
  22072. * If omitted, SourceMapConsumer's file property will be used.
  22073. * @param aSourceMapPath Optional. The dirname of the path to the source map
  22074. * to be applied. If relative, it is relative to the SourceMapConsumer.
  22075. * This parameter is needed when the two source maps aren't in the same
  22076. * directory, and the source map to be applied contains relative source
  22077. * paths. If so, those relative source paths need to be rewritten
  22078. * relative to the SourceMapGenerator.
  22079. */
  22080. SourceMapGenerator.prototype.applySourceMap =
  22081. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  22082. var sourceFile = aSourceFile;
  22083. // If aSourceFile is omitted, we will use the file property of the SourceMap
  22084. if (aSourceFile == null) {
  22085. if (aSourceMapConsumer.file == null) {
  22086. throw new Error(
  22087. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  22088. 'or the source map\'s "file" property. Both were omitted.'
  22089. );
  22090. }
  22091. sourceFile = aSourceMapConsumer.file;
  22092. }
  22093. var sourceRoot = this._sourceRoot;
  22094. // Make "sourceFile" relative if an absolute Url is passed.
  22095. if (sourceRoot != null) {
  22096. sourceFile = util.relative(sourceRoot, sourceFile);
  22097. }
  22098. // Applying the SourceMap can add and remove items from the sources and
  22099. // the names array.
  22100. var newSources = new ArraySet();
  22101. var newNames = new ArraySet();
  22102. // Find mappings for the "sourceFile"
  22103. this._mappings.unsortedForEach(function (mapping) {
  22104. if (mapping.source === sourceFile && mapping.originalLine != null) {
  22105. // Check if it can be mapped by the source map, then update the mapping.
  22106. var original = aSourceMapConsumer.originalPositionFor({
  22107. line: mapping.originalLine,
  22108. column: mapping.originalColumn
  22109. });
  22110. if (original.source != null) {
  22111. // Copy mapping
  22112. mapping.source = original.source;
  22113. if (aSourceMapPath != null) {
  22114. mapping.source = util.join(aSourceMapPath, mapping.source);
  22115. }
  22116. if (sourceRoot != null) {
  22117. mapping.source = util.relative(sourceRoot, mapping.source);
  22118. }
  22119. mapping.originalLine = original.line;
  22120. mapping.originalColumn = original.column;
  22121. if (original.name != null) {
  22122. mapping.name = original.name;
  22123. }
  22124. }
  22125. }
  22126. var source = mapping.source;
  22127. if (source != null && !newSources.has(source)) {
  22128. newSources.add(source);
  22129. }
  22130. var name = mapping.name;
  22131. if (name != null && !newNames.has(name)) {
  22132. newNames.add(name);
  22133. }
  22134. }, this);
  22135. this._sources = newSources;
  22136. this._names = newNames;
  22137. // Copy sourcesContents of applied map.
  22138. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  22139. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  22140. if (content != null) {
  22141. if (aSourceMapPath != null) {
  22142. sourceFile = util.join(aSourceMapPath, sourceFile);
  22143. }
  22144. if (sourceRoot != null) {
  22145. sourceFile = util.relative(sourceRoot, sourceFile);
  22146. }
  22147. this.setSourceContent(sourceFile, content);
  22148. }
  22149. }, this);
  22150. };
  22151. /**
  22152. * A mapping can have one of the three levels of data:
  22153. *
  22154. * 1. Just the generated position.
  22155. * 2. The Generated position, original position, and original source.
  22156. * 3. Generated and original position, original source, as well as a name
  22157. * token.
  22158. *
  22159. * To maintain consistency, we validate that any new mapping being added falls
  22160. * in to one of these categories.
  22161. */
  22162. SourceMapGenerator.prototype._validateMapping =
  22163. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  22164. aName) {
  22165. // When aOriginal is truthy but has empty values for .line and .column,
  22166. // it is most likely a programmer error. In this case we throw a very
  22167. // specific error message to try to guide them the right way.
  22168. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  22169. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  22170. var message = 'original.line and original.column are not numbers -- you probably meant to omit ' +
  22171. 'the original mapping entirely and only map the generated position. If so, pass ' +
  22172. 'null for the original mapping instead of an object with empty or null values.';
  22173. if (this._ignoreInvalidMapping) {
  22174. if (typeof console !== 'undefined' && console.warn) {
  22175. console.warn(message);
  22176. }
  22177. return false;
  22178. } else {
  22179. throw new Error(message);
  22180. }
  22181. }
  22182. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  22183. && aGenerated.line > 0 && aGenerated.column >= 0
  22184. && !aOriginal && !aSource && !aName) {
  22185. // Case 1.
  22186. return;
  22187. }
  22188. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  22189. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  22190. && aGenerated.line > 0 && aGenerated.column >= 0
  22191. && aOriginal.line > 0 && aOriginal.column >= 0
  22192. && aSource) {
  22193. // Cases 2 and 3.
  22194. return;
  22195. }
  22196. else {
  22197. var message = 'Invalid mapping: ' + JSON.stringify({
  22198. generated: aGenerated,
  22199. source: aSource,
  22200. original: aOriginal,
  22201. name: aName
  22202. });
  22203. if (this._ignoreInvalidMapping) {
  22204. if (typeof console !== 'undefined' && console.warn) {
  22205. console.warn(message);
  22206. }
  22207. return false;
  22208. } else {
  22209. throw new Error(message)
  22210. }
  22211. }
  22212. };
  22213. /**
  22214. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  22215. * specified by the source map format.
  22216. */
  22217. SourceMapGenerator.prototype._serializeMappings =
  22218. function SourceMapGenerator_serializeMappings() {
  22219. var previousGeneratedColumn = 0;
  22220. var previousGeneratedLine = 1;
  22221. var previousOriginalColumn = 0;
  22222. var previousOriginalLine = 0;
  22223. var previousName = 0;
  22224. var previousSource = 0;
  22225. var result = '';
  22226. var next;
  22227. var mapping;
  22228. var nameIdx;
  22229. var sourceIdx;
  22230. var mappings = this._mappings.toArray();
  22231. for (var i = 0, len = mappings.length; i < len; i++) {
  22232. mapping = mappings[i];
  22233. next = '';
  22234. if (mapping.generatedLine !== previousGeneratedLine) {
  22235. previousGeneratedColumn = 0;
  22236. while (mapping.generatedLine !== previousGeneratedLine) {
  22237. next += ';';
  22238. previousGeneratedLine++;
  22239. }
  22240. }
  22241. else {
  22242. if (i > 0) {
  22243. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  22244. continue;
  22245. }
  22246. next += ',';
  22247. }
  22248. }
  22249. next += base64VLQ.encode(mapping.generatedColumn
  22250. - previousGeneratedColumn);
  22251. previousGeneratedColumn = mapping.generatedColumn;
  22252. if (mapping.source != null) {
  22253. sourceIdx = this._sources.indexOf(mapping.source);
  22254. next += base64VLQ.encode(sourceIdx - previousSource);
  22255. previousSource = sourceIdx;
  22256. // lines are stored 0-based in SourceMap spec version 3
  22257. next += base64VLQ.encode(mapping.originalLine - 1
  22258. - previousOriginalLine);
  22259. previousOriginalLine = mapping.originalLine - 1;
  22260. next += base64VLQ.encode(mapping.originalColumn
  22261. - previousOriginalColumn);
  22262. previousOriginalColumn = mapping.originalColumn;
  22263. if (mapping.name != null) {
  22264. nameIdx = this._names.indexOf(mapping.name);
  22265. next += base64VLQ.encode(nameIdx - previousName);
  22266. previousName = nameIdx;
  22267. }
  22268. }
  22269. result += next;
  22270. }
  22271. return result;
  22272. };
  22273. SourceMapGenerator.prototype._generateSourcesContent =
  22274. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  22275. return aSources.map(function (source) {
  22276. if (!this._sourcesContents) {
  22277. return null;
  22278. }
  22279. if (aSourceRoot != null) {
  22280. source = util.relative(aSourceRoot, source);
  22281. }
  22282. var key = util.toSetString(source);
  22283. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  22284. ? this._sourcesContents[key]
  22285. : null;
  22286. }, this);
  22287. };
  22288. /**
  22289. * Externalize the source map.
  22290. */
  22291. SourceMapGenerator.prototype.toJSON =
  22292. function SourceMapGenerator_toJSON() {
  22293. var map = {
  22294. version: this._version,
  22295. sources: this._sources.toArray(),
  22296. names: this._names.toArray(),
  22297. mappings: this._serializeMappings()
  22298. };
  22299. if (this._file != null) {
  22300. map.file = this._file;
  22301. }
  22302. if (this._sourceRoot != null) {
  22303. map.sourceRoot = this._sourceRoot;
  22304. }
  22305. if (this._sourcesContents) {
  22306. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  22307. }
  22308. return map;
  22309. };
  22310. /**
  22311. * Render the source map being generated to a string.
  22312. */
  22313. SourceMapGenerator.prototype.toString =
  22314. function SourceMapGenerator_toString() {
  22315. return JSON.stringify(this.toJSON());
  22316. };
  22317. sourceMapGenerator$1.SourceMapGenerator = SourceMapGenerator;
  22318. return sourceMapGenerator$1;
  22319. }
  22320. var sourceMapConsumer$1 = {};
  22321. var binarySearch$1 = {};
  22322. /* -*- Mode: js; js-indent-level: 2; -*- */
  22323. var hasRequiredBinarySearch$1;
  22324. function requireBinarySearch$1 () {
  22325. if (hasRequiredBinarySearch$1) return binarySearch$1;
  22326. hasRequiredBinarySearch$1 = 1;
  22327. (function (exports) {
  22328. /*
  22329. * Copyright 2011 Mozilla Foundation and contributors
  22330. * Licensed under the New BSD license. See LICENSE or:
  22331. * http://opensource.org/licenses/BSD-3-Clause
  22332. */
  22333. exports.GREATEST_LOWER_BOUND = 1;
  22334. exports.LEAST_UPPER_BOUND = 2;
  22335. /**
  22336. * Recursive implementation of binary search.
  22337. *
  22338. * @param aLow Indices here and lower do not contain the needle.
  22339. * @param aHigh Indices here and higher do not contain the needle.
  22340. * @param aNeedle The element being searched for.
  22341. * @param aHaystack The non-empty array being searched.
  22342. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  22343. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  22344. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  22345. * closest element that is smaller than or greater than the one we are
  22346. * searching for, respectively, if the exact element cannot be found.
  22347. */
  22348. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  22349. // This function terminates when one of the following is true:
  22350. //
  22351. // 1. We find the exact element we are looking for.
  22352. //
  22353. // 2. We did not find the exact element, but we can return the index of
  22354. // the next-closest element.
  22355. //
  22356. // 3. We did not find the exact element, and there is no next-closest
  22357. // element than the one we are searching for, so we return -1.
  22358. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  22359. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  22360. if (cmp === 0) {
  22361. // Found the element we are looking for.
  22362. return mid;
  22363. }
  22364. else if (cmp > 0) {
  22365. // Our needle is greater than aHaystack[mid].
  22366. if (aHigh - mid > 1) {
  22367. // The element is in the upper half.
  22368. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  22369. }
  22370. // The exact needle element was not found in this haystack. Determine if
  22371. // we are in termination case (3) or (2) and return the appropriate thing.
  22372. if (aBias == exports.LEAST_UPPER_BOUND) {
  22373. return aHigh < aHaystack.length ? aHigh : -1;
  22374. } else {
  22375. return mid;
  22376. }
  22377. }
  22378. else {
  22379. // Our needle is less than aHaystack[mid].
  22380. if (mid - aLow > 1) {
  22381. // The element is in the lower half.
  22382. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  22383. }
  22384. // we are in termination case (3) or (2) and return the appropriate thing.
  22385. if (aBias == exports.LEAST_UPPER_BOUND) {
  22386. return mid;
  22387. } else {
  22388. return aLow < 0 ? -1 : aLow;
  22389. }
  22390. }
  22391. }
  22392. /**
  22393. * This is an implementation of binary search which will always try and return
  22394. * the index of the closest element if there is no exact hit. This is because
  22395. * mappings between original and generated line/col pairs are single points,
  22396. * and there is an implicit region between each of them, so a miss just means
  22397. * that you aren't on the very start of a region.
  22398. *
  22399. * @param aNeedle The element you are looking for.
  22400. * @param aHaystack The array that is being searched.
  22401. * @param aCompare A function which takes the needle and an element in the
  22402. * array and returns -1, 0, or 1 depending on whether the needle is less
  22403. * than, equal to, or greater than the element, respectively.
  22404. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  22405. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  22406. * closest element that is smaller than or greater than the one we are
  22407. * searching for, respectively, if the exact element cannot be found.
  22408. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  22409. */
  22410. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  22411. if (aHaystack.length === 0) {
  22412. return -1;
  22413. }
  22414. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  22415. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  22416. if (index < 0) {
  22417. return -1;
  22418. }
  22419. // We have found either the exact element, or the next-closest element than
  22420. // the one we are searching for. However, there may be more than one such
  22421. // element. Make sure we always return the smallest of these.
  22422. while (index - 1 >= 0) {
  22423. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  22424. break;
  22425. }
  22426. --index;
  22427. }
  22428. return index;
  22429. };
  22430. } (binarySearch$1));
  22431. return binarySearch$1;
  22432. }
  22433. var quickSort$1 = {};
  22434. /* -*- Mode: js; js-indent-level: 2; -*- */
  22435. var hasRequiredQuickSort$1;
  22436. function requireQuickSort$1 () {
  22437. if (hasRequiredQuickSort$1) return quickSort$1;
  22438. hasRequiredQuickSort$1 = 1;
  22439. /*
  22440. * Copyright 2011 Mozilla Foundation and contributors
  22441. * Licensed under the New BSD license. See LICENSE or:
  22442. * http://opensource.org/licenses/BSD-3-Clause
  22443. */
  22444. // It turns out that some (most?) JavaScript engines don't self-host
  22445. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  22446. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  22447. // custom comparator function, calling back and forth between the VM's C++ and
  22448. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  22449. // worse generated code for the comparator function than would be optimal. In
  22450. // fact, when sorting with a comparator, these costs outweigh the benefits of
  22451. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  22452. // a ~3500ms mean speed-up in `bench/bench.html`.
  22453. function SortTemplate(comparator) {
  22454. /**
  22455. * Swap the elements indexed by `x` and `y` in the array `ary`.
  22456. *
  22457. * @param {Array} ary
  22458. * The array.
  22459. * @param {Number} x
  22460. * The index of the first item.
  22461. * @param {Number} y
  22462. * The index of the second item.
  22463. */
  22464. function swap(ary, x, y) {
  22465. var temp = ary[x];
  22466. ary[x] = ary[y];
  22467. ary[y] = temp;
  22468. }
  22469. /**
  22470. * Returns a random integer within the range `low .. high` inclusive.
  22471. *
  22472. * @param {Number} low
  22473. * The lower bound on the range.
  22474. * @param {Number} high
  22475. * The upper bound on the range.
  22476. */
  22477. function randomIntInRange(low, high) {
  22478. return Math.round(low + (Math.random() * (high - low)));
  22479. }
  22480. /**
  22481. * The Quick Sort algorithm.
  22482. *
  22483. * @param {Array} ary
  22484. * An array to sort.
  22485. * @param {function} comparator
  22486. * Function to use to compare two items.
  22487. * @param {Number} p
  22488. * Start index of the array
  22489. * @param {Number} r
  22490. * End index of the array
  22491. */
  22492. function doQuickSort(ary, comparator, p, r) {
  22493. // If our lower bound is less than our upper bound, we (1) partition the
  22494. // array into two pieces and (2) recurse on each half. If it is not, this is
  22495. // the empty array and our base case.
  22496. if (p < r) {
  22497. // (1) Partitioning.
  22498. //
  22499. // The partitioning chooses a pivot between `p` and `r` and moves all
  22500. // elements that are less than or equal to the pivot to the before it, and
  22501. // all the elements that are greater than it after it. The effect is that
  22502. // once partition is done, the pivot is in the exact place it will be when
  22503. // the array is put in sorted order, and it will not need to be moved
  22504. // again. This runs in O(n) time.
  22505. // Always choose a random pivot so that an input array which is reverse
  22506. // sorted does not cause O(n^2) running time.
  22507. var pivotIndex = randomIntInRange(p, r);
  22508. var i = p - 1;
  22509. swap(ary, pivotIndex, r);
  22510. var pivot = ary[r];
  22511. // Immediately after `j` is incremented in this loop, the following hold
  22512. // true:
  22513. //
  22514. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  22515. //
  22516. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  22517. for (var j = p; j < r; j++) {
  22518. if (comparator(ary[j], pivot, false) <= 0) {
  22519. i += 1;
  22520. swap(ary, i, j);
  22521. }
  22522. }
  22523. swap(ary, i + 1, j);
  22524. var q = i + 1;
  22525. // (2) Recurse on each half.
  22526. doQuickSort(ary, comparator, p, q - 1);
  22527. doQuickSort(ary, comparator, q + 1, r);
  22528. }
  22529. }
  22530. return doQuickSort;
  22531. }
  22532. function cloneSort(comparator) {
  22533. let template = SortTemplate.toString();
  22534. let templateFn = new Function(`return ${template}`)();
  22535. return templateFn(comparator);
  22536. }
  22537. /**
  22538. * Sort the given array in-place with the given comparator function.
  22539. *
  22540. * @param {Array} ary
  22541. * An array to sort.
  22542. * @param {function} comparator
  22543. * Function to use to compare two items.
  22544. */
  22545. let sortCache = new WeakMap();
  22546. quickSort$1.quickSort = function (ary, comparator, start = 0) {
  22547. let doQuickSort = sortCache.get(comparator);
  22548. if (doQuickSort === void 0) {
  22549. doQuickSort = cloneSort(comparator);
  22550. sortCache.set(comparator, doQuickSort);
  22551. }
  22552. doQuickSort(ary, comparator, start, ary.length - 1);
  22553. };
  22554. return quickSort$1;
  22555. }
  22556. /* -*- Mode: js; js-indent-level: 2; -*- */
  22557. var hasRequiredSourceMapConsumer$1;
  22558. function requireSourceMapConsumer$1 () {
  22559. if (hasRequiredSourceMapConsumer$1) return sourceMapConsumer$1;
  22560. hasRequiredSourceMapConsumer$1 = 1;
  22561. /*
  22562. * Copyright 2011 Mozilla Foundation and contributors
  22563. * Licensed under the New BSD license. See LICENSE or:
  22564. * http://opensource.org/licenses/BSD-3-Clause
  22565. */
  22566. var util = /*@__PURE__*/ requireUtil$2();
  22567. var binarySearch = /*@__PURE__*/ requireBinarySearch$1();
  22568. var ArraySet = /*@__PURE__*/ requireArraySet$1().ArraySet;
  22569. var base64VLQ = /*@__PURE__*/ requireBase64Vlq$1();
  22570. var quickSort = /*@__PURE__*/ requireQuickSort$1().quickSort;
  22571. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  22572. var sourceMap = aSourceMap;
  22573. if (typeof aSourceMap === 'string') {
  22574. sourceMap = util.parseSourceMapInput(aSourceMap);
  22575. }
  22576. return sourceMap.sections != null
  22577. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  22578. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  22579. }
  22580. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  22581. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  22582. };
  22583. /**
  22584. * The version of the source mapping spec that we are consuming.
  22585. */
  22586. SourceMapConsumer.prototype._version = 3;
  22587. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  22588. // parsed mapping coordinates from the source map's "mappings" attribute. They
  22589. // are lazily instantiated, accessed via the `_generatedMappings` and
  22590. // `_originalMappings` getters respectively, and we only parse the mappings
  22591. // and create these arrays once queried for a source location. We jump through
  22592. // these hoops because there can be many thousands of mappings, and parsing
  22593. // them is expensive, so we only want to do it if we must.
  22594. //
  22595. // Each object in the arrays is of the form:
  22596. //
  22597. // {
  22598. // generatedLine: The line number in the generated code,
  22599. // generatedColumn: The column number in the generated code,
  22600. // source: The path to the original source file that generated this
  22601. // chunk of code,
  22602. // originalLine: The line number in the original source that
  22603. // corresponds to this chunk of generated code,
  22604. // originalColumn: The column number in the original source that
  22605. // corresponds to this chunk of generated code,
  22606. // name: The name of the original symbol which generated this chunk of
  22607. // code.
  22608. // }
  22609. //
  22610. // All properties except for `generatedLine` and `generatedColumn` can be
  22611. // `null`.
  22612. //
  22613. // `_generatedMappings` is ordered by the generated positions.
  22614. //
  22615. // `_originalMappings` is ordered by the original positions.
  22616. SourceMapConsumer.prototype.__generatedMappings = null;
  22617. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  22618. configurable: true,
  22619. enumerable: true,
  22620. get: function () {
  22621. if (!this.__generatedMappings) {
  22622. this._parseMappings(this._mappings, this.sourceRoot);
  22623. }
  22624. return this.__generatedMappings;
  22625. }
  22626. });
  22627. SourceMapConsumer.prototype.__originalMappings = null;
  22628. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  22629. configurable: true,
  22630. enumerable: true,
  22631. get: function () {
  22632. if (!this.__originalMappings) {
  22633. this._parseMappings(this._mappings, this.sourceRoot);
  22634. }
  22635. return this.__originalMappings;
  22636. }
  22637. });
  22638. SourceMapConsumer.prototype._charIsMappingSeparator =
  22639. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  22640. var c = aStr.charAt(index);
  22641. return c === ";" || c === ",";
  22642. };
  22643. /**
  22644. * Parse the mappings in a string in to a data structure which we can easily
  22645. * query (the ordered arrays in the `this.__generatedMappings` and
  22646. * `this.__originalMappings` properties).
  22647. */
  22648. SourceMapConsumer.prototype._parseMappings =
  22649. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  22650. throw new Error("Subclasses must implement _parseMappings");
  22651. };
  22652. SourceMapConsumer.GENERATED_ORDER = 1;
  22653. SourceMapConsumer.ORIGINAL_ORDER = 2;
  22654. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  22655. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  22656. /**
  22657. * Iterate over each mapping between an original source/line/column and a
  22658. * generated line/column in this source map.
  22659. *
  22660. * @param Function aCallback
  22661. * The function that is called with each mapping.
  22662. * @param Object aContext
  22663. * Optional. If specified, this object will be the value of `this` every
  22664. * time that `aCallback` is called.
  22665. * @param aOrder
  22666. * Either `SourceMapConsumer.GENERATED_ORDER` or
  22667. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  22668. * iterate over the mappings sorted by the generated file's line/column
  22669. * order or the original's source/line/column order, respectively. Defaults to
  22670. * `SourceMapConsumer.GENERATED_ORDER`.
  22671. */
  22672. SourceMapConsumer.prototype.eachMapping =
  22673. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  22674. var context = aContext || null;
  22675. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  22676. var mappings;
  22677. switch (order) {
  22678. case SourceMapConsumer.GENERATED_ORDER:
  22679. mappings = this._generatedMappings;
  22680. break;
  22681. case SourceMapConsumer.ORIGINAL_ORDER:
  22682. mappings = this._originalMappings;
  22683. break;
  22684. default:
  22685. throw new Error("Unknown order of iteration.");
  22686. }
  22687. var sourceRoot = this.sourceRoot;
  22688. var boundCallback = aCallback.bind(context);
  22689. var names = this._names;
  22690. var sources = this._sources;
  22691. var sourceMapURL = this._sourceMapURL;
  22692. for (var i = 0, n = mappings.length; i < n; i++) {
  22693. var mapping = mappings[i];
  22694. var source = mapping.source === null ? null : sources.at(mapping.source);
  22695. if(source !== null) {
  22696. source = util.computeSourceURL(sourceRoot, source, sourceMapURL);
  22697. }
  22698. boundCallback({
  22699. source: source,
  22700. generatedLine: mapping.generatedLine,
  22701. generatedColumn: mapping.generatedColumn,
  22702. originalLine: mapping.originalLine,
  22703. originalColumn: mapping.originalColumn,
  22704. name: mapping.name === null ? null : names.at(mapping.name)
  22705. });
  22706. }
  22707. };
  22708. /**
  22709. * Returns all generated line and column information for the original source,
  22710. * line, and column provided. If no column is provided, returns all mappings
  22711. * corresponding to a either the line we are searching for or the next
  22712. * closest line that has any mappings. Otherwise, returns all mappings
  22713. * corresponding to the given line and either the column we are searching for
  22714. * or the next closest column that has any offsets.
  22715. *
  22716. * The only argument is an object with the following properties:
  22717. *
  22718. * - source: The filename of the original source.
  22719. * - line: The line number in the original source. The line number is 1-based.
  22720. * - column: Optional. the column number in the original source.
  22721. * The column number is 0-based.
  22722. *
  22723. * and an array of objects is returned, each with the following properties:
  22724. *
  22725. * - line: The line number in the generated source, or null. The
  22726. * line number is 1-based.
  22727. * - column: The column number in the generated source, or null.
  22728. * The column number is 0-based.
  22729. */
  22730. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  22731. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  22732. var line = util.getArg(aArgs, 'line');
  22733. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  22734. // returns the index of the closest mapping less than the needle. By
  22735. // setting needle.originalColumn to 0, we thus find the last mapping for
  22736. // the given line, provided such a mapping exists.
  22737. var needle = {
  22738. source: util.getArg(aArgs, 'source'),
  22739. originalLine: line,
  22740. originalColumn: util.getArg(aArgs, 'column', 0)
  22741. };
  22742. needle.source = this._findSourceIndex(needle.source);
  22743. if (needle.source < 0) {
  22744. return [];
  22745. }
  22746. var mappings = [];
  22747. var index = this._findMapping(needle,
  22748. this._originalMappings,
  22749. "originalLine",
  22750. "originalColumn",
  22751. util.compareByOriginalPositions,
  22752. binarySearch.LEAST_UPPER_BOUND);
  22753. if (index >= 0) {
  22754. var mapping = this._originalMappings[index];
  22755. if (aArgs.column === undefined) {
  22756. var originalLine = mapping.originalLine;
  22757. // Iterate until either we run out of mappings, or we run into
  22758. // a mapping for a different line than the one we found. Since
  22759. // mappings are sorted, this is guaranteed to find all mappings for
  22760. // the line we found.
  22761. while (mapping && mapping.originalLine === originalLine) {
  22762. mappings.push({
  22763. line: util.getArg(mapping, 'generatedLine', null),
  22764. column: util.getArg(mapping, 'generatedColumn', null),
  22765. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  22766. });
  22767. mapping = this._originalMappings[++index];
  22768. }
  22769. } else {
  22770. var originalColumn = mapping.originalColumn;
  22771. // Iterate until either we run out of mappings, or we run into
  22772. // a mapping for a different line than the one we were searching for.
  22773. // Since mappings are sorted, this is guaranteed to find all mappings for
  22774. // the line we are searching for.
  22775. while (mapping &&
  22776. mapping.originalLine === line &&
  22777. mapping.originalColumn == originalColumn) {
  22778. mappings.push({
  22779. line: util.getArg(mapping, 'generatedLine', null),
  22780. column: util.getArg(mapping, 'generatedColumn', null),
  22781. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  22782. });
  22783. mapping = this._originalMappings[++index];
  22784. }
  22785. }
  22786. }
  22787. return mappings;
  22788. };
  22789. sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer;
  22790. /**
  22791. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  22792. * query for information about the original file positions by giving it a file
  22793. * position in the generated source.
  22794. *
  22795. * The first parameter is the raw source map (either as a JSON string, or
  22796. * already parsed to an object). According to the spec, source maps have the
  22797. * following attributes:
  22798. *
  22799. * - version: Which version of the source map spec this map is following.
  22800. * - sources: An array of URLs to the original source files.
  22801. * - names: An array of identifiers which can be referrenced by individual mappings.
  22802. * - sourceRoot: Optional. The URL root from which all sources are relative.
  22803. * - sourcesContent: Optional. An array of contents of the original source files.
  22804. * - mappings: A string of base64 VLQs which contain the actual mappings.
  22805. * - file: Optional. The generated file this source map is associated with.
  22806. *
  22807. * Here is an example source map, taken from the source map spec[0]:
  22808. *
  22809. * {
  22810. * version : 3,
  22811. * file: "out.js",
  22812. * sourceRoot : "",
  22813. * sources: ["foo.js", "bar.js"],
  22814. * names: ["src", "maps", "are", "fun"],
  22815. * mappings: "AA,AB;;ABCDE;"
  22816. * }
  22817. *
  22818. * The second parameter, if given, is a string whose value is the URL
  22819. * at which the source map was found. This URL is used to compute the
  22820. * sources array.
  22821. *
  22822. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  22823. */
  22824. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  22825. var sourceMap = aSourceMap;
  22826. if (typeof aSourceMap === 'string') {
  22827. sourceMap = util.parseSourceMapInput(aSourceMap);
  22828. }
  22829. var version = util.getArg(sourceMap, 'version');
  22830. var sources = util.getArg(sourceMap, 'sources');
  22831. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  22832. // requires the array) to play nice here.
  22833. var names = util.getArg(sourceMap, 'names', []);
  22834. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  22835. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  22836. var mappings = util.getArg(sourceMap, 'mappings');
  22837. var file = util.getArg(sourceMap, 'file', null);
  22838. // Once again, Sass deviates from the spec and supplies the version as a
  22839. // string rather than a number, so we use loose equality checking here.
  22840. if (version != this._version) {
  22841. throw new Error('Unsupported version: ' + version);
  22842. }
  22843. if (sourceRoot) {
  22844. sourceRoot = util.normalize(sourceRoot);
  22845. }
  22846. sources = sources
  22847. .map(String)
  22848. // Some source maps produce relative source paths like "./foo.js" instead of
  22849. // "foo.js". Normalize these first so that future comparisons will succeed.
  22850. // See bugzil.la/1090768.
  22851. .map(util.normalize)
  22852. // Always ensure that absolute sources are internally stored relative to
  22853. // the source root, if the source root is absolute. Not doing this would
  22854. // be particularly problematic when the source root is a prefix of the
  22855. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  22856. .map(function (source) {
  22857. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  22858. ? util.relative(sourceRoot, source)
  22859. : source;
  22860. });
  22861. // Pass `true` below to allow duplicate names and sources. While source maps
  22862. // are intended to be compressed and deduplicated, the TypeScript compiler
  22863. // sometimes generates source maps with duplicates in them. See Github issue
  22864. // #72 and bugzil.la/889492.
  22865. this._names = ArraySet.fromArray(names.map(String), true);
  22866. this._sources = ArraySet.fromArray(sources, true);
  22867. this._absoluteSources = this._sources.toArray().map(function (s) {
  22868. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  22869. });
  22870. this.sourceRoot = sourceRoot;
  22871. this.sourcesContent = sourcesContent;
  22872. this._mappings = mappings;
  22873. this._sourceMapURL = aSourceMapURL;
  22874. this.file = file;
  22875. }
  22876. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  22877. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  22878. /**
  22879. * Utility function to find the index of a source. Returns -1 if not
  22880. * found.
  22881. */
  22882. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  22883. var relativeSource = aSource;
  22884. if (this.sourceRoot != null) {
  22885. relativeSource = util.relative(this.sourceRoot, relativeSource);
  22886. }
  22887. if (this._sources.has(relativeSource)) {
  22888. return this._sources.indexOf(relativeSource);
  22889. }
  22890. // Maybe aSource is an absolute URL as returned by |sources|. In
  22891. // this case we can't simply undo the transform.
  22892. var i;
  22893. for (i = 0; i < this._absoluteSources.length; ++i) {
  22894. if (this._absoluteSources[i] == aSource) {
  22895. return i;
  22896. }
  22897. }
  22898. return -1;
  22899. };
  22900. /**
  22901. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  22902. *
  22903. * @param SourceMapGenerator aSourceMap
  22904. * The source map that will be consumed.
  22905. * @param String aSourceMapURL
  22906. * The URL at which the source map can be found (optional)
  22907. * @returns BasicSourceMapConsumer
  22908. */
  22909. BasicSourceMapConsumer.fromSourceMap =
  22910. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  22911. var smc = Object.create(BasicSourceMapConsumer.prototype);
  22912. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  22913. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  22914. smc.sourceRoot = aSourceMap._sourceRoot;
  22915. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  22916. smc.sourceRoot);
  22917. smc.file = aSourceMap._file;
  22918. smc._sourceMapURL = aSourceMapURL;
  22919. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  22920. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  22921. });
  22922. // Because we are modifying the entries (by converting string sources and
  22923. // names to indices into the sources and names ArraySets), we have to make
  22924. // a copy of the entry or else bad things happen. Shared mutable state
  22925. // strikes again! See github issue #191.
  22926. var generatedMappings = aSourceMap._mappings.toArray().slice();
  22927. var destGeneratedMappings = smc.__generatedMappings = [];
  22928. var destOriginalMappings = smc.__originalMappings = [];
  22929. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  22930. var srcMapping = generatedMappings[i];
  22931. var destMapping = new Mapping;
  22932. destMapping.generatedLine = srcMapping.generatedLine;
  22933. destMapping.generatedColumn = srcMapping.generatedColumn;
  22934. if (srcMapping.source) {
  22935. destMapping.source = sources.indexOf(srcMapping.source);
  22936. destMapping.originalLine = srcMapping.originalLine;
  22937. destMapping.originalColumn = srcMapping.originalColumn;
  22938. if (srcMapping.name) {
  22939. destMapping.name = names.indexOf(srcMapping.name);
  22940. }
  22941. destOriginalMappings.push(destMapping);
  22942. }
  22943. destGeneratedMappings.push(destMapping);
  22944. }
  22945. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  22946. return smc;
  22947. };
  22948. /**
  22949. * The version of the source mapping spec that we are consuming.
  22950. */
  22951. BasicSourceMapConsumer.prototype._version = 3;
  22952. /**
  22953. * The list of original sources.
  22954. */
  22955. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  22956. get: function () {
  22957. return this._absoluteSources.slice();
  22958. }
  22959. });
  22960. /**
  22961. * Provide the JIT with a nice shape / hidden class.
  22962. */
  22963. function Mapping() {
  22964. this.generatedLine = 0;
  22965. this.generatedColumn = 0;
  22966. this.source = null;
  22967. this.originalLine = null;
  22968. this.originalColumn = null;
  22969. this.name = null;
  22970. }
  22971. /**
  22972. * Parse the mappings in a string in to a data structure which we can easily
  22973. * query (the ordered arrays in the `this.__generatedMappings` and
  22974. * `this.__originalMappings` properties).
  22975. */
  22976. const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine;
  22977. function sortGenerated(array, start) {
  22978. let l = array.length;
  22979. let n = array.length - start;
  22980. if (n <= 1) {
  22981. return;
  22982. } else if (n == 2) {
  22983. let a = array[start];
  22984. let b = array[start + 1];
  22985. if (compareGenerated(a, b) > 0) {
  22986. array[start] = b;
  22987. array[start + 1] = a;
  22988. }
  22989. } else if (n < 20) {
  22990. for (let i = start; i < l; i++) {
  22991. for (let j = i; j > start; j--) {
  22992. let a = array[j - 1];
  22993. let b = array[j];
  22994. if (compareGenerated(a, b) <= 0) {
  22995. break;
  22996. }
  22997. array[j - 1] = b;
  22998. array[j] = a;
  22999. }
  23000. }
  23001. } else {
  23002. quickSort(array, compareGenerated, start);
  23003. }
  23004. }
  23005. BasicSourceMapConsumer.prototype._parseMappings =
  23006. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  23007. var generatedLine = 1;
  23008. var previousGeneratedColumn = 0;
  23009. var previousOriginalLine = 0;
  23010. var previousOriginalColumn = 0;
  23011. var previousSource = 0;
  23012. var previousName = 0;
  23013. var length = aStr.length;
  23014. var index = 0;
  23015. var temp = {};
  23016. var originalMappings = [];
  23017. var generatedMappings = [];
  23018. var mapping, segment, end, value;
  23019. let subarrayStart = 0;
  23020. while (index < length) {
  23021. if (aStr.charAt(index) === ';') {
  23022. generatedLine++;
  23023. index++;
  23024. previousGeneratedColumn = 0;
  23025. sortGenerated(generatedMappings, subarrayStart);
  23026. subarrayStart = generatedMappings.length;
  23027. }
  23028. else if (aStr.charAt(index) === ',') {
  23029. index++;
  23030. }
  23031. else {
  23032. mapping = new Mapping();
  23033. mapping.generatedLine = generatedLine;
  23034. for (end = index; end < length; end++) {
  23035. if (this._charIsMappingSeparator(aStr, end)) {
  23036. break;
  23037. }
  23038. }
  23039. aStr.slice(index, end);
  23040. segment = [];
  23041. while (index < end) {
  23042. base64VLQ.decode(aStr, index, temp);
  23043. value = temp.value;
  23044. index = temp.rest;
  23045. segment.push(value);
  23046. }
  23047. if (segment.length === 2) {
  23048. throw new Error('Found a source, but no line and column');
  23049. }
  23050. if (segment.length === 3) {
  23051. throw new Error('Found a source and line, but no column');
  23052. }
  23053. // Generated column.
  23054. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  23055. previousGeneratedColumn = mapping.generatedColumn;
  23056. if (segment.length > 1) {
  23057. // Original source.
  23058. mapping.source = previousSource + segment[1];
  23059. previousSource += segment[1];
  23060. // Original line.
  23061. mapping.originalLine = previousOriginalLine + segment[2];
  23062. previousOriginalLine = mapping.originalLine;
  23063. // Lines are stored 0-based
  23064. mapping.originalLine += 1;
  23065. // Original column.
  23066. mapping.originalColumn = previousOriginalColumn + segment[3];
  23067. previousOriginalColumn = mapping.originalColumn;
  23068. if (segment.length > 4) {
  23069. // Original name.
  23070. mapping.name = previousName + segment[4];
  23071. previousName += segment[4];
  23072. }
  23073. }
  23074. generatedMappings.push(mapping);
  23075. if (typeof mapping.originalLine === 'number') {
  23076. let currentSource = mapping.source;
  23077. while (originalMappings.length <= currentSource) {
  23078. originalMappings.push(null);
  23079. }
  23080. if (originalMappings[currentSource] === null) {
  23081. originalMappings[currentSource] = [];
  23082. }
  23083. originalMappings[currentSource].push(mapping);
  23084. }
  23085. }
  23086. }
  23087. sortGenerated(generatedMappings, subarrayStart);
  23088. this.__generatedMappings = generatedMappings;
  23089. for (var i = 0; i < originalMappings.length; i++) {
  23090. if (originalMappings[i] != null) {
  23091. quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource);
  23092. }
  23093. }
  23094. this.__originalMappings = [].concat(...originalMappings);
  23095. };
  23096. /**
  23097. * Find the mapping that best matches the hypothetical "needle" mapping that
  23098. * we are searching for in the given "haystack" of mappings.
  23099. */
  23100. BasicSourceMapConsumer.prototype._findMapping =
  23101. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  23102. aColumnName, aComparator, aBias) {
  23103. // To return the position we are searching for, we must first find the
  23104. // mapping for the given position and then return the opposite position it
  23105. // points to. Because the mappings are sorted, we can use binary search to
  23106. // find the best mapping.
  23107. if (aNeedle[aLineName] <= 0) {
  23108. throw new TypeError('Line must be greater than or equal to 1, got '
  23109. + aNeedle[aLineName]);
  23110. }
  23111. if (aNeedle[aColumnName] < 0) {
  23112. throw new TypeError('Column must be greater than or equal to 0, got '
  23113. + aNeedle[aColumnName]);
  23114. }
  23115. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  23116. };
  23117. /**
  23118. * Compute the last column for each generated mapping. The last column is
  23119. * inclusive.
  23120. */
  23121. BasicSourceMapConsumer.prototype.computeColumnSpans =
  23122. function SourceMapConsumer_computeColumnSpans() {
  23123. for (var index = 0; index < this._generatedMappings.length; ++index) {
  23124. var mapping = this._generatedMappings[index];
  23125. // Mappings do not contain a field for the last generated columnt. We
  23126. // can come up with an optimistic estimate, however, by assuming that
  23127. // mappings are contiguous (i.e. given two consecutive mappings, the
  23128. // first mapping ends where the second one starts).
  23129. if (index + 1 < this._generatedMappings.length) {
  23130. var nextMapping = this._generatedMappings[index + 1];
  23131. if (mapping.generatedLine === nextMapping.generatedLine) {
  23132. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  23133. continue;
  23134. }
  23135. }
  23136. // The last mapping for each line spans the entire line.
  23137. mapping.lastGeneratedColumn = Infinity;
  23138. }
  23139. };
  23140. /**
  23141. * Returns the original source, line, and column information for the generated
  23142. * source's line and column positions provided. The only argument is an object
  23143. * with the following properties:
  23144. *
  23145. * - line: The line number in the generated source. The line number
  23146. * is 1-based.
  23147. * - column: The column number in the generated source. The column
  23148. * number is 0-based.
  23149. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  23150. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  23151. * closest element that is smaller than or greater than the one we are
  23152. * searching for, respectively, if the exact element cannot be found.
  23153. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  23154. *
  23155. * and an object is returned with the following properties:
  23156. *
  23157. * - source: The original source file, or null.
  23158. * - line: The line number in the original source, or null. The
  23159. * line number is 1-based.
  23160. * - column: The column number in the original source, or null. The
  23161. * column number is 0-based.
  23162. * - name: The original identifier, or null.
  23163. */
  23164. BasicSourceMapConsumer.prototype.originalPositionFor =
  23165. function SourceMapConsumer_originalPositionFor(aArgs) {
  23166. var needle = {
  23167. generatedLine: util.getArg(aArgs, 'line'),
  23168. generatedColumn: util.getArg(aArgs, 'column')
  23169. };
  23170. var index = this._findMapping(
  23171. needle,
  23172. this._generatedMappings,
  23173. "generatedLine",
  23174. "generatedColumn",
  23175. util.compareByGeneratedPositionsDeflated,
  23176. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  23177. );
  23178. if (index >= 0) {
  23179. var mapping = this._generatedMappings[index];
  23180. if (mapping.generatedLine === needle.generatedLine) {
  23181. var source = util.getArg(mapping, 'source', null);
  23182. if (source !== null) {
  23183. source = this._sources.at(source);
  23184. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  23185. }
  23186. var name = util.getArg(mapping, 'name', null);
  23187. if (name !== null) {
  23188. name = this._names.at(name);
  23189. }
  23190. return {
  23191. source: source,
  23192. line: util.getArg(mapping, 'originalLine', null),
  23193. column: util.getArg(mapping, 'originalColumn', null),
  23194. name: name
  23195. };
  23196. }
  23197. }
  23198. return {
  23199. source: null,
  23200. line: null,
  23201. column: null,
  23202. name: null
  23203. };
  23204. };
  23205. /**
  23206. * Return true if we have the source content for every source in the source
  23207. * map, false otherwise.
  23208. */
  23209. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  23210. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  23211. if (!this.sourcesContent) {
  23212. return false;
  23213. }
  23214. return this.sourcesContent.length >= this._sources.size() &&
  23215. !this.sourcesContent.some(function (sc) { return sc == null; });
  23216. };
  23217. /**
  23218. * Returns the original source content. The only argument is the url of the
  23219. * original source file. Returns null if no original source content is
  23220. * available.
  23221. */
  23222. BasicSourceMapConsumer.prototype.sourceContentFor =
  23223. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  23224. if (!this.sourcesContent) {
  23225. return null;
  23226. }
  23227. var index = this._findSourceIndex(aSource);
  23228. if (index >= 0) {
  23229. return this.sourcesContent[index];
  23230. }
  23231. var relativeSource = aSource;
  23232. if (this.sourceRoot != null) {
  23233. relativeSource = util.relative(this.sourceRoot, relativeSource);
  23234. }
  23235. var url;
  23236. if (this.sourceRoot != null
  23237. && (url = util.urlParse(this.sourceRoot))) {
  23238. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  23239. // many users. We can help them out when they expect file:// URIs to
  23240. // behave like it would if they were running a local HTTP server. See
  23241. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  23242. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  23243. if (url.scheme == "file"
  23244. && this._sources.has(fileUriAbsPath)) {
  23245. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  23246. }
  23247. if ((!url.path || url.path == "/")
  23248. && this._sources.has("/" + relativeSource)) {
  23249. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  23250. }
  23251. }
  23252. // This function is used recursively from
  23253. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  23254. // don't want to throw if we can't find the source - we just want to
  23255. // return null, so we provide a flag to exit gracefully.
  23256. if (nullOnMissing) {
  23257. return null;
  23258. }
  23259. else {
  23260. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  23261. }
  23262. };
  23263. /**
  23264. * Returns the generated line and column information for the original source,
  23265. * line, and column positions provided. The only argument is an object with
  23266. * the following properties:
  23267. *
  23268. * - source: The filename of the original source.
  23269. * - line: The line number in the original source. The line number
  23270. * is 1-based.
  23271. * - column: The column number in the original source. The column
  23272. * number is 0-based.
  23273. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  23274. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  23275. * closest element that is smaller than or greater than the one we are
  23276. * searching for, respectively, if the exact element cannot be found.
  23277. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  23278. *
  23279. * and an object is returned with the following properties:
  23280. *
  23281. * - line: The line number in the generated source, or null. The
  23282. * line number is 1-based.
  23283. * - column: The column number in the generated source, or null.
  23284. * The column number is 0-based.
  23285. */
  23286. BasicSourceMapConsumer.prototype.generatedPositionFor =
  23287. function SourceMapConsumer_generatedPositionFor(aArgs) {
  23288. var source = util.getArg(aArgs, 'source');
  23289. source = this._findSourceIndex(source);
  23290. if (source < 0) {
  23291. return {
  23292. line: null,
  23293. column: null,
  23294. lastColumn: null
  23295. };
  23296. }
  23297. var needle = {
  23298. source: source,
  23299. originalLine: util.getArg(aArgs, 'line'),
  23300. originalColumn: util.getArg(aArgs, 'column')
  23301. };
  23302. var index = this._findMapping(
  23303. needle,
  23304. this._originalMappings,
  23305. "originalLine",
  23306. "originalColumn",
  23307. util.compareByOriginalPositions,
  23308. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  23309. );
  23310. if (index >= 0) {
  23311. var mapping = this._originalMappings[index];
  23312. if (mapping.source === needle.source) {
  23313. return {
  23314. line: util.getArg(mapping, 'generatedLine', null),
  23315. column: util.getArg(mapping, 'generatedColumn', null),
  23316. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  23317. };
  23318. }
  23319. }
  23320. return {
  23321. line: null,
  23322. column: null,
  23323. lastColumn: null
  23324. };
  23325. };
  23326. sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer;
  23327. /**
  23328. * An IndexedSourceMapConsumer instance represents a parsed source map which
  23329. * we can query for information. It differs from BasicSourceMapConsumer in
  23330. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  23331. * input.
  23332. *
  23333. * The first parameter is a raw source map (either as a JSON string, or already
  23334. * parsed to an object). According to the spec for indexed source maps, they
  23335. * have the following attributes:
  23336. *
  23337. * - version: Which version of the source map spec this map is following.
  23338. * - file: Optional. The generated file this source map is associated with.
  23339. * - sections: A list of section definitions.
  23340. *
  23341. * Each value under the "sections" field has two fields:
  23342. * - offset: The offset into the original specified at which this section
  23343. * begins to apply, defined as an object with a "line" and "column"
  23344. * field.
  23345. * - map: A source map definition. This source map could also be indexed,
  23346. * but doesn't have to be.
  23347. *
  23348. * Instead of the "map" field, it's also possible to have a "url" field
  23349. * specifying a URL to retrieve a source map from, but that's currently
  23350. * unsupported.
  23351. *
  23352. * Here's an example source map, taken from the source map spec[0], but
  23353. * modified to omit a section which uses the "url" field.
  23354. *
  23355. * {
  23356. * version : 3,
  23357. * file: "app.js",
  23358. * sections: [{
  23359. * offset: {line:100, column:10},
  23360. * map: {
  23361. * version : 3,
  23362. * file: "section.js",
  23363. * sources: ["foo.js", "bar.js"],
  23364. * names: ["src", "maps", "are", "fun"],
  23365. * mappings: "AAAA,E;;ABCDE;"
  23366. * }
  23367. * }],
  23368. * }
  23369. *
  23370. * The second parameter, if given, is a string whose value is the URL
  23371. * at which the source map was found. This URL is used to compute the
  23372. * sources array.
  23373. *
  23374. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  23375. */
  23376. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  23377. var sourceMap = aSourceMap;
  23378. if (typeof aSourceMap === 'string') {
  23379. sourceMap = util.parseSourceMapInput(aSourceMap);
  23380. }
  23381. var version = util.getArg(sourceMap, 'version');
  23382. var sections = util.getArg(sourceMap, 'sections');
  23383. if (version != this._version) {
  23384. throw new Error('Unsupported version: ' + version);
  23385. }
  23386. this._sources = new ArraySet();
  23387. this._names = new ArraySet();
  23388. var lastOffset = {
  23389. line: -1,
  23390. column: 0
  23391. };
  23392. this._sections = sections.map(function (s) {
  23393. if (s.url) {
  23394. // The url field will require support for asynchronicity.
  23395. // See https://github.com/mozilla/source-map/issues/16
  23396. throw new Error('Support for url field in sections not implemented.');
  23397. }
  23398. var offset = util.getArg(s, 'offset');
  23399. var offsetLine = util.getArg(offset, 'line');
  23400. var offsetColumn = util.getArg(offset, 'column');
  23401. if (offsetLine < lastOffset.line ||
  23402. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  23403. throw new Error('Section offsets must be ordered and non-overlapping.');
  23404. }
  23405. lastOffset = offset;
  23406. return {
  23407. generatedOffset: {
  23408. // The offset fields are 0-based, but we use 1-based indices when
  23409. // encoding/decoding from VLQ.
  23410. generatedLine: offsetLine + 1,
  23411. generatedColumn: offsetColumn + 1
  23412. },
  23413. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  23414. }
  23415. });
  23416. }
  23417. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  23418. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  23419. /**
  23420. * The version of the source mapping spec that we are consuming.
  23421. */
  23422. IndexedSourceMapConsumer.prototype._version = 3;
  23423. /**
  23424. * The list of original sources.
  23425. */
  23426. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  23427. get: function () {
  23428. var sources = [];
  23429. for (var i = 0; i < this._sections.length; i++) {
  23430. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  23431. sources.push(this._sections[i].consumer.sources[j]);
  23432. }
  23433. }
  23434. return sources;
  23435. }
  23436. });
  23437. /**
  23438. * Returns the original source, line, and column information for the generated
  23439. * source's line and column positions provided. The only argument is an object
  23440. * with the following properties:
  23441. *
  23442. * - line: The line number in the generated source. The line number
  23443. * is 1-based.
  23444. * - column: The column number in the generated source. The column
  23445. * number is 0-based.
  23446. *
  23447. * and an object is returned with the following properties:
  23448. *
  23449. * - source: The original source file, or null.
  23450. * - line: The line number in the original source, or null. The
  23451. * line number is 1-based.
  23452. * - column: The column number in the original source, or null. The
  23453. * column number is 0-based.
  23454. * - name: The original identifier, or null.
  23455. */
  23456. IndexedSourceMapConsumer.prototype.originalPositionFor =
  23457. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  23458. var needle = {
  23459. generatedLine: util.getArg(aArgs, 'line'),
  23460. generatedColumn: util.getArg(aArgs, 'column')
  23461. };
  23462. // Find the section containing the generated position we're trying to map
  23463. // to an original position.
  23464. var sectionIndex = binarySearch.search(needle, this._sections,
  23465. function(needle, section) {
  23466. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  23467. if (cmp) {
  23468. return cmp;
  23469. }
  23470. return (needle.generatedColumn -
  23471. section.generatedOffset.generatedColumn);
  23472. });
  23473. var section = this._sections[sectionIndex];
  23474. if (!section) {
  23475. return {
  23476. source: null,
  23477. line: null,
  23478. column: null,
  23479. name: null
  23480. };
  23481. }
  23482. return section.consumer.originalPositionFor({
  23483. line: needle.generatedLine -
  23484. (section.generatedOffset.generatedLine - 1),
  23485. column: needle.generatedColumn -
  23486. (section.generatedOffset.generatedLine === needle.generatedLine
  23487. ? section.generatedOffset.generatedColumn - 1
  23488. : 0),
  23489. bias: aArgs.bias
  23490. });
  23491. };
  23492. /**
  23493. * Return true if we have the source content for every source in the source
  23494. * map, false otherwise.
  23495. */
  23496. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  23497. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  23498. return this._sections.every(function (s) {
  23499. return s.consumer.hasContentsOfAllSources();
  23500. });
  23501. };
  23502. /**
  23503. * Returns the original source content. The only argument is the url of the
  23504. * original source file. Returns null if no original source content is
  23505. * available.
  23506. */
  23507. IndexedSourceMapConsumer.prototype.sourceContentFor =
  23508. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  23509. for (var i = 0; i < this._sections.length; i++) {
  23510. var section = this._sections[i];
  23511. var content = section.consumer.sourceContentFor(aSource, true);
  23512. if (content || content === '') {
  23513. return content;
  23514. }
  23515. }
  23516. if (nullOnMissing) {
  23517. return null;
  23518. }
  23519. else {
  23520. throw new Error('"' + aSource + '" is not in the SourceMap.');
  23521. }
  23522. };
  23523. /**
  23524. * Returns the generated line and column information for the original source,
  23525. * line, and column positions provided. The only argument is an object with
  23526. * the following properties:
  23527. *
  23528. * - source: The filename of the original source.
  23529. * - line: The line number in the original source. The line number
  23530. * is 1-based.
  23531. * - column: The column number in the original source. The column
  23532. * number is 0-based.
  23533. *
  23534. * and an object is returned with the following properties:
  23535. *
  23536. * - line: The line number in the generated source, or null. The
  23537. * line number is 1-based.
  23538. * - column: The column number in the generated source, or null.
  23539. * The column number is 0-based.
  23540. */
  23541. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  23542. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  23543. for (var i = 0; i < this._sections.length; i++) {
  23544. var section = this._sections[i];
  23545. // Only consider this section if the requested source is in the list of
  23546. // sources of the consumer.
  23547. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  23548. continue;
  23549. }
  23550. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  23551. if (generatedPosition) {
  23552. var ret = {
  23553. line: generatedPosition.line +
  23554. (section.generatedOffset.generatedLine - 1),
  23555. column: generatedPosition.column +
  23556. (section.generatedOffset.generatedLine === generatedPosition.line
  23557. ? section.generatedOffset.generatedColumn - 1
  23558. : 0)
  23559. };
  23560. return ret;
  23561. }
  23562. }
  23563. return {
  23564. line: null,
  23565. column: null
  23566. };
  23567. };
  23568. /**
  23569. * Parse the mappings in a string in to a data structure which we can easily
  23570. * query (the ordered arrays in the `this.__generatedMappings` and
  23571. * `this.__originalMappings` properties).
  23572. */
  23573. IndexedSourceMapConsumer.prototype._parseMappings =
  23574. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  23575. this.__generatedMappings = [];
  23576. this.__originalMappings = [];
  23577. for (var i = 0; i < this._sections.length; i++) {
  23578. var section = this._sections[i];
  23579. var sectionMappings = section.consumer._generatedMappings;
  23580. for (var j = 0; j < sectionMappings.length; j++) {
  23581. var mapping = sectionMappings[j];
  23582. var source = section.consumer._sources.at(mapping.source);
  23583. if(source !== null) {
  23584. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  23585. }
  23586. this._sources.add(source);
  23587. source = this._sources.indexOf(source);
  23588. var name = null;
  23589. if (mapping.name) {
  23590. name = section.consumer._names.at(mapping.name);
  23591. this._names.add(name);
  23592. name = this._names.indexOf(name);
  23593. }
  23594. // The mappings coming from the consumer for the section have
  23595. // generated positions relative to the start of the section, so we
  23596. // need to offset them to be relative to the start of the concatenated
  23597. // generated file.
  23598. var adjustedMapping = {
  23599. source: source,
  23600. generatedLine: mapping.generatedLine +
  23601. (section.generatedOffset.generatedLine - 1),
  23602. generatedColumn: mapping.generatedColumn +
  23603. (section.generatedOffset.generatedLine === mapping.generatedLine
  23604. ? section.generatedOffset.generatedColumn - 1
  23605. : 0),
  23606. originalLine: mapping.originalLine,
  23607. originalColumn: mapping.originalColumn,
  23608. name: name
  23609. };
  23610. this.__generatedMappings.push(adjustedMapping);
  23611. if (typeof adjustedMapping.originalLine === 'number') {
  23612. this.__originalMappings.push(adjustedMapping);
  23613. }
  23614. }
  23615. }
  23616. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  23617. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  23618. };
  23619. sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  23620. return sourceMapConsumer$1;
  23621. }
  23622. var sourceNode$1 = {};
  23623. /* -*- Mode: js; js-indent-level: 2; -*- */
  23624. var hasRequiredSourceNode$1;
  23625. function requireSourceNode$1 () {
  23626. if (hasRequiredSourceNode$1) return sourceNode$1;
  23627. hasRequiredSourceNode$1 = 1;
  23628. /*
  23629. * Copyright 2011 Mozilla Foundation and contributors
  23630. * Licensed under the New BSD license. See LICENSE or:
  23631. * http://opensource.org/licenses/BSD-3-Clause
  23632. */
  23633. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator$1().SourceMapGenerator;
  23634. var util = /*@__PURE__*/ requireUtil$2();
  23635. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  23636. // operating systems these days (capturing the result).
  23637. var REGEX_NEWLINE = /(\r?\n)/;
  23638. // Newline character code for charCodeAt() comparisons
  23639. var NEWLINE_CODE = 10;
  23640. // Private symbol for identifying `SourceNode`s when multiple versions of
  23641. // the source-map library are loaded. This MUST NOT CHANGE across
  23642. // versions!
  23643. var isSourceNode = "$$$isSourceNode$$$";
  23644. /**
  23645. * SourceNodes provide a way to abstract over interpolating/concatenating
  23646. * snippets of generated JavaScript source code while maintaining the line and
  23647. * column information associated with the original source code.
  23648. *
  23649. * @param aLine The original line number.
  23650. * @param aColumn The original column number.
  23651. * @param aSource The original source's filename.
  23652. * @param aChunks Optional. An array of strings which are snippets of
  23653. * generated JS, or other SourceNodes.
  23654. * @param aName The original identifier.
  23655. */
  23656. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  23657. this.children = [];
  23658. this.sourceContents = {};
  23659. this.line = aLine == null ? null : aLine;
  23660. this.column = aColumn == null ? null : aColumn;
  23661. this.source = aSource == null ? null : aSource;
  23662. this.name = aName == null ? null : aName;
  23663. this[isSourceNode] = true;
  23664. if (aChunks != null) this.add(aChunks);
  23665. }
  23666. /**
  23667. * Creates a SourceNode from generated code and a SourceMapConsumer.
  23668. *
  23669. * @param aGeneratedCode The generated code
  23670. * @param aSourceMapConsumer The SourceMap for the generated code
  23671. * @param aRelativePath Optional. The path that relative sources in the
  23672. * SourceMapConsumer should be relative to.
  23673. */
  23674. SourceNode.fromStringWithSourceMap =
  23675. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  23676. // The SourceNode we want to fill with the generated code
  23677. // and the SourceMap
  23678. var node = new SourceNode();
  23679. // All even indices of this array are one line of the generated code,
  23680. // while all odd indices are the newlines between two adjacent lines
  23681. // (since `REGEX_NEWLINE` captures its match).
  23682. // Processed fragments are accessed by calling `shiftNextLine`.
  23683. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  23684. var remainingLinesIndex = 0;
  23685. var shiftNextLine = function() {
  23686. var lineContents = getNextLine();
  23687. // The last line of a file might not have a newline.
  23688. var newLine = getNextLine() || "";
  23689. return lineContents + newLine;
  23690. function getNextLine() {
  23691. return remainingLinesIndex < remainingLines.length ?
  23692. remainingLines[remainingLinesIndex++] : undefined;
  23693. }
  23694. };
  23695. // We need to remember the position of "remainingLines"
  23696. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  23697. // The generate SourceNodes we need a code range.
  23698. // To extract it current and last mapping is used.
  23699. // Here we store the last mapping.
  23700. var lastMapping = null;
  23701. aSourceMapConsumer.eachMapping(function (mapping) {
  23702. if (lastMapping !== null) {
  23703. // We add the code from "lastMapping" to "mapping":
  23704. // First check if there is a new line in between.
  23705. if (lastGeneratedLine < mapping.generatedLine) {
  23706. // Associate first line with "lastMapping"
  23707. addMappingWithCode(lastMapping, shiftNextLine());
  23708. lastGeneratedLine++;
  23709. lastGeneratedColumn = 0;
  23710. // The remaining code is added without mapping
  23711. } else {
  23712. // There is no new line in between.
  23713. // Associate the code between "lastGeneratedColumn" and
  23714. // "mapping.generatedColumn" with "lastMapping"
  23715. var nextLine = remainingLines[remainingLinesIndex] || '';
  23716. var code = nextLine.substr(0, mapping.generatedColumn -
  23717. lastGeneratedColumn);
  23718. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  23719. lastGeneratedColumn);
  23720. lastGeneratedColumn = mapping.generatedColumn;
  23721. addMappingWithCode(lastMapping, code);
  23722. // No more remaining code, continue
  23723. lastMapping = mapping;
  23724. return;
  23725. }
  23726. }
  23727. // We add the generated code until the first mapping
  23728. // to the SourceNode without any mapping.
  23729. // Each line is added as separate string.
  23730. while (lastGeneratedLine < mapping.generatedLine) {
  23731. node.add(shiftNextLine());
  23732. lastGeneratedLine++;
  23733. }
  23734. if (lastGeneratedColumn < mapping.generatedColumn) {
  23735. var nextLine = remainingLines[remainingLinesIndex] || '';
  23736. node.add(nextLine.substr(0, mapping.generatedColumn));
  23737. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  23738. lastGeneratedColumn = mapping.generatedColumn;
  23739. }
  23740. lastMapping = mapping;
  23741. }, this);
  23742. // We have processed all mappings.
  23743. if (remainingLinesIndex < remainingLines.length) {
  23744. if (lastMapping) {
  23745. // Associate the remaining code in the current line with "lastMapping"
  23746. addMappingWithCode(lastMapping, shiftNextLine());
  23747. }
  23748. // and add the remaining lines without any mapping
  23749. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  23750. }
  23751. // Copy sourcesContent into SourceNode
  23752. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  23753. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  23754. if (content != null) {
  23755. if (aRelativePath != null) {
  23756. sourceFile = util.join(aRelativePath, sourceFile);
  23757. }
  23758. node.setSourceContent(sourceFile, content);
  23759. }
  23760. });
  23761. return node;
  23762. function addMappingWithCode(mapping, code) {
  23763. if (mapping === null || mapping.source === undefined) {
  23764. node.add(code);
  23765. } else {
  23766. var source = aRelativePath
  23767. ? util.join(aRelativePath, mapping.source)
  23768. : mapping.source;
  23769. node.add(new SourceNode(mapping.originalLine,
  23770. mapping.originalColumn,
  23771. source,
  23772. code,
  23773. mapping.name));
  23774. }
  23775. }
  23776. };
  23777. /**
  23778. * Add a chunk of generated JS to this source node.
  23779. *
  23780. * @param aChunk A string snippet of generated JS code, another instance of
  23781. * SourceNode, or an array where each member is one of those things.
  23782. */
  23783. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  23784. if (Array.isArray(aChunk)) {
  23785. aChunk.forEach(function (chunk) {
  23786. this.add(chunk);
  23787. }, this);
  23788. }
  23789. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  23790. if (aChunk) {
  23791. this.children.push(aChunk);
  23792. }
  23793. }
  23794. else {
  23795. throw new TypeError(
  23796. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  23797. );
  23798. }
  23799. return this;
  23800. };
  23801. /**
  23802. * Add a chunk of generated JS to the beginning of this source node.
  23803. *
  23804. * @param aChunk A string snippet of generated JS code, another instance of
  23805. * SourceNode, or an array where each member is one of those things.
  23806. */
  23807. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  23808. if (Array.isArray(aChunk)) {
  23809. for (var i = aChunk.length-1; i >= 0; i--) {
  23810. this.prepend(aChunk[i]);
  23811. }
  23812. }
  23813. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  23814. this.children.unshift(aChunk);
  23815. }
  23816. else {
  23817. throw new TypeError(
  23818. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  23819. );
  23820. }
  23821. return this;
  23822. };
  23823. /**
  23824. * Walk over the tree of JS snippets in this node and its children. The
  23825. * walking function is called once for each snippet of JS and is passed that
  23826. * snippet and the its original associated source's line/column location.
  23827. *
  23828. * @param aFn The traversal function.
  23829. */
  23830. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  23831. var chunk;
  23832. for (var i = 0, len = this.children.length; i < len; i++) {
  23833. chunk = this.children[i];
  23834. if (chunk[isSourceNode]) {
  23835. chunk.walk(aFn);
  23836. }
  23837. else {
  23838. if (chunk !== '') {
  23839. aFn(chunk, { source: this.source,
  23840. line: this.line,
  23841. column: this.column,
  23842. name: this.name });
  23843. }
  23844. }
  23845. }
  23846. };
  23847. /**
  23848. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  23849. * each of `this.children`.
  23850. *
  23851. * @param aSep The separator.
  23852. */
  23853. SourceNode.prototype.join = function SourceNode_join(aSep) {
  23854. var newChildren;
  23855. var i;
  23856. var len = this.children.length;
  23857. if (len > 0) {
  23858. newChildren = [];
  23859. for (i = 0; i < len-1; i++) {
  23860. newChildren.push(this.children[i]);
  23861. newChildren.push(aSep);
  23862. }
  23863. newChildren.push(this.children[i]);
  23864. this.children = newChildren;
  23865. }
  23866. return this;
  23867. };
  23868. /**
  23869. * Call String.prototype.replace on the very right-most source snippet. Useful
  23870. * for trimming whitespace from the end of a source node, etc.
  23871. *
  23872. * @param aPattern The pattern to replace.
  23873. * @param aReplacement The thing to replace the pattern with.
  23874. */
  23875. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  23876. var lastChild = this.children[this.children.length - 1];
  23877. if (lastChild[isSourceNode]) {
  23878. lastChild.replaceRight(aPattern, aReplacement);
  23879. }
  23880. else if (typeof lastChild === 'string') {
  23881. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  23882. }
  23883. else {
  23884. this.children.push(''.replace(aPattern, aReplacement));
  23885. }
  23886. return this;
  23887. };
  23888. /**
  23889. * Set the source content for a source file. This will be added to the SourceMapGenerator
  23890. * in the sourcesContent field.
  23891. *
  23892. * @param aSourceFile The filename of the source file
  23893. * @param aSourceContent The content of the source file
  23894. */
  23895. SourceNode.prototype.setSourceContent =
  23896. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  23897. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  23898. };
  23899. /**
  23900. * Walk over the tree of SourceNodes. The walking function is called for each
  23901. * source file content and is passed the filename and source content.
  23902. *
  23903. * @param aFn The traversal function.
  23904. */
  23905. SourceNode.prototype.walkSourceContents =
  23906. function SourceNode_walkSourceContents(aFn) {
  23907. for (var i = 0, len = this.children.length; i < len; i++) {
  23908. if (this.children[i][isSourceNode]) {
  23909. this.children[i].walkSourceContents(aFn);
  23910. }
  23911. }
  23912. var sources = Object.keys(this.sourceContents);
  23913. for (var i = 0, len = sources.length; i < len; i++) {
  23914. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  23915. }
  23916. };
  23917. /**
  23918. * Return the string representation of this source node. Walks over the tree
  23919. * and concatenates all the various snippets together to one string.
  23920. */
  23921. SourceNode.prototype.toString = function SourceNode_toString() {
  23922. var str = "";
  23923. this.walk(function (chunk) {
  23924. str += chunk;
  23925. });
  23926. return str;
  23927. };
  23928. /**
  23929. * Returns the string representation of this source node along with a source
  23930. * map.
  23931. */
  23932. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  23933. var generated = {
  23934. code: "",
  23935. line: 1,
  23936. column: 0
  23937. };
  23938. var map = new SourceMapGenerator(aArgs);
  23939. var sourceMappingActive = false;
  23940. var lastOriginalSource = null;
  23941. var lastOriginalLine = null;
  23942. var lastOriginalColumn = null;
  23943. var lastOriginalName = null;
  23944. this.walk(function (chunk, original) {
  23945. generated.code += chunk;
  23946. if (original.source !== null
  23947. && original.line !== null
  23948. && original.column !== null) {
  23949. if(lastOriginalSource !== original.source
  23950. || lastOriginalLine !== original.line
  23951. || lastOriginalColumn !== original.column
  23952. || lastOriginalName !== original.name) {
  23953. map.addMapping({
  23954. source: original.source,
  23955. original: {
  23956. line: original.line,
  23957. column: original.column
  23958. },
  23959. generated: {
  23960. line: generated.line,
  23961. column: generated.column
  23962. },
  23963. name: original.name
  23964. });
  23965. }
  23966. lastOriginalSource = original.source;
  23967. lastOriginalLine = original.line;
  23968. lastOriginalColumn = original.column;
  23969. lastOriginalName = original.name;
  23970. sourceMappingActive = true;
  23971. } else if (sourceMappingActive) {
  23972. map.addMapping({
  23973. generated: {
  23974. line: generated.line,
  23975. column: generated.column
  23976. }
  23977. });
  23978. lastOriginalSource = null;
  23979. sourceMappingActive = false;
  23980. }
  23981. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  23982. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  23983. generated.line++;
  23984. generated.column = 0;
  23985. // Mappings end at eol
  23986. if (idx + 1 === length) {
  23987. lastOriginalSource = null;
  23988. sourceMappingActive = false;
  23989. } else if (sourceMappingActive) {
  23990. map.addMapping({
  23991. source: original.source,
  23992. original: {
  23993. line: original.line,
  23994. column: original.column
  23995. },
  23996. generated: {
  23997. line: generated.line,
  23998. column: generated.column
  23999. },
  24000. name: original.name
  24001. });
  24002. }
  24003. } else {
  24004. generated.column++;
  24005. }
  24006. }
  24007. });
  24008. this.walkSourceContents(function (sourceFile, sourceContent) {
  24009. map.setSourceContent(sourceFile, sourceContent);
  24010. });
  24011. return { code: generated.code, map: map };
  24012. };
  24013. sourceNode$1.SourceNode = SourceNode;
  24014. return sourceNode$1;
  24015. }
  24016. /*
  24017. * Copyright 2009-2011 Mozilla Foundation and contributors
  24018. * Licensed under the New BSD license. See LICENSE.txt or:
  24019. * http://opensource.org/licenses/BSD-3-Clause
  24020. */
  24021. var hasRequiredSourceMap$1;
  24022. function requireSourceMap$1 () {
  24023. if (hasRequiredSourceMap$1) return sourceMap$1;
  24024. hasRequiredSourceMap$1 = 1;
  24025. sourceMap$1.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator$1().SourceMapGenerator;
  24026. sourceMap$1.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer$1().SourceMapConsumer;
  24027. sourceMap$1.SourceNode = /*@__PURE__*/ requireSourceNode$1().SourceNode;
  24028. return sourceMap$1;
  24029. }
  24030. var sourceMapExports = /*@__PURE__*/ requireSourceMap$1();
  24031. const PURE_ANNOTATION = `/*@__PURE__*/`;
  24032. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  24033. function createCodegenContext(ast, {
  24034. mode = "function",
  24035. prefixIdentifiers = mode === "module",
  24036. sourceMap = false,
  24037. filename = `template.vue.html`,
  24038. scopeId = null,
  24039. optimizeImports = false,
  24040. runtimeGlobalName = `Vue`,
  24041. runtimeModuleName = `vue`,
  24042. ssrRuntimeModuleName = "vue/server-renderer",
  24043. ssr = false,
  24044. isTS = false,
  24045. inSSR = false
  24046. }) {
  24047. const context = {
  24048. mode,
  24049. prefixIdentifiers,
  24050. sourceMap,
  24051. filename,
  24052. scopeId,
  24053. optimizeImports,
  24054. runtimeGlobalName,
  24055. runtimeModuleName,
  24056. ssrRuntimeModuleName,
  24057. ssr,
  24058. isTS,
  24059. inSSR,
  24060. source: ast.source,
  24061. code: ``,
  24062. column: 1,
  24063. line: 1,
  24064. offset: 0,
  24065. indentLevel: 0,
  24066. pure: false,
  24067. map: void 0,
  24068. helper(key) {
  24069. return `_${helperNameMap[key]}`;
  24070. },
  24071. push(code, newlineIndex = -2 /* None */, node) {
  24072. context.code += code;
  24073. if (context.map) {
  24074. if (node) {
  24075. let name;
  24076. if (node.type === 4 && !node.isStatic) {
  24077. const content = node.content.replace(/^_ctx\./, "");
  24078. if (content !== node.content && isSimpleIdentifier(content)) {
  24079. name = content;
  24080. }
  24081. }
  24082. if (node.loc.source) {
  24083. addMapping(node.loc.start, name);
  24084. }
  24085. }
  24086. if (newlineIndex === -3 /* Unknown */) {
  24087. advancePositionWithMutation(context, code);
  24088. } else {
  24089. context.offset += code.length;
  24090. if (newlineIndex === -2 /* None */) {
  24091. context.column += code.length;
  24092. } else {
  24093. if (newlineIndex === -1 /* End */) {
  24094. newlineIndex = code.length - 1;
  24095. }
  24096. context.line++;
  24097. context.column = code.length - newlineIndex;
  24098. }
  24099. }
  24100. if (node && node.loc !== locStub && node.loc.source) {
  24101. addMapping(node.loc.end);
  24102. }
  24103. }
  24104. },
  24105. indent() {
  24106. newline(++context.indentLevel);
  24107. },
  24108. deindent(withoutNewLine = false) {
  24109. if (withoutNewLine) {
  24110. --context.indentLevel;
  24111. } else {
  24112. newline(--context.indentLevel);
  24113. }
  24114. },
  24115. newline() {
  24116. newline(context.indentLevel);
  24117. }
  24118. };
  24119. function newline(n) {
  24120. context.push("\n" + ` `.repeat(n), 0 /* Start */);
  24121. }
  24122. function addMapping(loc, name = null) {
  24123. const { _names, _mappings } = context.map;
  24124. if (name !== null && !_names.has(name)) _names.add(name);
  24125. _mappings.add({
  24126. originalLine: loc.line,
  24127. originalColumn: loc.column - 1,
  24128. // source-map column is 0 based
  24129. generatedLine: context.line,
  24130. generatedColumn: context.column - 1,
  24131. source: filename,
  24132. name
  24133. });
  24134. }
  24135. if (sourceMap) {
  24136. context.map = new sourceMapExports.SourceMapGenerator();
  24137. context.map.setSourceContent(filename, context.source);
  24138. context.map._sources.add(filename);
  24139. }
  24140. return context;
  24141. }
  24142. function generate(ast, options = {}) {
  24143. const context = createCodegenContext(ast, options);
  24144. if (options.onContextCreated) options.onContextCreated(context);
  24145. const {
  24146. mode,
  24147. push,
  24148. prefixIdentifiers,
  24149. indent,
  24150. deindent,
  24151. newline,
  24152. scopeId,
  24153. ssr
  24154. } = context;
  24155. const helpers = Array.from(ast.helpers);
  24156. const hasHelpers = helpers.length > 0;
  24157. const useWithBlock = !prefixIdentifiers && mode !== "module";
  24158. const genScopeId = scopeId != null && mode === "module";
  24159. const isSetupInlined = !!options.inline;
  24160. const preambleContext = isSetupInlined ? createCodegenContext(ast, options) : context;
  24161. if (mode === "module") {
  24162. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  24163. } else {
  24164. genFunctionPreamble(ast, preambleContext);
  24165. }
  24166. const functionName = ssr ? `ssrRender` : `render`;
  24167. const args = ssr ? ["_ctx", "_push", "_parent", "_attrs"] : ["_ctx", "_cache"];
  24168. if (options.bindingMetadata && !options.inline) {
  24169. args.push("$props", "$setup", "$data", "$options");
  24170. }
  24171. const signature = options.isTS ? args.map((arg) => `${arg}: any`).join(",") : args.join(", ");
  24172. if (isSetupInlined) {
  24173. push(`(${signature}) => {`);
  24174. } else {
  24175. push(`function ${functionName}(${signature}) {`);
  24176. }
  24177. indent();
  24178. if (useWithBlock) {
  24179. push(`with (_ctx) {`);
  24180. indent();
  24181. if (hasHelpers) {
  24182. push(
  24183. `const { ${helpers.map(aliasHelper).join(", ")} } = _Vue
  24184. `,
  24185. -1 /* End */
  24186. );
  24187. newline();
  24188. }
  24189. }
  24190. if (ast.components.length) {
  24191. genAssets(ast.components, "component", context);
  24192. if (ast.directives.length || ast.temps > 0) {
  24193. newline();
  24194. }
  24195. }
  24196. if (ast.directives.length) {
  24197. genAssets(ast.directives, "directive", context);
  24198. if (ast.temps > 0) {
  24199. newline();
  24200. }
  24201. }
  24202. if (ast.temps > 0) {
  24203. push(`let `);
  24204. for (let i = 0; i < ast.temps; i++) {
  24205. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  24206. }
  24207. }
  24208. if (ast.components.length || ast.directives.length || ast.temps) {
  24209. push(`
  24210. `, 0 /* Start */);
  24211. newline();
  24212. }
  24213. if (!ssr) {
  24214. push(`return `);
  24215. }
  24216. if (ast.codegenNode) {
  24217. genNode(ast.codegenNode, context);
  24218. } else {
  24219. push(`null`);
  24220. }
  24221. if (useWithBlock) {
  24222. deindent();
  24223. push(`}`);
  24224. }
  24225. deindent();
  24226. push(`}`);
  24227. return {
  24228. ast,
  24229. code: context.code,
  24230. preamble: isSetupInlined ? preambleContext.code : ``,
  24231. map: context.map ? context.map.toJSON() : void 0
  24232. };
  24233. }
  24234. function genFunctionPreamble(ast, context) {
  24235. const {
  24236. ssr,
  24237. prefixIdentifiers,
  24238. push,
  24239. newline,
  24240. runtimeModuleName,
  24241. runtimeGlobalName,
  24242. ssrRuntimeModuleName
  24243. } = context;
  24244. const VueBinding = ssr ? `require(${JSON.stringify(runtimeModuleName)})` : runtimeGlobalName;
  24245. const helpers = Array.from(ast.helpers);
  24246. if (helpers.length > 0) {
  24247. if (prefixIdentifiers) {
  24248. push(
  24249. `const { ${helpers.map(aliasHelper).join(", ")} } = ${VueBinding}
  24250. `,
  24251. -1 /* End */
  24252. );
  24253. } else {
  24254. push(`const _Vue = ${VueBinding}
  24255. `, -1 /* End */);
  24256. if (ast.hoists.length) {
  24257. const staticHelpers = [
  24258. CREATE_VNODE,
  24259. CREATE_ELEMENT_VNODE,
  24260. CREATE_COMMENT,
  24261. CREATE_TEXT,
  24262. CREATE_STATIC
  24263. ].filter((helper) => helpers.includes(helper)).map(aliasHelper).join(", ");
  24264. push(`const { ${staticHelpers} } = _Vue
  24265. `, -1 /* End */);
  24266. }
  24267. }
  24268. }
  24269. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  24270. push(
  24271. `const { ${ast.ssrHelpers.map(aliasHelper).join(", ")} } = require("${ssrRuntimeModuleName}")
  24272. `,
  24273. -1 /* End */
  24274. );
  24275. }
  24276. genHoists(ast.hoists, context);
  24277. newline();
  24278. push(`return `);
  24279. }
  24280. function genModulePreamble(ast, context, genScopeId, inline) {
  24281. const {
  24282. push,
  24283. newline,
  24284. optimizeImports,
  24285. runtimeModuleName,
  24286. ssrRuntimeModuleName
  24287. } = context;
  24288. if (ast.helpers.size) {
  24289. const helpers = Array.from(ast.helpers);
  24290. if (optimizeImports) {
  24291. push(
  24292. `import { ${helpers.map((s) => helperNameMap[s]).join(", ")} } from ${JSON.stringify(runtimeModuleName)}
  24293. `,
  24294. -1 /* End */
  24295. );
  24296. push(
  24297. `
  24298. // Binding optimization for webpack code-split
  24299. const ${helpers.map((s) => `_${helperNameMap[s]} = ${helperNameMap[s]}`).join(", ")}
  24300. `,
  24301. -1 /* End */
  24302. );
  24303. } else {
  24304. push(
  24305. `import { ${helpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from ${JSON.stringify(runtimeModuleName)}
  24306. `,
  24307. -1 /* End */
  24308. );
  24309. }
  24310. }
  24311. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  24312. push(
  24313. `import { ${ast.ssrHelpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from "${ssrRuntimeModuleName}"
  24314. `,
  24315. -1 /* End */
  24316. );
  24317. }
  24318. if (ast.imports.length) {
  24319. genImports(ast.imports, context);
  24320. newline();
  24321. }
  24322. genHoists(ast.hoists, context);
  24323. newline();
  24324. if (!inline) {
  24325. push(`export `);
  24326. }
  24327. }
  24328. function genAssets(assets, type, { helper, push, newline, isTS }) {
  24329. const resolver = helper(
  24330. type === "component" ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE
  24331. );
  24332. for (let i = 0; i < assets.length; i++) {
  24333. let id = assets[i];
  24334. const maybeSelfReference = id.endsWith("__self");
  24335. if (maybeSelfReference) {
  24336. id = id.slice(0, -6);
  24337. }
  24338. push(
  24339. `const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`
  24340. );
  24341. if (i < assets.length - 1) {
  24342. newline();
  24343. }
  24344. }
  24345. }
  24346. function genHoists(hoists, context) {
  24347. if (!hoists.length) {
  24348. return;
  24349. }
  24350. context.pure = true;
  24351. const { push, newline } = context;
  24352. newline();
  24353. for (let i = 0; i < hoists.length; i++) {
  24354. const exp = hoists[i];
  24355. if (exp) {
  24356. push(`const _hoisted_${i + 1} = `);
  24357. genNode(exp, context);
  24358. newline();
  24359. }
  24360. }
  24361. context.pure = false;
  24362. }
  24363. function genImports(importsOptions, context) {
  24364. if (!importsOptions.length) {
  24365. return;
  24366. }
  24367. importsOptions.forEach((imports) => {
  24368. context.push(`import `);
  24369. genNode(imports.exp, context);
  24370. context.push(` from '${imports.path}'`);
  24371. context.newline();
  24372. });
  24373. }
  24374. function isText(n) {
  24375. return isString$1(n) || n.type === 4 || n.type === 2 || n.type === 5 || n.type === 8;
  24376. }
  24377. function genNodeListAsArray(nodes, context) {
  24378. const multilines = nodes.length > 3 || nodes.some((n) => isArray$3(n) || !isText(n));
  24379. context.push(`[`);
  24380. multilines && context.indent();
  24381. genNodeList(nodes, context, multilines);
  24382. multilines && context.deindent();
  24383. context.push(`]`);
  24384. }
  24385. function genNodeList(nodes, context, multilines = false, comma = true) {
  24386. const { push, newline } = context;
  24387. for (let i = 0; i < nodes.length; i++) {
  24388. const node = nodes[i];
  24389. if (isString$1(node)) {
  24390. push(node, -3 /* Unknown */);
  24391. } else if (isArray$3(node)) {
  24392. genNodeListAsArray(node, context);
  24393. } else {
  24394. genNode(node, context);
  24395. }
  24396. if (i < nodes.length - 1) {
  24397. if (multilines) {
  24398. comma && push(",");
  24399. newline();
  24400. } else {
  24401. comma && push(", ");
  24402. }
  24403. }
  24404. }
  24405. }
  24406. function genNode(node, context) {
  24407. if (isString$1(node)) {
  24408. context.push(node, -3 /* Unknown */);
  24409. return;
  24410. }
  24411. if (isSymbol$1(node)) {
  24412. context.push(context.helper(node));
  24413. return;
  24414. }
  24415. switch (node.type) {
  24416. case 1:
  24417. case 9:
  24418. case 11:
  24419. assert(
  24420. node.codegenNode != null,
  24421. `Codegen node is missing for element/if/for node. Apply appropriate transforms first.`
  24422. );
  24423. genNode(node.codegenNode, context);
  24424. break;
  24425. case 2:
  24426. genText(node, context);
  24427. break;
  24428. case 4:
  24429. genExpression(node, context);
  24430. break;
  24431. case 5:
  24432. genInterpolation(node, context);
  24433. break;
  24434. case 12:
  24435. genNode(node.codegenNode, context);
  24436. break;
  24437. case 8:
  24438. genCompoundExpression(node, context);
  24439. break;
  24440. case 3:
  24441. genComment(node, context);
  24442. break;
  24443. case 13:
  24444. genVNodeCall(node, context);
  24445. break;
  24446. case 14:
  24447. genCallExpression(node, context);
  24448. break;
  24449. case 15:
  24450. genObjectExpression(node, context);
  24451. break;
  24452. case 17:
  24453. genArrayExpression(node, context);
  24454. break;
  24455. case 18:
  24456. genFunctionExpression(node, context);
  24457. break;
  24458. case 19:
  24459. genConditionalExpression(node, context);
  24460. break;
  24461. case 20:
  24462. genCacheExpression(node, context);
  24463. break;
  24464. case 21:
  24465. genNodeList(node.body, context, true, false);
  24466. break;
  24467. // SSR only types
  24468. case 22:
  24469. genTemplateLiteral(node, context);
  24470. break;
  24471. case 23:
  24472. genIfStatement(node, context);
  24473. break;
  24474. case 24:
  24475. genAssignmentExpression(node, context);
  24476. break;
  24477. case 25:
  24478. genSequenceExpression(node, context);
  24479. break;
  24480. case 26:
  24481. genReturnStatement(node, context);
  24482. break;
  24483. /* v8 ignore start */
  24484. case 10:
  24485. break;
  24486. default:
  24487. {
  24488. assert(false, `unhandled codegen node type: ${node.type}`);
  24489. const exhaustiveCheck = node;
  24490. return exhaustiveCheck;
  24491. }
  24492. }
  24493. }
  24494. function genText(node, context) {
  24495. context.push(JSON.stringify(node.content), -3 /* Unknown */, node);
  24496. }
  24497. function genExpression(node, context) {
  24498. const { content, isStatic } = node;
  24499. context.push(
  24500. isStatic ? JSON.stringify(content) : content,
  24501. -3 /* Unknown */,
  24502. node
  24503. );
  24504. }
  24505. function genInterpolation(node, context) {
  24506. const { push, helper, pure } = context;
  24507. if (pure) push(PURE_ANNOTATION);
  24508. push(`${helper(TO_DISPLAY_STRING)}(`);
  24509. genNode(node.content, context);
  24510. push(`)`);
  24511. }
  24512. function genCompoundExpression(node, context) {
  24513. for (let i = 0; i < node.children.length; i++) {
  24514. const child = node.children[i];
  24515. if (isString$1(child)) {
  24516. context.push(child, -3 /* Unknown */);
  24517. } else {
  24518. genNode(child, context);
  24519. }
  24520. }
  24521. }
  24522. function genExpressionAsPropertyKey(node, context) {
  24523. const { push } = context;
  24524. if (node.type === 8) {
  24525. push(`[`);
  24526. genCompoundExpression(node, context);
  24527. push(`]`);
  24528. } else if (node.isStatic) {
  24529. const text = isSimpleIdentifier(node.content) ? node.content : JSON.stringify(node.content);
  24530. push(text, -2 /* None */, node);
  24531. } else {
  24532. push(`[${node.content}]`, -3 /* Unknown */, node);
  24533. }
  24534. }
  24535. function genComment(node, context) {
  24536. const { push, helper, pure } = context;
  24537. if (pure) {
  24538. push(PURE_ANNOTATION);
  24539. }
  24540. push(
  24541. `${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`,
  24542. -3 /* Unknown */,
  24543. node
  24544. );
  24545. }
  24546. function genVNodeCall(node, context) {
  24547. const { push, helper, pure } = context;
  24548. const {
  24549. tag,
  24550. props,
  24551. children,
  24552. patchFlag,
  24553. dynamicProps,
  24554. directives,
  24555. isBlock,
  24556. disableTracking,
  24557. isComponent
  24558. } = node;
  24559. let patchFlagString;
  24560. if (patchFlag) {
  24561. {
  24562. if (patchFlag < 0) {
  24563. patchFlagString = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  24564. } else {
  24565. const flagNames = Object.keys(PatchFlagNames).map(Number).filter((n) => n > 0 && patchFlag & n).map((n) => PatchFlagNames[n]).join(`, `);
  24566. patchFlagString = patchFlag + ` /* ${flagNames} */`;
  24567. }
  24568. }
  24569. }
  24570. if (directives) {
  24571. push(helper(WITH_DIRECTIVES) + `(`);
  24572. }
  24573. if (isBlock) {
  24574. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  24575. }
  24576. if (pure) {
  24577. push(PURE_ANNOTATION);
  24578. }
  24579. const callHelper = isBlock ? getVNodeBlockHelper(context.inSSR, isComponent) : getVNodeHelper(context.inSSR, isComponent);
  24580. push(helper(callHelper) + `(`, -2 /* None */, node);
  24581. genNodeList(
  24582. genNullableArgs([tag, props, children, patchFlagString, dynamicProps]),
  24583. context
  24584. );
  24585. push(`)`);
  24586. if (isBlock) {
  24587. push(`)`);
  24588. }
  24589. if (directives) {
  24590. push(`, `);
  24591. genNode(directives, context);
  24592. push(`)`);
  24593. }
  24594. }
  24595. function genNullableArgs(args) {
  24596. let i = args.length;
  24597. while (i--) {
  24598. if (args[i] != null) break;
  24599. }
  24600. return args.slice(0, i + 1).map((arg) => arg || `null`);
  24601. }
  24602. function genCallExpression(node, context) {
  24603. const { push, helper, pure } = context;
  24604. const callee = isString$1(node.callee) ? node.callee : helper(node.callee);
  24605. if (pure) {
  24606. push(PURE_ANNOTATION);
  24607. }
  24608. push(callee + `(`, -2 /* None */, node);
  24609. genNodeList(node.arguments, context);
  24610. push(`)`);
  24611. }
  24612. function genObjectExpression(node, context) {
  24613. const { push, indent, deindent, newline } = context;
  24614. const { properties } = node;
  24615. if (!properties.length) {
  24616. push(`{}`, -2 /* None */, node);
  24617. return;
  24618. }
  24619. const multilines = properties.length > 1 || properties.some((p) => p.value.type !== 4);
  24620. push(multilines ? `{` : `{ `);
  24621. multilines && indent();
  24622. for (let i = 0; i < properties.length; i++) {
  24623. const { key, value } = properties[i];
  24624. genExpressionAsPropertyKey(key, context);
  24625. push(`: `);
  24626. genNode(value, context);
  24627. if (i < properties.length - 1) {
  24628. push(`,`);
  24629. newline();
  24630. }
  24631. }
  24632. multilines && deindent();
  24633. push(multilines ? `}` : ` }`);
  24634. }
  24635. function genArrayExpression(node, context) {
  24636. genNodeListAsArray(node.elements, context);
  24637. }
  24638. function genFunctionExpression(node, context) {
  24639. const { push, indent, deindent } = context;
  24640. const { params, returns, body, newline, isSlot } = node;
  24641. if (isSlot) {
  24642. push(`_${helperNameMap[WITH_CTX]}(`);
  24643. }
  24644. push(`(`, -2 /* None */, node);
  24645. if (isArray$3(params)) {
  24646. genNodeList(params, context);
  24647. } else if (params) {
  24648. genNode(params, context);
  24649. }
  24650. push(`) => `);
  24651. if (newline || body) {
  24652. push(`{`);
  24653. indent();
  24654. }
  24655. if (returns) {
  24656. if (newline) {
  24657. push(`return `);
  24658. }
  24659. if (isArray$3(returns)) {
  24660. genNodeListAsArray(returns, context);
  24661. } else {
  24662. genNode(returns, context);
  24663. }
  24664. } else if (body) {
  24665. genNode(body, context);
  24666. }
  24667. if (newline || body) {
  24668. deindent();
  24669. push(`}`);
  24670. }
  24671. if (isSlot) {
  24672. push(`)`);
  24673. }
  24674. }
  24675. function genConditionalExpression(node, context) {
  24676. const { test, consequent, alternate, newline: needNewline } = node;
  24677. const { push, indent, deindent, newline } = context;
  24678. if (test.type === 4) {
  24679. const needsParens = !isSimpleIdentifier(test.content);
  24680. needsParens && push(`(`);
  24681. genExpression(test, context);
  24682. needsParens && push(`)`);
  24683. } else {
  24684. push(`(`);
  24685. genNode(test, context);
  24686. push(`)`);
  24687. }
  24688. needNewline && indent();
  24689. context.indentLevel++;
  24690. needNewline || push(` `);
  24691. push(`? `);
  24692. genNode(consequent, context);
  24693. context.indentLevel--;
  24694. needNewline && newline();
  24695. needNewline || push(` `);
  24696. push(`: `);
  24697. const isNested = alternate.type === 19;
  24698. if (!isNested) {
  24699. context.indentLevel++;
  24700. }
  24701. genNode(alternate, context);
  24702. if (!isNested) {
  24703. context.indentLevel--;
  24704. }
  24705. needNewline && deindent(
  24706. true
  24707. /* without newline */
  24708. );
  24709. }
  24710. function genCacheExpression(node, context) {
  24711. const { push, helper, indent, deindent, newline } = context;
  24712. const { needPauseTracking, needArraySpread } = node;
  24713. if (needArraySpread) {
  24714. push(`[...(`);
  24715. }
  24716. push(`_cache[${node.index}] || (`);
  24717. if (needPauseTracking) {
  24718. indent();
  24719. push(`${helper(SET_BLOCK_TRACKING)}(-1`);
  24720. if (node.inVOnce) push(`, true`);
  24721. push(`),`);
  24722. newline();
  24723. push(`(`);
  24724. }
  24725. push(`_cache[${node.index}] = `);
  24726. genNode(node.value, context);
  24727. if (needPauseTracking) {
  24728. push(`).cacheIndex = ${node.index},`);
  24729. newline();
  24730. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  24731. newline();
  24732. push(`_cache[${node.index}]`);
  24733. deindent();
  24734. }
  24735. push(`)`);
  24736. if (needArraySpread) {
  24737. push(`)]`);
  24738. }
  24739. }
  24740. function genTemplateLiteral(node, context) {
  24741. const { push, indent, deindent } = context;
  24742. push("`");
  24743. const l = node.elements.length;
  24744. const multilines = l > 3;
  24745. for (let i = 0; i < l; i++) {
  24746. const e = node.elements[i];
  24747. if (isString$1(e)) {
  24748. push(e.replace(/(`|\$|\\)/g, "\\$1"), -3 /* Unknown */);
  24749. } else {
  24750. push("${");
  24751. if (multilines) indent();
  24752. genNode(e, context);
  24753. if (multilines) deindent();
  24754. push("}");
  24755. }
  24756. }
  24757. push("`");
  24758. }
  24759. function genIfStatement(node, context) {
  24760. const { push, indent, deindent } = context;
  24761. const { test, consequent, alternate } = node;
  24762. push(`if (`);
  24763. genNode(test, context);
  24764. push(`) {`);
  24765. indent();
  24766. genNode(consequent, context);
  24767. deindent();
  24768. push(`}`);
  24769. if (alternate) {
  24770. push(` else `);
  24771. if (alternate.type === 23) {
  24772. genIfStatement(alternate, context);
  24773. } else {
  24774. push(`{`);
  24775. indent();
  24776. genNode(alternate, context);
  24777. deindent();
  24778. push(`}`);
  24779. }
  24780. }
  24781. }
  24782. function genAssignmentExpression(node, context) {
  24783. genNode(node.left, context);
  24784. context.push(` = `);
  24785. genNode(node.right, context);
  24786. }
  24787. function genSequenceExpression(node, context) {
  24788. context.push(`(`);
  24789. genNodeList(node.expressions, context);
  24790. context.push(`)`);
  24791. }
  24792. function genReturnStatement({ returns }, context) {
  24793. context.push(`return `);
  24794. if (isArray$3(returns)) {
  24795. genNodeListAsArray(returns, context);
  24796. } else {
  24797. genNode(returns, context);
  24798. }
  24799. }
  24800. const isLiteralWhitelisted = /* @__PURE__ */ makeMap("true,false,null,this");
  24801. const transformExpression = (node, context) => {
  24802. if (node.type === 5) {
  24803. node.content = processExpression(
  24804. node.content,
  24805. context
  24806. );
  24807. } else if (node.type === 1) {
  24808. const memo = findDir(node, "memo");
  24809. for (let i = 0; i < node.props.length; i++) {
  24810. const dir = node.props[i];
  24811. if (dir.type === 7 && dir.name !== "for") {
  24812. const exp = dir.exp;
  24813. const arg = dir.arg;
  24814. if (exp && exp.type === 4 && !(dir.name === "on" && arg) && // key has been processed in transformFor(vMemo + vFor)
  24815. !(memo && context.vForMemoKeyedNodes.has(node) && arg && arg.type === 4 && arg.content === "key")) {
  24816. dir.exp = processExpression(
  24817. exp,
  24818. context,
  24819. // slot args must be processed as function params
  24820. dir.name === "slot"
  24821. );
  24822. }
  24823. if (arg && arg.type === 4 && !arg.isStatic) {
  24824. dir.arg = processExpression(arg, context);
  24825. }
  24826. }
  24827. }
  24828. }
  24829. };
  24830. function processExpression(node, context, asParams = false, asRawStatements = false, localVars = Object.create(context.identifiers)) {
  24831. if (!context.prefixIdentifiers || !node.content.trim()) {
  24832. return node;
  24833. }
  24834. const { inline, bindingMetadata } = context;
  24835. const rewriteIdentifier = (raw, parent, id) => {
  24836. const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  24837. if (inline) {
  24838. const isAssignmentLVal = parent && parent.type === "AssignmentExpression" && parent.left === id;
  24839. const isUpdateArg = parent && parent.type === "UpdateExpression" && parent.argument === id;
  24840. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  24841. const isNewExpression = parent && isInNewExpression(parentStack);
  24842. const wrapWithUnref = (raw2) => {
  24843. const wrapped = `${context.helperString(UNREF)}(${raw2})`;
  24844. return isNewExpression ? `(${wrapped})` : wrapped;
  24845. };
  24846. if (isConst(type) || type === "setup-reactive-const" || localVars[raw]) {
  24847. return raw;
  24848. } else if (type === "setup-ref") {
  24849. return `${raw}.value`;
  24850. } else if (type === "setup-maybe-ref") {
  24851. return isAssignmentLVal || isUpdateArg || isDestructureAssignment ? `${raw}.value` : wrapWithUnref(raw);
  24852. } else if (type === "setup-let") {
  24853. if (isAssignmentLVal) {
  24854. const { right: rVal, operator } = parent;
  24855. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  24856. const rExpString = stringifyExpression(
  24857. processExpression(
  24858. createSimpleExpression(rExp, false),
  24859. context,
  24860. false,
  24861. false,
  24862. knownIds
  24863. )
  24864. );
  24865. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore
  24866. ` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;
  24867. } else if (isUpdateArg) {
  24868. id.start = parent.start;
  24869. id.end = parent.end;
  24870. const { prefix: isPrefix, operator } = parent;
  24871. const prefix = isPrefix ? operator : ``;
  24872. const postfix = isPrefix ? `` : operator;
  24873. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore
  24874. ` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  24875. } else if (isDestructureAssignment) {
  24876. return raw;
  24877. } else {
  24878. return wrapWithUnref(raw);
  24879. }
  24880. } else if (type === "props") {
  24881. return genPropsAccessExp(raw);
  24882. } else if (type === "props-aliased") {
  24883. return genPropsAccessExp(bindingMetadata.__propsAliases[raw]);
  24884. }
  24885. } else {
  24886. if (type && type.startsWith("setup") || type === "literal-const") {
  24887. return `$setup.${raw}`;
  24888. } else if (type === "props-aliased") {
  24889. return `$props['${bindingMetadata.__propsAliases[raw]}']`;
  24890. } else if (type) {
  24891. return `$${type}.${raw}`;
  24892. }
  24893. }
  24894. return `_ctx.${raw}`;
  24895. };
  24896. const rawExp = node.content;
  24897. let ast = node.ast;
  24898. if (ast === false) {
  24899. return node;
  24900. }
  24901. if (ast === null || !ast && isSimpleIdentifier(rawExp)) {
  24902. const isScopeVarReference = context.identifiers[rawExp];
  24903. const isAllowedGlobal = isGloballyAllowed(rawExp);
  24904. const isLiteral = isLiteralWhitelisted(rawExp);
  24905. if (!asParams && !isScopeVarReference && !isLiteral && (!isAllowedGlobal || bindingMetadata[rawExp])) {
  24906. if (isConst(bindingMetadata[rawExp])) {
  24907. node.constType = 1;
  24908. }
  24909. node.content = rewriteIdentifier(rawExp);
  24910. } else if (!isScopeVarReference) {
  24911. if (isLiteral) {
  24912. node.constType = 3;
  24913. } else {
  24914. node.constType = 2;
  24915. }
  24916. }
  24917. return node;
  24918. }
  24919. if (!ast) {
  24920. const source = asRawStatements ? ` ${rawExp} ` : `(${rawExp})${asParams ? `=>{}` : ``}`;
  24921. try {
  24922. ast = libExports.parseExpression(source, {
  24923. sourceType: "module",
  24924. plugins: context.expressionPlugins
  24925. });
  24926. } catch (e) {
  24927. context.onError(
  24928. createCompilerError(
  24929. 46,
  24930. node.loc,
  24931. void 0,
  24932. e.message
  24933. )
  24934. );
  24935. return node;
  24936. }
  24937. }
  24938. const ids = [];
  24939. const parentStack = [];
  24940. const knownIds = Object.create(context.identifiers);
  24941. walkIdentifiers(
  24942. ast,
  24943. (node2, parent, _, isReferenced, isLocal) => {
  24944. if (isStaticPropertyKey(node2, parent)) {
  24945. return;
  24946. }
  24947. const needPrefix = isReferenced && canPrefix(node2);
  24948. if (needPrefix && !isLocal) {
  24949. if (isStaticProperty(parent) && parent.shorthand) {
  24950. node2.prefix = `${node2.name}: `;
  24951. }
  24952. node2.name = rewriteIdentifier(node2.name, parent, node2);
  24953. ids.push(node2);
  24954. } else {
  24955. if (!(needPrefix && isLocal) && (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "MemberExpression")) {
  24956. node2.isConstant = true;
  24957. }
  24958. ids.push(node2);
  24959. }
  24960. },
  24961. true,
  24962. // invoke on ALL identifiers
  24963. parentStack,
  24964. knownIds
  24965. );
  24966. const children = [];
  24967. ids.sort((a, b) => a.start - b.start);
  24968. ids.forEach((id, i) => {
  24969. const start = id.start - 1;
  24970. const end = id.end - 1;
  24971. const last = ids[i - 1];
  24972. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  24973. if (leadingText.length || id.prefix) {
  24974. children.push(leadingText + (id.prefix || ``));
  24975. }
  24976. const source = rawExp.slice(start, end);
  24977. children.push(
  24978. createSimpleExpression(
  24979. id.name,
  24980. false,
  24981. {
  24982. start: advancePositionWithClone(node.loc.start, source, start),
  24983. end: advancePositionWithClone(node.loc.start, source, end),
  24984. source
  24985. },
  24986. id.isConstant ? 3 : 0
  24987. )
  24988. );
  24989. if (i === ids.length - 1 && end < rawExp.length) {
  24990. children.push(rawExp.slice(end));
  24991. }
  24992. });
  24993. let ret;
  24994. if (children.length) {
  24995. ret = createCompoundExpression(children, node.loc);
  24996. ret.ast = ast;
  24997. } else {
  24998. ret = node;
  24999. ret.constType = 3;
  25000. }
  25001. ret.identifiers = Object.keys(knownIds);
  25002. return ret;
  25003. }
  25004. function canPrefix(id) {
  25005. if (isGloballyAllowed(id.name)) {
  25006. return false;
  25007. }
  25008. if (id.name === "require") {
  25009. return false;
  25010. }
  25011. return true;
  25012. }
  25013. function stringifyExpression(exp) {
  25014. if (isString$1(exp)) {
  25015. return exp;
  25016. } else if (exp.type === 4) {
  25017. return exp.content;
  25018. } else {
  25019. return exp.children.map(stringifyExpression).join("");
  25020. }
  25021. }
  25022. function isConst(type) {
  25023. return type === "setup-const" || type === "literal-const";
  25024. }
  25025. const transformIf = createStructuralDirectiveTransform(
  25026. /^(?:if|else|else-if)$/,
  25027. (node, dir, context) => {
  25028. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  25029. const siblings = context.parent.children;
  25030. let i = siblings.indexOf(ifNode);
  25031. let key = 0;
  25032. while (i-- >= 0) {
  25033. const sibling = siblings[i];
  25034. if (sibling && sibling.type === 9) {
  25035. key += sibling.branches.length;
  25036. }
  25037. }
  25038. return () => {
  25039. if (isRoot) {
  25040. ifNode.codegenNode = createCodegenNodeForBranch(
  25041. branch,
  25042. key,
  25043. context
  25044. );
  25045. } else {
  25046. const parentCondition = getParentCondition(ifNode.codegenNode);
  25047. parentCondition.alternate = createCodegenNodeForBranch(
  25048. branch,
  25049. key + ifNode.branches.length - 1,
  25050. context
  25051. );
  25052. }
  25053. };
  25054. });
  25055. }
  25056. );
  25057. function processIf(node, dir, context, processCodegen) {
  25058. if (dir.name !== "else" && (!dir.exp || !dir.exp.content.trim())) {
  25059. const loc = dir.exp ? dir.exp.loc : node.loc;
  25060. context.onError(
  25061. createCompilerError(28, dir.loc)
  25062. );
  25063. dir.exp = createSimpleExpression(`true`, false, loc);
  25064. }
  25065. if (context.prefixIdentifiers && dir.exp) {
  25066. dir.exp = processExpression(dir.exp, context);
  25067. }
  25068. if (dir.name === "if") {
  25069. const branch = createIfBranch(node, dir);
  25070. const ifNode = {
  25071. type: 9,
  25072. loc: cloneLoc(node.loc),
  25073. branches: [branch]
  25074. };
  25075. context.replaceNode(ifNode);
  25076. if (processCodegen) {
  25077. return processCodegen(ifNode, branch, true);
  25078. }
  25079. } else {
  25080. const siblings = context.parent.children;
  25081. const comments = [];
  25082. let i = siblings.indexOf(node);
  25083. while (i-- >= -1) {
  25084. const sibling = siblings[i];
  25085. if (sibling && isCommentOrWhitespace(sibling)) {
  25086. context.removeNode(sibling);
  25087. if (sibling.type === 3) {
  25088. comments.unshift(sibling);
  25089. }
  25090. continue;
  25091. }
  25092. if (sibling && sibling.type === 9) {
  25093. if ((dir.name === "else-if" || dir.name === "else") && sibling.branches[sibling.branches.length - 1].condition === void 0) {
  25094. context.onError(
  25095. createCompilerError(30, node.loc)
  25096. );
  25097. }
  25098. context.removeNode();
  25099. const branch = createIfBranch(node, dir);
  25100. if (comments.length && // #3619 ignore comments if the v-if is direct child of <transition>
  25101. !(context.parent && context.parent.type === 1 && (context.parent.tag === "transition" || context.parent.tag === "Transition"))) {
  25102. branch.children = [...comments, ...branch.children];
  25103. }
  25104. {
  25105. const key = branch.userKey;
  25106. if (key) {
  25107. sibling.branches.forEach(({ userKey }) => {
  25108. if (isSameKey(userKey, key)) {
  25109. context.onError(
  25110. createCompilerError(
  25111. 29,
  25112. branch.userKey.loc
  25113. )
  25114. );
  25115. }
  25116. });
  25117. }
  25118. }
  25119. sibling.branches.push(branch);
  25120. const onExit = processCodegen && processCodegen(sibling, branch, false);
  25121. traverseNode(branch, context);
  25122. if (onExit) onExit();
  25123. context.currentNode = null;
  25124. } else {
  25125. context.onError(
  25126. createCompilerError(30, node.loc)
  25127. );
  25128. }
  25129. break;
  25130. }
  25131. }
  25132. }
  25133. function createIfBranch(node, dir) {
  25134. const isTemplateIf = node.tagType === 3;
  25135. return {
  25136. type: 10,
  25137. loc: node.loc,
  25138. condition: dir.name === "else" ? void 0 : dir.exp,
  25139. children: isTemplateIf && !findDir(node, "for") ? node.children : [node],
  25140. userKey: findProp(node, `key`),
  25141. isTemplateIf
  25142. };
  25143. }
  25144. function createCodegenNodeForBranch(branch, keyIndex, context) {
  25145. if (branch.condition) {
  25146. return createConditionalExpression(
  25147. branch.condition,
  25148. createChildrenCodegenNode(branch, keyIndex, context),
  25149. // make sure to pass in asBlock: true so that the comment node call
  25150. // closes the current block.
  25151. createCallExpression(context.helper(CREATE_COMMENT), [
  25152. '"v-if"' ,
  25153. "true"
  25154. ])
  25155. );
  25156. } else {
  25157. return createChildrenCodegenNode(branch, keyIndex, context);
  25158. }
  25159. }
  25160. function createChildrenCodegenNode(branch, keyIndex, context) {
  25161. const { helper } = context;
  25162. const keyProperty = createObjectProperty(
  25163. `key`,
  25164. createSimpleExpression(
  25165. `${keyIndex}`,
  25166. false,
  25167. locStub,
  25168. 2
  25169. )
  25170. );
  25171. const { children } = branch;
  25172. const firstChild = children[0];
  25173. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1;
  25174. if (needFragmentWrapper) {
  25175. if (children.length === 1 && firstChild.type === 11) {
  25176. const vnodeCall = firstChild.codegenNode;
  25177. injectProp(vnodeCall, keyProperty, context);
  25178. return vnodeCall;
  25179. } else {
  25180. let patchFlag = 64;
  25181. if (!branch.isTemplateIf && children.filter((c) => c.type !== 3).length === 1) {
  25182. patchFlag |= 2048;
  25183. }
  25184. return createVNodeCall(
  25185. context,
  25186. helper(FRAGMENT),
  25187. createObjectExpression([keyProperty]),
  25188. children,
  25189. patchFlag,
  25190. void 0,
  25191. void 0,
  25192. true,
  25193. false,
  25194. false,
  25195. branch.loc
  25196. );
  25197. }
  25198. } else {
  25199. const ret = firstChild.codegenNode;
  25200. const vnodeCall = getMemoedVNodeCall(ret);
  25201. if (vnodeCall.type === 13) {
  25202. convertToBlock(vnodeCall, context);
  25203. }
  25204. injectProp(vnodeCall, keyProperty, context);
  25205. return ret;
  25206. }
  25207. }
  25208. function isSameKey(a, b) {
  25209. if (!a || a.type !== b.type) {
  25210. return false;
  25211. }
  25212. if (a.type === 6) {
  25213. if (a.value.content !== b.value.content) {
  25214. return false;
  25215. }
  25216. } else {
  25217. const exp = a.exp;
  25218. const branchExp = b.exp;
  25219. if (exp.type !== branchExp.type) {
  25220. return false;
  25221. }
  25222. if (exp.type !== 4 || exp.isStatic !== branchExp.isStatic || exp.content !== branchExp.content) {
  25223. return false;
  25224. }
  25225. }
  25226. return true;
  25227. }
  25228. function getParentCondition(node) {
  25229. while (true) {
  25230. if (node.type === 19) {
  25231. if (node.alternate.type === 19) {
  25232. node = node.alternate;
  25233. } else {
  25234. return node;
  25235. }
  25236. } else if (node.type === 20) {
  25237. node = node.value;
  25238. }
  25239. }
  25240. }
  25241. const transformFor = createStructuralDirectiveTransform(
  25242. "for",
  25243. (node, dir, context) => {
  25244. const { helper, removeHelper } = context;
  25245. return processFor(node, dir, context, (forNode) => {
  25246. const renderExp = createCallExpression(helper(RENDER_LIST), [
  25247. forNode.source
  25248. ]);
  25249. const isTemplate = isTemplateNode(node);
  25250. const memo = findDir(node, "memo");
  25251. const keyProp = findProp(node, `key`, false, true);
  25252. const isDirKey = keyProp && keyProp.type === 7;
  25253. let keyExp = keyProp && (keyProp.type === 6 ? keyProp.value ? createSimpleExpression(keyProp.value.content, true) : void 0 : keyProp.exp);
  25254. const keyProperty = keyExp ? createObjectProperty(`key`, keyExp) : null;
  25255. {
  25256. if (isTemplate && memo) {
  25257. memo.exp = processExpression(
  25258. memo.exp,
  25259. context
  25260. );
  25261. }
  25262. if ((isTemplate || memo) && keyProperty && isDirKey) {
  25263. keyExp = keyProp.exp = keyProperty.value = processExpression(
  25264. keyProperty.value,
  25265. context
  25266. );
  25267. if (memo) {
  25268. context.vForMemoKeyedNodes.add(node);
  25269. }
  25270. }
  25271. }
  25272. const isStableFragment = forNode.source.type === 4 && forNode.source.constType > 0;
  25273. const fragmentFlag = isStableFragment ? 64 : keyProp ? 128 : 256;
  25274. forNode.codegenNode = createVNodeCall(
  25275. context,
  25276. helper(FRAGMENT),
  25277. void 0,
  25278. renderExp,
  25279. fragmentFlag,
  25280. void 0,
  25281. void 0,
  25282. true,
  25283. !isStableFragment,
  25284. false,
  25285. node.loc
  25286. );
  25287. return () => {
  25288. let childBlock;
  25289. const { children } = forNode;
  25290. if (isTemplate) {
  25291. node.children.some((c) => {
  25292. if (c.type === 1) {
  25293. const key = findProp(c, "key");
  25294. if (key) {
  25295. context.onError(
  25296. createCompilerError(
  25297. 33,
  25298. key.loc
  25299. )
  25300. );
  25301. return true;
  25302. }
  25303. }
  25304. });
  25305. }
  25306. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1;
  25307. const slotOutlet = isSlotOutlet(node) ? node : isTemplate && node.children.length === 1 && isSlotOutlet(node.children[0]) ? node.children[0] : null;
  25308. if (slotOutlet) {
  25309. childBlock = slotOutlet.codegenNode;
  25310. if (isTemplate && keyProperty) {
  25311. injectProp(childBlock, keyProperty, context);
  25312. }
  25313. } else if (needFragmentWrapper) {
  25314. childBlock = createVNodeCall(
  25315. context,
  25316. helper(FRAGMENT),
  25317. keyProperty ? createObjectExpression([keyProperty]) : void 0,
  25318. node.children,
  25319. 64,
  25320. void 0,
  25321. void 0,
  25322. true,
  25323. void 0,
  25324. false
  25325. );
  25326. } else {
  25327. childBlock = children[0].codegenNode;
  25328. if (isTemplate && keyProperty) {
  25329. injectProp(childBlock, keyProperty, context);
  25330. }
  25331. if (childBlock.isBlock !== !isStableFragment) {
  25332. if (childBlock.isBlock) {
  25333. removeHelper(OPEN_BLOCK);
  25334. removeHelper(
  25335. getVNodeBlockHelper(context.inSSR, childBlock.isComponent)
  25336. );
  25337. } else {
  25338. removeHelper(
  25339. getVNodeHelper(context.inSSR, childBlock.isComponent)
  25340. );
  25341. }
  25342. }
  25343. childBlock.isBlock = !isStableFragment;
  25344. if (childBlock.isBlock) {
  25345. helper(OPEN_BLOCK);
  25346. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  25347. } else {
  25348. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  25349. }
  25350. }
  25351. if (memo) {
  25352. const loop = createFunctionExpression(
  25353. createForLoopParams(forNode.parseResult, [
  25354. createSimpleExpression(`_cached`)
  25355. ])
  25356. );
  25357. loop.body = createBlockStatement([
  25358. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  25359. createCompoundExpression([
  25360. `if (_cached && _cached.el`,
  25361. ...keyExp ? [` && _cached.key === `, keyExp] : [],
  25362. ` && ${context.helperString(
  25363. IS_MEMO_SAME
  25364. )}(_cached, _memo)) return _cached`
  25365. ]),
  25366. createCompoundExpression([`const _item = `, childBlock]),
  25367. createSimpleExpression(`_item.memo = _memo`),
  25368. createSimpleExpression(`return _item`)
  25369. ]);
  25370. renderExp.arguments.push(
  25371. loop,
  25372. createSimpleExpression(`_cache`),
  25373. createSimpleExpression(String(context.cached.length))
  25374. );
  25375. context.cached.push(null);
  25376. } else {
  25377. renderExp.arguments.push(
  25378. createFunctionExpression(
  25379. createForLoopParams(forNode.parseResult),
  25380. childBlock,
  25381. true
  25382. )
  25383. );
  25384. }
  25385. };
  25386. });
  25387. }
  25388. );
  25389. function processFor(node, dir, context, processCodegen) {
  25390. if (!dir.exp) {
  25391. context.onError(
  25392. createCompilerError(31, dir.loc)
  25393. );
  25394. return;
  25395. }
  25396. const parseResult = dir.forParseResult;
  25397. if (!parseResult) {
  25398. context.onError(
  25399. createCompilerError(32, dir.loc)
  25400. );
  25401. return;
  25402. }
  25403. finalizeForParseResult(parseResult, context);
  25404. const { addIdentifiers, removeIdentifiers, scopes } = context;
  25405. const { source, value, key, index } = parseResult;
  25406. const forNode = {
  25407. type: 11,
  25408. loc: dir.loc,
  25409. source,
  25410. valueAlias: value,
  25411. keyAlias: key,
  25412. objectIndexAlias: index,
  25413. parseResult,
  25414. children: isTemplateNode(node) ? node.children : [node]
  25415. };
  25416. context.replaceNode(forNode);
  25417. scopes.vFor++;
  25418. if (context.prefixIdentifiers) {
  25419. value && addIdentifiers(value);
  25420. key && addIdentifiers(key);
  25421. index && addIdentifiers(index);
  25422. }
  25423. const onExit = processCodegen && processCodegen(forNode);
  25424. return () => {
  25425. scopes.vFor--;
  25426. if (context.prefixIdentifiers) {
  25427. value && removeIdentifiers(value);
  25428. key && removeIdentifiers(key);
  25429. index && removeIdentifiers(index);
  25430. }
  25431. if (onExit) onExit();
  25432. };
  25433. }
  25434. function finalizeForParseResult(result, context) {
  25435. if (result.finalized) return;
  25436. if (context.prefixIdentifiers) {
  25437. result.source = processExpression(
  25438. result.source,
  25439. context
  25440. );
  25441. if (result.key) {
  25442. result.key = processExpression(
  25443. result.key,
  25444. context,
  25445. true
  25446. );
  25447. }
  25448. if (result.index) {
  25449. result.index = processExpression(
  25450. result.index,
  25451. context,
  25452. true
  25453. );
  25454. }
  25455. if (result.value) {
  25456. result.value = processExpression(
  25457. result.value,
  25458. context,
  25459. true
  25460. );
  25461. }
  25462. }
  25463. result.finalized = true;
  25464. }
  25465. function createForLoopParams({ value, key, index }, memoArgs = []) {
  25466. return createParamsList([value, key, index, ...memoArgs]);
  25467. }
  25468. function createParamsList(args) {
  25469. let i = args.length;
  25470. while (i--) {
  25471. if (args[i]) break;
  25472. }
  25473. return args.slice(0, i + 1).map((arg, i2) => arg || createSimpleExpression(`_`.repeat(i2 + 1), false));
  25474. }
  25475. const defaultFallback = createSimpleExpression(`undefined`, false);
  25476. const trackSlotScopes = (node, context) => {
  25477. if (node.type === 1 && (node.tagType === 1 || node.tagType === 3)) {
  25478. const vSlot = findDir(node, "slot");
  25479. if (vSlot) {
  25480. const slotProps = vSlot.exp;
  25481. if (context.prefixIdentifiers) {
  25482. slotProps && context.addIdentifiers(slotProps);
  25483. }
  25484. context.scopes.vSlot++;
  25485. return () => {
  25486. if (context.prefixIdentifiers) {
  25487. slotProps && context.removeIdentifiers(slotProps);
  25488. }
  25489. context.scopes.vSlot--;
  25490. };
  25491. }
  25492. }
  25493. };
  25494. const trackVForSlotScopes = (node, context) => {
  25495. let vFor;
  25496. if (isTemplateNode(node) && node.props.some(isVSlot) && (vFor = findDir(node, "for"))) {
  25497. const result = vFor.forParseResult;
  25498. if (result) {
  25499. finalizeForParseResult(result, context);
  25500. const { value, key, index } = result;
  25501. const { addIdentifiers, removeIdentifiers } = context;
  25502. value && addIdentifiers(value);
  25503. key && addIdentifiers(key);
  25504. index && addIdentifiers(index);
  25505. return () => {
  25506. value && removeIdentifiers(value);
  25507. key && removeIdentifiers(key);
  25508. index && removeIdentifiers(index);
  25509. };
  25510. }
  25511. }
  25512. };
  25513. const buildClientSlotFn = (props, _vForExp, children, loc) => createFunctionExpression(
  25514. props,
  25515. children,
  25516. false,
  25517. true,
  25518. children.length ? children[0].loc : loc
  25519. );
  25520. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  25521. context.helper(WITH_CTX);
  25522. const { children, loc } = node;
  25523. const slotsProperties = [];
  25524. const dynamicSlots = [];
  25525. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  25526. if (!context.ssr && context.prefixIdentifiers) {
  25527. hasDynamicSlots = node.props.some(
  25528. (prop) => isVSlot(prop) && (hasScopeRef(prop.arg, context.identifiers) || hasScopeRef(prop.exp, context.identifiers))
  25529. ) || children.some((child) => hasScopeRef(child, context.identifiers));
  25530. }
  25531. const onComponentSlot = findDir(node, "slot", true);
  25532. if (onComponentSlot) {
  25533. const { arg, exp } = onComponentSlot;
  25534. if (arg && !isStaticExp(arg)) {
  25535. hasDynamicSlots = true;
  25536. }
  25537. slotsProperties.push(
  25538. createObjectProperty(
  25539. arg || createSimpleExpression("default", true),
  25540. buildSlotFn(exp, void 0, children, loc)
  25541. )
  25542. );
  25543. }
  25544. let hasTemplateSlots = false;
  25545. let hasNamedDefaultSlot = false;
  25546. const implicitDefaultChildren = [];
  25547. const seenSlotNames = /* @__PURE__ */ new Set();
  25548. let conditionalBranchIndex = 0;
  25549. for (let i = 0; i < children.length; i++) {
  25550. const slotElement = children[i];
  25551. let slotDir;
  25552. if (!isTemplateNode(slotElement) || !(slotDir = findDir(slotElement, "slot", true))) {
  25553. if (slotElement.type !== 3) {
  25554. implicitDefaultChildren.push(slotElement);
  25555. }
  25556. continue;
  25557. }
  25558. if (onComponentSlot) {
  25559. context.onError(
  25560. createCompilerError(37, slotDir.loc)
  25561. );
  25562. break;
  25563. }
  25564. hasTemplateSlots = true;
  25565. const { children: slotChildren, loc: slotLoc } = slotElement;
  25566. const {
  25567. arg: slotName = createSimpleExpression(`default`, true),
  25568. exp: slotProps,
  25569. loc: dirLoc
  25570. } = slotDir;
  25571. let staticSlotName;
  25572. if (isStaticExp(slotName)) {
  25573. staticSlotName = slotName ? slotName.content : `default`;
  25574. } else {
  25575. hasDynamicSlots = true;
  25576. }
  25577. const vFor = findDir(slotElement, "for");
  25578. const slotFunction = buildSlotFn(slotProps, vFor, slotChildren, slotLoc);
  25579. let vIf;
  25580. let vElse;
  25581. if (vIf = findDir(slotElement, "if")) {
  25582. hasDynamicSlots = true;
  25583. dynamicSlots.push(
  25584. createConditionalExpression(
  25585. vIf.exp,
  25586. buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++),
  25587. defaultFallback
  25588. )
  25589. );
  25590. } else if (vElse = findDir(
  25591. slotElement,
  25592. /^else(?:-if)?$/,
  25593. true
  25594. /* allowEmpty */
  25595. )) {
  25596. let j = i;
  25597. let prev;
  25598. while (j--) {
  25599. prev = children[j];
  25600. if (!isCommentOrWhitespace(prev)) {
  25601. break;
  25602. }
  25603. }
  25604. if (prev && isTemplateNode(prev) && findDir(prev, /^(?:else-)?if$/)) {
  25605. let conditional = dynamicSlots[dynamicSlots.length - 1];
  25606. while (conditional.alternate.type === 19) {
  25607. conditional = conditional.alternate;
  25608. }
  25609. conditional.alternate = vElse.exp ? createConditionalExpression(
  25610. vElse.exp,
  25611. buildDynamicSlot(
  25612. slotName,
  25613. slotFunction,
  25614. conditionalBranchIndex++
  25615. ),
  25616. defaultFallback
  25617. ) : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  25618. } else {
  25619. context.onError(
  25620. createCompilerError(30, vElse.loc)
  25621. );
  25622. }
  25623. } else if (vFor) {
  25624. hasDynamicSlots = true;
  25625. const parseResult = vFor.forParseResult;
  25626. if (parseResult) {
  25627. finalizeForParseResult(parseResult, context);
  25628. dynamicSlots.push(
  25629. createCallExpression(context.helper(RENDER_LIST), [
  25630. parseResult.source,
  25631. createFunctionExpression(
  25632. createForLoopParams(parseResult),
  25633. buildDynamicSlot(slotName, slotFunction),
  25634. true
  25635. )
  25636. ])
  25637. );
  25638. } else {
  25639. context.onError(
  25640. createCompilerError(
  25641. 32,
  25642. vFor.loc
  25643. )
  25644. );
  25645. }
  25646. } else {
  25647. if (staticSlotName) {
  25648. if (seenSlotNames.has(staticSlotName)) {
  25649. context.onError(
  25650. createCompilerError(
  25651. 38,
  25652. dirLoc
  25653. )
  25654. );
  25655. continue;
  25656. }
  25657. seenSlotNames.add(staticSlotName);
  25658. if (staticSlotName === "default") {
  25659. hasNamedDefaultSlot = true;
  25660. }
  25661. }
  25662. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  25663. }
  25664. }
  25665. if (!onComponentSlot) {
  25666. const buildDefaultSlotProperty = (props, children2) => {
  25667. const fn = buildSlotFn(props, void 0, children2, loc);
  25668. return createObjectProperty(`default`, fn);
  25669. };
  25670. if (!hasTemplateSlots) {
  25671. slotsProperties.push(buildDefaultSlotProperty(void 0, children));
  25672. } else if (implicitDefaultChildren.length && // #3766
  25673. // with whitespace: 'preserve', whitespaces between slots will end up in
  25674. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  25675. !implicitDefaultChildren.every(isWhitespaceText)) {
  25676. if (hasNamedDefaultSlot) {
  25677. context.onError(
  25678. createCompilerError(
  25679. 39,
  25680. implicitDefaultChildren[0].loc
  25681. )
  25682. );
  25683. } else {
  25684. slotsProperties.push(
  25685. buildDefaultSlotProperty(void 0, implicitDefaultChildren)
  25686. );
  25687. }
  25688. }
  25689. }
  25690. const slotFlag = hasDynamicSlots ? 2 : hasForwardedSlots(node.children) ? 3 : 1;
  25691. let slots = createObjectExpression(
  25692. slotsProperties.concat(
  25693. createObjectProperty(
  25694. `_`,
  25695. // 2 = compiled but dynamic = can skip normalization, but must run diff
  25696. // 1 = compiled and static = can skip normalization AND diff as optimized
  25697. createSimpleExpression(
  25698. slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ),
  25699. false
  25700. )
  25701. )
  25702. ),
  25703. loc
  25704. );
  25705. if (dynamicSlots.length) {
  25706. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  25707. slots,
  25708. createArrayExpression(dynamicSlots)
  25709. ]);
  25710. }
  25711. return {
  25712. slots,
  25713. hasDynamicSlots
  25714. };
  25715. }
  25716. function buildDynamicSlot(name, fn, index) {
  25717. const props = [
  25718. createObjectProperty(`name`, name),
  25719. createObjectProperty(`fn`, fn)
  25720. ];
  25721. if (index != null) {
  25722. props.push(
  25723. createObjectProperty(`key`, createSimpleExpression(String(index), true))
  25724. );
  25725. }
  25726. return createObjectExpression(props);
  25727. }
  25728. function hasForwardedSlots(children) {
  25729. for (let i = 0; i < children.length; i++) {
  25730. const child = children[i];
  25731. switch (child.type) {
  25732. case 1:
  25733. if (child.tagType === 2 || hasForwardedSlots(child.children)) {
  25734. return true;
  25735. }
  25736. break;
  25737. case 9:
  25738. if (hasForwardedSlots(child.branches)) return true;
  25739. break;
  25740. case 10:
  25741. case 11:
  25742. if (hasForwardedSlots(child.children)) return true;
  25743. break;
  25744. }
  25745. }
  25746. return false;
  25747. }
  25748. const directiveImportMap = /* @__PURE__ */ new WeakMap();
  25749. const transformElement = (node, context) => {
  25750. return function postTransformElement() {
  25751. node = context.currentNode;
  25752. if (!(node.type === 1 && (node.tagType === 0 || node.tagType === 1))) {
  25753. return;
  25754. }
  25755. const { tag, props } = node;
  25756. const isComponent = node.tagType === 1;
  25757. let vnodeTag = isComponent ? resolveComponentType(node, context) : `"${tag}"`;
  25758. const isDynamicComponent = isObject$2(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  25759. let vnodeProps;
  25760. let vnodeChildren;
  25761. let patchFlag = 0;
  25762. let vnodeDynamicProps;
  25763. let dynamicPropNames;
  25764. let vnodeDirectives;
  25765. let shouldUseBlock = (
  25766. // dynamic component may resolve to plain elements
  25767. isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || !isComponent && // <svg> and <foreignObject> must be forced into blocks so that block
  25768. // updates inside get proper isSVG flag at runtime. (#639, #643)
  25769. // This is technically web-specific, but splitting the logic out of core
  25770. // leads to too much unnecessary complexity.
  25771. (tag === "svg" || tag === "foreignObject" || tag === "math")
  25772. );
  25773. if (props.length > 0) {
  25774. const propsBuildResult = buildProps(
  25775. node,
  25776. context,
  25777. void 0,
  25778. isComponent,
  25779. isDynamicComponent
  25780. );
  25781. vnodeProps = propsBuildResult.props;
  25782. patchFlag = propsBuildResult.patchFlag;
  25783. dynamicPropNames = propsBuildResult.dynamicPropNames;
  25784. const directives = propsBuildResult.directives;
  25785. vnodeDirectives = directives && directives.length ? createArrayExpression(
  25786. directives.map((dir) => buildDirectiveArgs(dir, context))
  25787. ) : void 0;
  25788. if (propsBuildResult.shouldUseBlock) {
  25789. shouldUseBlock = true;
  25790. }
  25791. }
  25792. if (node.children.length > 0) {
  25793. if (vnodeTag === KEEP_ALIVE) {
  25794. shouldUseBlock = true;
  25795. patchFlag |= 1024;
  25796. if (node.children.length > 1) {
  25797. context.onError(
  25798. createCompilerError(47, {
  25799. start: node.children[0].loc.start,
  25800. end: node.children[node.children.length - 1].loc.end,
  25801. source: ""
  25802. })
  25803. );
  25804. }
  25805. }
  25806. const shouldBuildAsSlots = isComponent && // Teleport is not a real component and has dedicated runtime handling
  25807. vnodeTag !== TELEPORT && // explained above.
  25808. vnodeTag !== KEEP_ALIVE;
  25809. if (shouldBuildAsSlots) {
  25810. const { slots, hasDynamicSlots } = buildSlots(node, context);
  25811. vnodeChildren = slots;
  25812. if (hasDynamicSlots) {
  25813. patchFlag |= 1024;
  25814. }
  25815. } else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  25816. const child = node.children[0];
  25817. const type = child.type;
  25818. const hasDynamicTextChild = type === 5 || type === 8;
  25819. if (hasDynamicTextChild && getConstantType(child, context) === 0) {
  25820. patchFlag |= 1;
  25821. }
  25822. if (hasDynamicTextChild || type === 2) {
  25823. vnodeChildren = child;
  25824. } else {
  25825. vnodeChildren = node.children;
  25826. }
  25827. } else {
  25828. vnodeChildren = node.children;
  25829. }
  25830. }
  25831. if (dynamicPropNames && dynamicPropNames.length) {
  25832. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  25833. }
  25834. node.codegenNode = createVNodeCall(
  25835. context,
  25836. vnodeTag,
  25837. vnodeProps,
  25838. vnodeChildren,
  25839. patchFlag === 0 ? void 0 : patchFlag,
  25840. vnodeDynamicProps,
  25841. vnodeDirectives,
  25842. !!shouldUseBlock,
  25843. false,
  25844. isComponent,
  25845. node.loc
  25846. );
  25847. };
  25848. };
  25849. function resolveComponentType(node, context, ssr = false) {
  25850. let { tag } = node;
  25851. const isExplicitDynamic = isComponentTag(tag);
  25852. const isProp = findProp(
  25853. node,
  25854. "is",
  25855. false,
  25856. true
  25857. /* allow empty */
  25858. );
  25859. if (isProp) {
  25860. if (isExplicitDynamic || false) {
  25861. let exp;
  25862. if (isProp.type === 6) {
  25863. exp = isProp.value && createSimpleExpression(isProp.value.content, true);
  25864. } else {
  25865. exp = isProp.exp;
  25866. if (!exp) {
  25867. exp = createSimpleExpression(`is`, false, isProp.arg.loc);
  25868. {
  25869. exp = isProp.exp = processExpression(exp, context);
  25870. }
  25871. }
  25872. }
  25873. if (exp) {
  25874. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  25875. exp
  25876. ]);
  25877. }
  25878. } else if (isProp.type === 6 && isProp.value.content.startsWith("vue:")) {
  25879. tag = isProp.value.content.slice(4);
  25880. }
  25881. }
  25882. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  25883. if (builtIn) {
  25884. if (!ssr) context.helper(builtIn);
  25885. return builtIn;
  25886. }
  25887. {
  25888. const fromSetup = resolveSetupReference(tag, context);
  25889. if (fromSetup) {
  25890. return fromSetup;
  25891. }
  25892. const dotIndex = tag.indexOf(".");
  25893. if (dotIndex > 0) {
  25894. const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
  25895. if (ns) {
  25896. return ns + tag.slice(dotIndex);
  25897. }
  25898. }
  25899. }
  25900. if (context.selfName && capitalize(camelize(tag)) === context.selfName) {
  25901. context.helper(RESOLVE_COMPONENT);
  25902. context.components.add(tag + `__self`);
  25903. return toValidAssetId(tag, `component`);
  25904. }
  25905. context.helper(RESOLVE_COMPONENT);
  25906. context.components.add(tag);
  25907. return toValidAssetId(tag, `component`);
  25908. }
  25909. function resolveSetupReference(name, context) {
  25910. const bindings = context.bindingMetadata;
  25911. if (!bindings || bindings.__isScriptSetup === false) {
  25912. return;
  25913. }
  25914. const camelName = camelize(name);
  25915. const PascalName = capitalize(camelName);
  25916. const checkType = (type) => {
  25917. if (bindings[name] === type) {
  25918. return name;
  25919. }
  25920. if (bindings[camelName] === type) {
  25921. return camelName;
  25922. }
  25923. if (bindings[PascalName] === type) {
  25924. return PascalName;
  25925. }
  25926. };
  25927. const fromConst = checkType("setup-const") || checkType("setup-reactive-const") || checkType("literal-const");
  25928. if (fromConst) {
  25929. return context.inline ? (
  25930. // in inline mode, const setup bindings (e.g. imports) can be used as-is
  25931. fromConst
  25932. ) : `$setup[${JSON.stringify(fromConst)}]`;
  25933. }
  25934. const fromMaybeRef = checkType("setup-let") || checkType("setup-ref") || checkType("setup-maybe-ref");
  25935. if (fromMaybeRef) {
  25936. return context.inline ? (
  25937. // setup scope bindings that may be refs need to be unrefed
  25938. `${context.helperString(UNREF)}(${fromMaybeRef})`
  25939. ) : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  25940. }
  25941. const fromProps = checkType("props");
  25942. if (fromProps) {
  25943. return `${context.helperString(UNREF)}(${context.inline ? "__props" : "$props"}[${JSON.stringify(fromProps)}])`;
  25944. }
  25945. }
  25946. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  25947. const { tag, loc: elementLoc, children } = node;
  25948. let properties = [];
  25949. const mergeArgs = [];
  25950. const runtimeDirectives = [];
  25951. const hasChildren = children.length > 0;
  25952. let shouldUseBlock = false;
  25953. let patchFlag = 0;
  25954. let hasRef = false;
  25955. let hasClassBinding = false;
  25956. let hasStyleBinding = false;
  25957. let hasHydrationEventBinding = false;
  25958. let hasDynamicKeys = false;
  25959. let hasVnodeHook = false;
  25960. const dynamicPropNames = [];
  25961. const pushMergeArg = (arg) => {
  25962. if (properties.length) {
  25963. mergeArgs.push(
  25964. createObjectExpression(dedupeProperties(properties), elementLoc)
  25965. );
  25966. properties = [];
  25967. }
  25968. if (arg) mergeArgs.push(arg);
  25969. };
  25970. const pushRefVForMarker = () => {
  25971. if (context.scopes.vFor > 0) {
  25972. properties.push(
  25973. createObjectProperty(
  25974. createSimpleExpression("ref_for", true),
  25975. createSimpleExpression("true")
  25976. )
  25977. );
  25978. }
  25979. };
  25980. const analyzePatchFlag = ({ key, value }) => {
  25981. if (isStaticExp(key)) {
  25982. const name = key.content;
  25983. const isEventHandler = isOn(name);
  25984. if (isEventHandler && (!isComponent || isDynamicComponent) && // omit the flag for click handlers because hydration gives click
  25985. // dedicated fast path.
  25986. name.toLowerCase() !== "onclick" && // omit v-model handlers
  25987. name !== "onUpdate:modelValue" && // omit onVnodeXXX hooks
  25988. !isReservedProp(name)) {
  25989. hasHydrationEventBinding = true;
  25990. }
  25991. if (isEventHandler && isReservedProp(name)) {
  25992. hasVnodeHook = true;
  25993. }
  25994. if (isEventHandler && value.type === 14) {
  25995. value = value.arguments[0];
  25996. }
  25997. if (value.type === 20 || (value.type === 4 || value.type === 8) && getConstantType(value, context) > 0) {
  25998. return;
  25999. }
  26000. if (name === "ref") {
  26001. hasRef = true;
  26002. } else if (name === "class") {
  26003. hasClassBinding = true;
  26004. } else if (name === "style") {
  26005. hasStyleBinding = true;
  26006. } else if (name !== "key" && !dynamicPropNames.includes(name)) {
  26007. dynamicPropNames.push(name);
  26008. }
  26009. if (isComponent && (name === "class" || name === "style") && !dynamicPropNames.includes(name)) {
  26010. dynamicPropNames.push(name);
  26011. }
  26012. } else {
  26013. hasDynamicKeys = true;
  26014. }
  26015. };
  26016. for (let i = 0; i < props.length; i++) {
  26017. const prop = props[i];
  26018. if (prop.type === 6) {
  26019. const { loc, name, nameLoc, value } = prop;
  26020. let isStatic = true;
  26021. if (name === "ref") {
  26022. hasRef = true;
  26023. pushRefVForMarker();
  26024. if (value && context.inline) {
  26025. const binding = context.bindingMetadata[value.content];
  26026. if (binding === "setup-let" || binding === "setup-ref" || binding === "setup-maybe-ref") {
  26027. isStatic = false;
  26028. properties.push(
  26029. createObjectProperty(
  26030. createSimpleExpression("ref_key", true),
  26031. createSimpleExpression(value.content, true, value.loc)
  26032. )
  26033. );
  26034. }
  26035. }
  26036. }
  26037. if (name === "is" && (isComponentTag(tag) || value && value.content.startsWith("vue:") || false)) {
  26038. continue;
  26039. }
  26040. properties.push(
  26041. createObjectProperty(
  26042. createSimpleExpression(name, true, nameLoc),
  26043. createSimpleExpression(
  26044. value ? value.content : "",
  26045. isStatic,
  26046. value ? value.loc : loc
  26047. )
  26048. )
  26049. );
  26050. } else {
  26051. const { name, arg, exp, loc, modifiers } = prop;
  26052. const isVBind = name === "bind";
  26053. const isVOn = name === "on";
  26054. if (name === "slot") {
  26055. if (!isComponent) {
  26056. context.onError(
  26057. createCompilerError(40, loc)
  26058. );
  26059. }
  26060. continue;
  26061. }
  26062. if (name === "once" || name === "memo") {
  26063. continue;
  26064. }
  26065. if (name === "is" || isVBind && isStaticArgOf(arg, "is") && (isComponentTag(tag) || false)) {
  26066. continue;
  26067. }
  26068. if (isVOn && ssr) {
  26069. continue;
  26070. }
  26071. if (
  26072. // #938: elements with dynamic keys should be forced into blocks
  26073. isVBind && isStaticArgOf(arg, "key") || // inline before-update hooks need to force block so that it is invoked
  26074. // before children
  26075. isVOn && hasChildren && isStaticArgOf(arg, "vue:before-update")
  26076. ) {
  26077. shouldUseBlock = true;
  26078. }
  26079. if (isVBind && isStaticArgOf(arg, "ref")) {
  26080. pushRefVForMarker();
  26081. }
  26082. if (!arg && (isVBind || isVOn)) {
  26083. hasDynamicKeys = true;
  26084. if (exp) {
  26085. if (isVBind) {
  26086. pushRefVForMarker();
  26087. pushMergeArg();
  26088. mergeArgs.push(exp);
  26089. } else {
  26090. pushMergeArg({
  26091. type: 14,
  26092. loc,
  26093. callee: context.helper(TO_HANDLERS),
  26094. arguments: isComponent ? [exp] : [exp, `true`]
  26095. });
  26096. }
  26097. } else {
  26098. context.onError(
  26099. createCompilerError(
  26100. isVBind ? 34 : 35,
  26101. loc
  26102. )
  26103. );
  26104. }
  26105. continue;
  26106. }
  26107. if (isVBind && modifiers.some((mod) => mod.content === "prop")) {
  26108. patchFlag |= 32;
  26109. }
  26110. const directiveTransform = context.directiveTransforms[name];
  26111. if (directiveTransform) {
  26112. const { props: props2, needRuntime } = directiveTransform(prop, node, context);
  26113. !ssr && props2.forEach(analyzePatchFlag);
  26114. if (isVOn && arg && !isStaticExp(arg)) {
  26115. pushMergeArg(createObjectExpression(props2, elementLoc));
  26116. } else {
  26117. properties.push(...props2);
  26118. }
  26119. if (needRuntime) {
  26120. runtimeDirectives.push(prop);
  26121. if (isSymbol$1(needRuntime)) {
  26122. directiveImportMap.set(prop, needRuntime);
  26123. }
  26124. }
  26125. } else if (!isBuiltInDirective(name)) {
  26126. runtimeDirectives.push(prop);
  26127. if (hasChildren) {
  26128. shouldUseBlock = true;
  26129. }
  26130. }
  26131. }
  26132. }
  26133. let propsExpression = void 0;
  26134. if (mergeArgs.length) {
  26135. pushMergeArg();
  26136. if (mergeArgs.length > 1) {
  26137. propsExpression = createCallExpression(
  26138. context.helper(MERGE_PROPS),
  26139. mergeArgs,
  26140. elementLoc
  26141. );
  26142. } else {
  26143. propsExpression = mergeArgs[0];
  26144. }
  26145. } else if (properties.length) {
  26146. propsExpression = createObjectExpression(
  26147. dedupeProperties(properties),
  26148. elementLoc
  26149. );
  26150. }
  26151. if (hasDynamicKeys) {
  26152. patchFlag |= 16;
  26153. } else {
  26154. if (hasClassBinding && !isComponent) {
  26155. patchFlag |= 2;
  26156. }
  26157. if (hasStyleBinding && !isComponent) {
  26158. patchFlag |= 4;
  26159. }
  26160. if (dynamicPropNames.length) {
  26161. patchFlag |= 8;
  26162. }
  26163. if (hasHydrationEventBinding) {
  26164. patchFlag |= 32;
  26165. }
  26166. }
  26167. if (!shouldUseBlock && (patchFlag === 0 || patchFlag === 32) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  26168. patchFlag |= 512;
  26169. }
  26170. if (!context.inSSR && propsExpression) {
  26171. switch (propsExpression.type) {
  26172. case 15:
  26173. let classKeyIndex = -1;
  26174. let styleKeyIndex = -1;
  26175. let hasDynamicKey = false;
  26176. for (let i = 0; i < propsExpression.properties.length; i++) {
  26177. const key = propsExpression.properties[i].key;
  26178. if (isStaticExp(key)) {
  26179. if (key.content === "class") {
  26180. classKeyIndex = i;
  26181. } else if (key.content === "style") {
  26182. styleKeyIndex = i;
  26183. }
  26184. } else if (!key.isHandlerKey) {
  26185. hasDynamicKey = true;
  26186. }
  26187. }
  26188. const classProp = propsExpression.properties[classKeyIndex];
  26189. const styleProp = propsExpression.properties[styleKeyIndex];
  26190. if (!hasDynamicKey) {
  26191. if (classProp && !isStaticExp(classProp.value)) {
  26192. classProp.value = createCallExpression(
  26193. context.helper(NORMALIZE_CLASS),
  26194. [classProp.value]
  26195. );
  26196. }
  26197. if (styleProp && // the static style is compiled into an object,
  26198. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  26199. (hasStyleBinding || styleProp.value.type === 4 && styleProp.value.content.trim()[0] === `[` || // v-bind:style and style both exist,
  26200. // v-bind:style with static literal object
  26201. styleProp.value.type === 17)) {
  26202. styleProp.value = createCallExpression(
  26203. context.helper(NORMALIZE_STYLE),
  26204. [styleProp.value]
  26205. );
  26206. }
  26207. } else {
  26208. propsExpression = createCallExpression(
  26209. context.helper(NORMALIZE_PROPS),
  26210. [propsExpression]
  26211. );
  26212. }
  26213. break;
  26214. case 14:
  26215. break;
  26216. default:
  26217. propsExpression = createCallExpression(
  26218. context.helper(NORMALIZE_PROPS),
  26219. [
  26220. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  26221. propsExpression
  26222. ])
  26223. ]
  26224. );
  26225. break;
  26226. }
  26227. }
  26228. return {
  26229. props: propsExpression,
  26230. directives: runtimeDirectives,
  26231. patchFlag,
  26232. dynamicPropNames,
  26233. shouldUseBlock
  26234. };
  26235. }
  26236. function dedupeProperties(properties) {
  26237. const knownProps = /* @__PURE__ */ new Map();
  26238. const deduped = [];
  26239. for (let i = 0; i < properties.length; i++) {
  26240. const prop = properties[i];
  26241. if (prop.key.type === 8 || !prop.key.isStatic) {
  26242. deduped.push(prop);
  26243. continue;
  26244. }
  26245. const name = prop.key.content;
  26246. const existing = knownProps.get(name);
  26247. if (existing) {
  26248. if (name === "style" || name === "class" || isOn(name)) {
  26249. mergeAsArray(existing, prop);
  26250. }
  26251. } else {
  26252. knownProps.set(name, prop);
  26253. deduped.push(prop);
  26254. }
  26255. }
  26256. return deduped;
  26257. }
  26258. function mergeAsArray(existing, incoming) {
  26259. if (existing.value.type === 17) {
  26260. existing.value.elements.push(incoming.value);
  26261. } else {
  26262. existing.value = createArrayExpression(
  26263. [existing.value, incoming.value],
  26264. existing.loc
  26265. );
  26266. }
  26267. }
  26268. function buildDirectiveArgs(dir, context) {
  26269. const dirArgs = [];
  26270. const runtime = directiveImportMap.get(dir);
  26271. if (runtime) {
  26272. dirArgs.push(context.helperString(runtime));
  26273. } else {
  26274. const fromSetup = resolveSetupReference("v-" + dir.name, context);
  26275. if (fromSetup) {
  26276. dirArgs.push(fromSetup);
  26277. } else {
  26278. context.helper(RESOLVE_DIRECTIVE);
  26279. context.directives.add(dir.name);
  26280. dirArgs.push(toValidAssetId(dir.name, `directive`));
  26281. }
  26282. }
  26283. const { loc } = dir;
  26284. if (dir.exp) dirArgs.push(dir.exp);
  26285. if (dir.arg) {
  26286. if (!dir.exp) {
  26287. dirArgs.push(`void 0`);
  26288. }
  26289. dirArgs.push(dir.arg);
  26290. }
  26291. if (Object.keys(dir.modifiers).length) {
  26292. if (!dir.arg) {
  26293. if (!dir.exp) {
  26294. dirArgs.push(`void 0`);
  26295. }
  26296. dirArgs.push(`void 0`);
  26297. }
  26298. const trueExpression = createSimpleExpression(`true`, false, loc);
  26299. dirArgs.push(
  26300. createObjectExpression(
  26301. dir.modifiers.map(
  26302. (modifier) => createObjectProperty(modifier, trueExpression)
  26303. ),
  26304. loc
  26305. )
  26306. );
  26307. }
  26308. return createArrayExpression(dirArgs, dir.loc);
  26309. }
  26310. function stringifyDynamicPropNames(props) {
  26311. let propsNamesString = `[`;
  26312. for (let i = 0, l = props.length; i < l; i++) {
  26313. propsNamesString += JSON.stringify(props[i]);
  26314. if (i < l - 1) propsNamesString += ", ";
  26315. }
  26316. return propsNamesString + `]`;
  26317. }
  26318. function isComponentTag(tag) {
  26319. return tag === "component" || tag === "Component";
  26320. }
  26321. const transformSlotOutlet = (node, context) => {
  26322. if (isSlotOutlet(node)) {
  26323. const { children, loc } = node;
  26324. const { slotName, slotProps } = processSlotOutlet(node, context);
  26325. const slotArgs = [
  26326. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  26327. slotName,
  26328. "{}",
  26329. "undefined",
  26330. "true"
  26331. ];
  26332. let expectedLen = 2;
  26333. if (slotProps) {
  26334. slotArgs[2] = slotProps;
  26335. expectedLen = 3;
  26336. }
  26337. if (children.length) {
  26338. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  26339. expectedLen = 4;
  26340. }
  26341. if (context.scopeId && !context.slotted) {
  26342. expectedLen = 5;
  26343. }
  26344. slotArgs.splice(expectedLen);
  26345. node.codegenNode = createCallExpression(
  26346. context.helper(RENDER_SLOT),
  26347. slotArgs,
  26348. loc
  26349. );
  26350. }
  26351. };
  26352. function processSlotOutlet(node, context) {
  26353. let slotName = `"default"`;
  26354. let slotProps = void 0;
  26355. const nonNameProps = [];
  26356. for (let i = 0; i < node.props.length; i++) {
  26357. const p = node.props[i];
  26358. if (p.type === 6) {
  26359. if (p.value) {
  26360. if (p.name === "name") {
  26361. slotName = JSON.stringify(p.value.content);
  26362. } else {
  26363. p.name = camelize(p.name);
  26364. nonNameProps.push(p);
  26365. }
  26366. }
  26367. } else {
  26368. if (p.name === "bind" && isStaticArgOf(p.arg, "name")) {
  26369. if (p.exp) {
  26370. slotName = p.exp;
  26371. } else if (p.arg && p.arg.type === 4) {
  26372. const name = camelize(p.arg.content);
  26373. slotName = p.exp = createSimpleExpression(name, false, p.arg.loc);
  26374. {
  26375. slotName = p.exp = processExpression(p.exp, context);
  26376. }
  26377. }
  26378. } else {
  26379. if (p.name === "bind" && p.arg && isStaticExp(p.arg)) {
  26380. p.arg.content = camelize(p.arg.content);
  26381. }
  26382. nonNameProps.push(p);
  26383. }
  26384. }
  26385. }
  26386. if (nonNameProps.length > 0) {
  26387. const { props, directives } = buildProps(
  26388. node,
  26389. context,
  26390. nonNameProps,
  26391. false,
  26392. false
  26393. );
  26394. slotProps = props;
  26395. if (directives.length) {
  26396. context.onError(
  26397. createCompilerError(
  26398. 36,
  26399. directives[0].loc
  26400. )
  26401. );
  26402. }
  26403. }
  26404. return {
  26405. slotName,
  26406. slotProps
  26407. };
  26408. }
  26409. const transformOn$1 = (dir, node, context, augmentor) => {
  26410. const { loc, modifiers, arg } = dir;
  26411. if (!dir.exp && !modifiers.length) {
  26412. context.onError(createCompilerError(35, loc));
  26413. }
  26414. let eventName;
  26415. if (arg.type === 4) {
  26416. if (arg.isStatic) {
  26417. let rawName = arg.content;
  26418. if (rawName.startsWith("vnode")) {
  26419. context.onError(createCompilerError(52, arg.loc));
  26420. }
  26421. if (rawName.startsWith("vue:")) {
  26422. rawName = `vnode-${rawName.slice(4)}`;
  26423. }
  26424. const eventString = node.tagType !== 0 || rawName.startsWith("vnode") || !/[A-Z]/.test(rawName) ? (
  26425. // for non-element and vnode lifecycle event listeners, auto convert
  26426. // it to camelCase. See issue #2249
  26427. toHandlerKey(camelize(rawName))
  26428. ) : (
  26429. // preserve case for plain element listeners that have uppercase
  26430. // letters, as these may be custom elements' custom events
  26431. `on:${rawName}`
  26432. );
  26433. eventName = createSimpleExpression(eventString, true, arg.loc);
  26434. } else {
  26435. eventName = createCompoundExpression([
  26436. `${context.helperString(TO_HANDLER_KEY)}(`,
  26437. arg,
  26438. `)`
  26439. ]);
  26440. }
  26441. } else {
  26442. eventName = arg;
  26443. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  26444. eventName.children.push(`)`);
  26445. }
  26446. let exp = dir.exp;
  26447. if (exp && !exp.content.trim()) {
  26448. exp = void 0;
  26449. }
  26450. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  26451. if (exp) {
  26452. const isMemberExp = isMemberExpression(exp, context);
  26453. const isInlineStatement = !(isMemberExp || isFnExpression(exp, context));
  26454. const hasMultipleStatements = exp.content.includes(`;`);
  26455. if (context.prefixIdentifiers) {
  26456. isInlineStatement && context.addIdentifiers(`$event`);
  26457. exp = dir.exp = processExpression(
  26458. exp,
  26459. context,
  26460. false,
  26461. hasMultipleStatements
  26462. );
  26463. isInlineStatement && context.removeIdentifiers(`$event`);
  26464. shouldCache = context.cacheHandlers && // unnecessary to cache inside v-once
  26465. !context.inVOnce && // runtime constants don't need to be cached
  26466. // (this is analyzed by compileScript in SFC <script setup>)
  26467. !(exp.type === 4 && exp.constType > 0) && // #1541 bail if this is a member exp handler passed to a component -
  26468. // we need to use the original function to preserve arity,
  26469. // e.g. <transition> relies on checking cb.length to determine
  26470. // transition end handling. Inline function is ok since its arity
  26471. // is preserved even when cached.
  26472. !(isMemberExp && node.tagType === 1) && // bail if the function references closure variables (v-for, v-slot)
  26473. // it must be passed fresh to avoid stale values.
  26474. !hasScopeRef(exp, context.identifiers);
  26475. if (shouldCache && isMemberExp) {
  26476. if (exp.type === 4) {
  26477. exp.content = `${exp.content} && ${exp.content}(...args)`;
  26478. } else {
  26479. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  26480. }
  26481. }
  26482. }
  26483. if (isInlineStatement || shouldCache && isMemberExp) {
  26484. exp = createCompoundExpression([
  26485. `${isInlineStatement ? context.isTS ? `($event: any)` : `$event` : `${context.isTS ? `
  26486. //@ts-ignore
  26487. ` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  26488. exp,
  26489. hasMultipleStatements ? `}` : `)`
  26490. ]);
  26491. }
  26492. }
  26493. let ret = {
  26494. props: [
  26495. createObjectProperty(
  26496. eventName,
  26497. exp || createSimpleExpression(`() => {}`, false, loc)
  26498. )
  26499. ]
  26500. };
  26501. if (augmentor) {
  26502. ret = augmentor(ret);
  26503. }
  26504. if (shouldCache) {
  26505. ret.props[0].value = context.cache(ret.props[0].value);
  26506. }
  26507. ret.props.forEach((p) => p.key.isHandlerKey = true);
  26508. return ret;
  26509. };
  26510. const transformBind = (dir, _node, context) => {
  26511. const { modifiers, loc } = dir;
  26512. const arg = dir.arg;
  26513. let { exp } = dir;
  26514. if (exp && exp.type === 4 && !exp.content.trim()) {
  26515. {
  26516. context.onError(
  26517. createCompilerError(34, loc)
  26518. );
  26519. return {
  26520. props: [
  26521. createObjectProperty(arg, createSimpleExpression("", true, loc))
  26522. ]
  26523. };
  26524. }
  26525. }
  26526. if (arg.type !== 4) {
  26527. arg.children.unshift(`(`);
  26528. arg.children.push(`) || ""`);
  26529. } else if (!arg.isStatic) {
  26530. arg.content = arg.content ? `${arg.content} || ""` : `""`;
  26531. }
  26532. if (modifiers.some((mod) => mod.content === "camel")) {
  26533. if (arg.type === 4) {
  26534. if (arg.isStatic) {
  26535. arg.content = camelize(arg.content);
  26536. } else {
  26537. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  26538. }
  26539. } else {
  26540. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  26541. arg.children.push(`)`);
  26542. }
  26543. }
  26544. if (!context.inSSR) {
  26545. if (modifiers.some((mod) => mod.content === "prop")) {
  26546. injectPrefix(arg, ".");
  26547. }
  26548. if (modifiers.some((mod) => mod.content === "attr")) {
  26549. injectPrefix(arg, "^");
  26550. }
  26551. }
  26552. return {
  26553. props: [createObjectProperty(arg, exp)]
  26554. };
  26555. };
  26556. const injectPrefix = (arg, prefix) => {
  26557. if (arg.type === 4) {
  26558. if (arg.isStatic) {
  26559. arg.content = prefix + arg.content;
  26560. } else {
  26561. arg.content = `\`${prefix}\${${arg.content}}\``;
  26562. }
  26563. } else {
  26564. arg.children.unshift(`'${prefix}' + (`);
  26565. arg.children.push(`)`);
  26566. }
  26567. };
  26568. const transformText = (node, context) => {
  26569. if (node.type === 0 || node.type === 1 || node.type === 11 || node.type === 10) {
  26570. return () => {
  26571. const children = node.children;
  26572. let currentContainer = void 0;
  26573. let hasText = false;
  26574. for (let i = 0; i < children.length; i++) {
  26575. const child = children[i];
  26576. if (isText$1(child)) {
  26577. hasText = true;
  26578. for (let j = i + 1; j < children.length; j++) {
  26579. const next = children[j];
  26580. if (isText$1(next)) {
  26581. if (!currentContainer) {
  26582. currentContainer = children[i] = createCompoundExpression(
  26583. [child],
  26584. child.loc
  26585. );
  26586. }
  26587. currentContainer.children.push(` + `, next);
  26588. children.splice(j, 1);
  26589. j--;
  26590. } else {
  26591. currentContainer = void 0;
  26592. break;
  26593. }
  26594. }
  26595. }
  26596. }
  26597. if (!hasText || // if this is a plain element with a single text child, leave it
  26598. // as-is since the runtime has dedicated fast path for this by directly
  26599. // setting textContent of the element.
  26600. // for component root it's always normalized anyway.
  26601. children.length === 1 && (node.type === 0 || node.type === 1 && node.tagType === 0 && // #3756
  26602. // custom directives can potentially add DOM elements arbitrarily,
  26603. // we need to avoid setting textContent of the element at runtime
  26604. // to avoid accidentally overwriting the DOM elements added
  26605. // by the user through custom directives.
  26606. !node.props.find(
  26607. (p) => p.type === 7 && !context.directiveTransforms[p.name]
  26608. ) && // in compat mode, <template> tags with no special directives
  26609. // will be rendered as a fragment so its children must be
  26610. // converted into vnodes.
  26611. true)) {
  26612. return;
  26613. }
  26614. for (let i = 0; i < children.length; i++) {
  26615. const child = children[i];
  26616. if (isText$1(child) || child.type === 8) {
  26617. const callArgs = [];
  26618. if (child.type !== 2 || child.content !== " ") {
  26619. callArgs.push(child);
  26620. }
  26621. if (!context.ssr && getConstantType(child, context) === 0) {
  26622. callArgs.push(
  26623. 1 + (` /* ${PatchFlagNames[1]} */` )
  26624. );
  26625. }
  26626. children[i] = {
  26627. type: 12,
  26628. content: child,
  26629. loc: child.loc,
  26630. codegenNode: createCallExpression(
  26631. context.helper(CREATE_TEXT),
  26632. callArgs
  26633. )
  26634. };
  26635. }
  26636. }
  26637. };
  26638. }
  26639. };
  26640. const seen$1 = /* @__PURE__ */ new WeakSet();
  26641. const transformOnce = (node, context) => {
  26642. if (node.type === 1 && findDir(node, "once", true)) {
  26643. if (seen$1.has(node) || context.inVOnce || context.inSSR) {
  26644. return;
  26645. }
  26646. seen$1.add(node);
  26647. context.inVOnce = true;
  26648. context.helper(SET_BLOCK_TRACKING);
  26649. return () => {
  26650. context.inVOnce = false;
  26651. const cur = context.currentNode;
  26652. if (cur.codegenNode) {
  26653. cur.codegenNode = context.cache(
  26654. cur.codegenNode,
  26655. true,
  26656. true
  26657. );
  26658. }
  26659. };
  26660. }
  26661. };
  26662. const transformModel$1 = (dir, node, context) => {
  26663. const { exp, arg } = dir;
  26664. if (!exp) {
  26665. context.onError(
  26666. createCompilerError(41, dir.loc)
  26667. );
  26668. return createTransformProps();
  26669. }
  26670. const rawExp = exp.loc.source.trim();
  26671. const expString = exp.type === 4 ? exp.content : rawExp;
  26672. const bindingType = context.bindingMetadata[rawExp];
  26673. if (bindingType === "props" || bindingType === "props-aliased") {
  26674. context.onError(createCompilerError(44, exp.loc));
  26675. return createTransformProps();
  26676. }
  26677. if (bindingType === "literal-const" || bindingType === "setup-const") {
  26678. context.onError(createCompilerError(45, exp.loc));
  26679. return createTransformProps();
  26680. }
  26681. const maybeRef = context.inline && (bindingType === "setup-let" || bindingType === "setup-ref" || bindingType === "setup-maybe-ref");
  26682. if (!expString.trim() || !isMemberExpression(exp, context) && !maybeRef) {
  26683. context.onError(
  26684. createCompilerError(42, exp.loc)
  26685. );
  26686. return createTransformProps();
  26687. }
  26688. if (context.prefixIdentifiers && isSimpleIdentifier(expString) && context.identifiers[expString]) {
  26689. context.onError(
  26690. createCompilerError(43, exp.loc)
  26691. );
  26692. return createTransformProps();
  26693. }
  26694. const propName = arg ? arg : createSimpleExpression("modelValue", true);
  26695. const eventName = arg ? isStaticExp(arg) ? `onUpdate:${camelize(arg.content)}` : createCompoundExpression(['"onUpdate:" + ', arg]) : `onUpdate:modelValue`;
  26696. let assignmentExp;
  26697. const eventArg = context.isTS ? `($event: any)` : `$event`;
  26698. if (maybeRef) {
  26699. if (bindingType === "setup-ref") {
  26700. assignmentExp = createCompoundExpression([
  26701. `${eventArg} => ((`,
  26702. createSimpleExpression(rawExp, false, exp.loc),
  26703. `).value = $event)`
  26704. ]);
  26705. } else {
  26706. const altAssignment = bindingType === "setup-let" ? `${rawExp} = $event` : `null`;
  26707. assignmentExp = createCompoundExpression([
  26708. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
  26709. createSimpleExpression(rawExp, false, exp.loc),
  26710. `).value = $event : ${altAssignment})`
  26711. ]);
  26712. }
  26713. } else {
  26714. assignmentExp = createCompoundExpression([
  26715. `${eventArg} => ((`,
  26716. exp,
  26717. `) = $event)`
  26718. ]);
  26719. }
  26720. const props = [
  26721. // modelValue: foo
  26722. createObjectProperty(propName, dir.exp),
  26723. // "onUpdate:modelValue": $event => (foo = $event)
  26724. createObjectProperty(eventName, assignmentExp)
  26725. ];
  26726. if (context.prefixIdentifiers && !context.inVOnce && context.cacheHandlers && !hasScopeRef(exp, context.identifiers)) {
  26727. props[1].value = context.cache(props[1].value);
  26728. }
  26729. if (dir.modifiers.length && node.tagType === 1) {
  26730. const modifiers = dir.modifiers.map((m) => m.content).map((m) => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`).join(`, `);
  26731. const modifiersKey = arg ? isStaticExp(arg) ? `${arg.content}Modifiers` : createCompoundExpression([arg, ' + "Modifiers"']) : `modelModifiers`;
  26732. props.push(
  26733. createObjectProperty(
  26734. modifiersKey,
  26735. createSimpleExpression(
  26736. `{ ${modifiers} }`,
  26737. false,
  26738. dir.loc,
  26739. 2
  26740. )
  26741. )
  26742. );
  26743. }
  26744. return createTransformProps(props);
  26745. };
  26746. function createTransformProps(props = []) {
  26747. return { props };
  26748. }
  26749. const seen = /* @__PURE__ */ new WeakSet();
  26750. const transformMemo = (node, context) => {
  26751. if (node.type === 1) {
  26752. const dir = findDir(node, "memo");
  26753. if (!dir || seen.has(node) || context.inSSR) {
  26754. return;
  26755. }
  26756. seen.add(node);
  26757. return () => {
  26758. const codegenNode = node.codegenNode || context.currentNode.codegenNode;
  26759. if (codegenNode && codegenNode.type === 13) {
  26760. if (node.tagType !== 1) {
  26761. convertToBlock(codegenNode, context);
  26762. }
  26763. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  26764. dir.exp,
  26765. createFunctionExpression(void 0, codegenNode),
  26766. `_cache`,
  26767. String(context.cached.length)
  26768. ]);
  26769. context.cached.push(null);
  26770. }
  26771. };
  26772. }
  26773. };
  26774. const transformVBindShorthand = (node, context) => {
  26775. if (node.type === 1) {
  26776. for (const prop of node.props) {
  26777. if (prop.type === 7 && prop.name === "bind" && (!prop.exp || // #13930 :foo in in-DOM templates will be parsed into :foo="" by browser
  26778. false) && prop.arg) {
  26779. const arg = prop.arg;
  26780. if (arg.type !== 4 || !arg.isStatic) {
  26781. context.onError(
  26782. createCompilerError(
  26783. 53,
  26784. arg.loc
  26785. )
  26786. );
  26787. prop.exp = createSimpleExpression("", true, arg.loc);
  26788. } else {
  26789. const propName = camelize(arg.content);
  26790. if (validFirstIdentCharRE.test(propName[0]) || // allow hyphen first char for https://github.com/vuejs/language-tools/pull/3424
  26791. propName[0] === "-") {
  26792. prop.exp = createSimpleExpression(propName, false, arg.loc);
  26793. }
  26794. }
  26795. }
  26796. }
  26797. }
  26798. };
  26799. function getBaseTransformPreset(prefixIdentifiers) {
  26800. return [
  26801. [
  26802. transformVBindShorthand,
  26803. transformOnce,
  26804. transformIf,
  26805. transformMemo,
  26806. transformFor,
  26807. ...[],
  26808. ...prefixIdentifiers ? [
  26809. // order is important
  26810. trackVForSlotScopes,
  26811. transformExpression
  26812. ] : [],
  26813. transformSlotOutlet,
  26814. transformElement,
  26815. trackSlotScopes,
  26816. transformText
  26817. ],
  26818. {
  26819. on: transformOn$1,
  26820. bind: transformBind,
  26821. model: transformModel$1
  26822. }
  26823. ];
  26824. }
  26825. function baseCompile(source, options = {}) {
  26826. const onError = options.onError || defaultOnError;
  26827. const isModuleMode = options.mode === "module";
  26828. const prefixIdentifiers = options.prefixIdentifiers === true || isModuleMode;
  26829. if (!prefixIdentifiers && options.cacheHandlers) {
  26830. onError(createCompilerError(50));
  26831. }
  26832. if (options.scopeId && !isModuleMode) {
  26833. onError(createCompilerError(51));
  26834. }
  26835. const resolvedOptions = extend({}, options, {
  26836. prefixIdentifiers
  26837. });
  26838. const ast = isString$1(source) ? baseParse(source, resolvedOptions) : source;
  26839. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  26840. if (options.isTS) {
  26841. const { expressionPlugins } = options;
  26842. if (!expressionPlugins || !expressionPlugins.includes("typescript")) {
  26843. options.expressionPlugins = [...expressionPlugins || [], "typescript"];
  26844. }
  26845. }
  26846. transform(
  26847. ast,
  26848. extend({}, resolvedOptions, {
  26849. nodeTransforms: [
  26850. ...nodeTransforms,
  26851. ...options.nodeTransforms || []
  26852. // user transforms
  26853. ],
  26854. directiveTransforms: extend(
  26855. {},
  26856. directiveTransforms,
  26857. options.directiveTransforms || {}
  26858. // user transforms
  26859. )
  26860. })
  26861. );
  26862. return generate(ast, resolvedOptions);
  26863. }
  26864. const BindingTypes = {
  26865. "DATA": "data",
  26866. "PROPS": "props",
  26867. "PROPS_ALIASED": "props-aliased",
  26868. "SETUP_LET": "setup-let",
  26869. "SETUP_CONST": "setup-const",
  26870. "SETUP_REACTIVE_CONST": "setup-reactive-const",
  26871. "SETUP_MAYBE_REF": "setup-maybe-ref",
  26872. "SETUP_REF": "setup-ref",
  26873. "OPTIONS": "options",
  26874. "LITERAL_CONST": "literal-const"
  26875. };
  26876. const noopDirectiveTransform = () => ({ props: [] });
  26877. const V_MODEL_RADIO = /* @__PURE__ */ Symbol(`vModelRadio` );
  26878. const V_MODEL_CHECKBOX = /* @__PURE__ */ Symbol(
  26879. `vModelCheckbox`
  26880. );
  26881. const V_MODEL_TEXT = /* @__PURE__ */ Symbol(`vModelText` );
  26882. const V_MODEL_SELECT = /* @__PURE__ */ Symbol(
  26883. `vModelSelect`
  26884. );
  26885. const V_MODEL_DYNAMIC = /* @__PURE__ */ Symbol(
  26886. `vModelDynamic`
  26887. );
  26888. const V_ON_WITH_MODIFIERS = /* @__PURE__ */ Symbol(
  26889. `vOnModifiersGuard`
  26890. );
  26891. const V_ON_WITH_KEYS = /* @__PURE__ */ Symbol(
  26892. `vOnKeysGuard`
  26893. );
  26894. const V_SHOW = /* @__PURE__ */ Symbol(`vShow` );
  26895. const TRANSITION = /* @__PURE__ */ Symbol(`Transition` );
  26896. const TRANSITION_GROUP = /* @__PURE__ */ Symbol(
  26897. `TransitionGroup`
  26898. );
  26899. registerRuntimeHelpers({
  26900. [V_MODEL_RADIO]: `vModelRadio`,
  26901. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  26902. [V_MODEL_TEXT]: `vModelText`,
  26903. [V_MODEL_SELECT]: `vModelSelect`,
  26904. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  26905. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  26906. [V_ON_WITH_KEYS]: `withKeys`,
  26907. [V_SHOW]: `vShow`,
  26908. [TRANSITION]: `Transition`,
  26909. [TRANSITION_GROUP]: `TransitionGroup`
  26910. });
  26911. const parserOptions = {
  26912. parseMode: "html",
  26913. isVoidTag,
  26914. isNativeTag: (tag) => isHTMLTag(tag) || isSVGTag(tag) || isMathMLTag(tag),
  26915. isPreTag: (tag) => tag === "pre",
  26916. isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea",
  26917. decodeEntities: void 0,
  26918. isBuiltInComponent: (tag) => {
  26919. if (tag === "Transition" || tag === "transition") {
  26920. return TRANSITION;
  26921. } else if (tag === "TransitionGroup" || tag === "transition-group") {
  26922. return TRANSITION_GROUP;
  26923. }
  26924. },
  26925. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  26926. getNamespace(tag, parent, rootNamespace) {
  26927. let ns = parent ? parent.ns : rootNamespace;
  26928. if (parent && ns === 2) {
  26929. if (parent.tag === "annotation-xml") {
  26930. if (tag === "svg") {
  26931. return 1;
  26932. }
  26933. if (parent.props.some(
  26934. (a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml")
  26935. )) {
  26936. ns = 0;
  26937. }
  26938. } else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") {
  26939. ns = 0;
  26940. }
  26941. } else if (parent && ns === 1) {
  26942. if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") {
  26943. ns = 0;
  26944. }
  26945. }
  26946. if (ns === 0) {
  26947. if (tag === "svg") {
  26948. return 1;
  26949. }
  26950. if (tag === "math") {
  26951. return 2;
  26952. }
  26953. }
  26954. return ns;
  26955. }
  26956. };
  26957. const transformStyle = (node) => {
  26958. if (node.type === 1) {
  26959. node.props.forEach((p, i) => {
  26960. if (p.type === 6 && p.name === "style" && p.value) {
  26961. node.props[i] = {
  26962. type: 7,
  26963. name: `bind`,
  26964. arg: createSimpleExpression(`style`, true, p.loc),
  26965. exp: parseInlineCSS(p.value.content, p.loc),
  26966. modifiers: [],
  26967. loc: p.loc
  26968. };
  26969. }
  26970. });
  26971. }
  26972. };
  26973. const parseInlineCSS = (cssText, loc) => {
  26974. const normalized = parseStringStyle(cssText);
  26975. return createSimpleExpression(
  26976. JSON.stringify(normalized),
  26977. false,
  26978. loc,
  26979. 3
  26980. );
  26981. };
  26982. function createDOMCompilerError(code, loc) {
  26983. return createCompilerError(
  26984. code,
  26985. loc,
  26986. DOMErrorMessages
  26987. );
  26988. }
  26989. const DOMErrorCodes = {
  26990. "X_V_HTML_NO_EXPRESSION": 54,
  26991. "54": "X_V_HTML_NO_EXPRESSION",
  26992. "X_V_HTML_WITH_CHILDREN": 55,
  26993. "55": "X_V_HTML_WITH_CHILDREN",
  26994. "X_V_TEXT_NO_EXPRESSION": 56,
  26995. "56": "X_V_TEXT_NO_EXPRESSION",
  26996. "X_V_TEXT_WITH_CHILDREN": 57,
  26997. "57": "X_V_TEXT_WITH_CHILDREN",
  26998. "X_V_MODEL_ON_INVALID_ELEMENT": 58,
  26999. "58": "X_V_MODEL_ON_INVALID_ELEMENT",
  27000. "X_V_MODEL_ARG_ON_ELEMENT": 59,
  27001. "59": "X_V_MODEL_ARG_ON_ELEMENT",
  27002. "X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60,
  27003. "60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT",
  27004. "X_V_MODEL_UNNECESSARY_VALUE": 61,
  27005. "61": "X_V_MODEL_UNNECESSARY_VALUE",
  27006. "X_V_SHOW_NO_EXPRESSION": 62,
  27007. "62": "X_V_SHOW_NO_EXPRESSION",
  27008. "X_TRANSITION_INVALID_CHILDREN": 63,
  27009. "63": "X_TRANSITION_INVALID_CHILDREN",
  27010. "X_IGNORED_SIDE_EFFECT_TAG": 64,
  27011. "64": "X_IGNORED_SIDE_EFFECT_TAG",
  27012. "__EXTEND_POINT__": 65,
  27013. "65": "__EXTEND_POINT__"
  27014. };
  27015. const DOMErrorMessages = {
  27016. [54]: `v-html is missing expression.`,
  27017. [55]: `v-html will override element children.`,
  27018. [56]: `v-text is missing expression.`,
  27019. [57]: `v-text will override element children.`,
  27020. [58]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  27021. [59]: `v-model argument is not supported on plain elements.`,
  27022. [60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  27023. [61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  27024. [62]: `v-show is missing expression.`,
  27025. [63]: `<Transition> expects exactly one child element or component.`,
  27026. [64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  27027. };
  27028. const transformVHtml = (dir, node, context) => {
  27029. const { exp, loc } = dir;
  27030. if (!exp) {
  27031. context.onError(
  27032. createDOMCompilerError(54, loc)
  27033. );
  27034. }
  27035. if (node.children.length) {
  27036. context.onError(
  27037. createDOMCompilerError(55, loc)
  27038. );
  27039. node.children.length = 0;
  27040. }
  27041. return {
  27042. props: [
  27043. createObjectProperty(
  27044. createSimpleExpression(`innerHTML`, true, loc),
  27045. exp || createSimpleExpression("", true)
  27046. )
  27047. ]
  27048. };
  27049. };
  27050. const transformVText = (dir, node, context) => {
  27051. const { exp, loc } = dir;
  27052. if (!exp) {
  27053. context.onError(
  27054. createDOMCompilerError(56, loc)
  27055. );
  27056. }
  27057. if (node.children.length) {
  27058. context.onError(
  27059. createDOMCompilerError(57, loc)
  27060. );
  27061. node.children.length = 0;
  27062. }
  27063. return {
  27064. props: [
  27065. createObjectProperty(
  27066. createSimpleExpression(`textContent`, true),
  27067. exp ? getConstantType(exp, context) > 0 ? exp : createCallExpression(
  27068. context.helperString(TO_DISPLAY_STRING),
  27069. [exp],
  27070. loc
  27071. ) : createSimpleExpression("", true)
  27072. )
  27073. ]
  27074. };
  27075. };
  27076. const transformModel = (dir, node, context) => {
  27077. const baseResult = transformModel$1(dir, node, context);
  27078. if (!baseResult.props.length || node.tagType === 1) {
  27079. return baseResult;
  27080. }
  27081. if (dir.arg) {
  27082. context.onError(
  27083. createDOMCompilerError(
  27084. 59,
  27085. dir.arg.loc
  27086. )
  27087. );
  27088. }
  27089. function checkDuplicatedValue() {
  27090. const value = findDir(node, "bind");
  27091. if (value && isStaticArgOf(value.arg, "value")) {
  27092. context.onError(
  27093. createDOMCompilerError(
  27094. 61,
  27095. value.loc
  27096. )
  27097. );
  27098. }
  27099. }
  27100. const { tag } = node;
  27101. const isCustomElement = context.isCustomElement(tag);
  27102. if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
  27103. let directiveToUse = V_MODEL_TEXT;
  27104. let isInvalidType = false;
  27105. if (tag === "input" || isCustomElement) {
  27106. const type = findProp(node, `type`);
  27107. if (type) {
  27108. if (type.type === 7) {
  27109. directiveToUse = V_MODEL_DYNAMIC;
  27110. } else if (type.value) {
  27111. switch (type.value.content) {
  27112. case "radio":
  27113. directiveToUse = V_MODEL_RADIO;
  27114. break;
  27115. case "checkbox":
  27116. directiveToUse = V_MODEL_CHECKBOX;
  27117. break;
  27118. case "file":
  27119. isInvalidType = true;
  27120. context.onError(
  27121. createDOMCompilerError(
  27122. 60,
  27123. dir.loc
  27124. )
  27125. );
  27126. break;
  27127. default:
  27128. checkDuplicatedValue();
  27129. break;
  27130. }
  27131. }
  27132. } else if (hasDynamicKeyVBind(node)) {
  27133. directiveToUse = V_MODEL_DYNAMIC;
  27134. } else {
  27135. checkDuplicatedValue();
  27136. }
  27137. } else if (tag === "select") {
  27138. directiveToUse = V_MODEL_SELECT;
  27139. } else {
  27140. checkDuplicatedValue();
  27141. }
  27142. if (!isInvalidType) {
  27143. baseResult.needRuntime = context.helper(directiveToUse);
  27144. }
  27145. } else {
  27146. context.onError(
  27147. createDOMCompilerError(
  27148. 58,
  27149. dir.loc
  27150. )
  27151. );
  27152. }
  27153. baseResult.props = baseResult.props.filter(
  27154. (p) => !(p.key.type === 4 && p.key.content === "modelValue")
  27155. );
  27156. return baseResult;
  27157. };
  27158. const isEventOptionModifier = /* @__PURE__ */ makeMap(`passive,once,capture`);
  27159. const isNonKeyModifier = /* @__PURE__ */ makeMap(
  27160. // event propagation management
  27161. `stop,prevent,self,ctrl,shift,alt,meta,exact,middle`
  27162. );
  27163. const maybeKeyModifier = /* @__PURE__ */ makeMap("left,right");
  27164. const isKeyboardEvent = /* @__PURE__ */ makeMap(`onkeyup,onkeydown,onkeypress`);
  27165. const resolveModifiers = (key, modifiers, context, loc) => {
  27166. const keyModifiers = [];
  27167. const nonKeyModifiers = [];
  27168. const eventOptionModifiers = [];
  27169. for (let i = 0; i < modifiers.length; i++) {
  27170. const modifier = modifiers[i].content;
  27171. if (isEventOptionModifier(modifier)) {
  27172. eventOptionModifiers.push(modifier);
  27173. } else {
  27174. if (maybeKeyModifier(modifier)) {
  27175. if (isStaticExp(key)) {
  27176. if (isKeyboardEvent(key.content.toLowerCase())) {
  27177. keyModifiers.push(modifier);
  27178. } else {
  27179. nonKeyModifiers.push(modifier);
  27180. }
  27181. } else {
  27182. keyModifiers.push(modifier);
  27183. nonKeyModifiers.push(modifier);
  27184. }
  27185. } else {
  27186. if (isNonKeyModifier(modifier)) {
  27187. nonKeyModifiers.push(modifier);
  27188. } else {
  27189. keyModifiers.push(modifier);
  27190. }
  27191. }
  27192. }
  27193. }
  27194. return {
  27195. keyModifiers,
  27196. nonKeyModifiers,
  27197. eventOptionModifiers
  27198. };
  27199. };
  27200. const transformClick = (key, event) => {
  27201. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === "onclick";
  27202. return isStaticClick ? createSimpleExpression(event, true) : key.type !== 4 ? createCompoundExpression([
  27203. `(`,
  27204. key,
  27205. `) === "onClick" ? "${event}" : (`,
  27206. key,
  27207. `)`
  27208. ]) : key;
  27209. };
  27210. const transformOn = (dir, node, context) => {
  27211. return transformOn$1(dir, node, context, (baseResult) => {
  27212. const { modifiers } = dir;
  27213. if (!modifiers.length) return baseResult;
  27214. let { key, value: handlerExp } = baseResult.props[0];
  27215. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  27216. if (nonKeyModifiers.includes("right")) {
  27217. key = transformClick(key, `onContextmenu`);
  27218. }
  27219. if (nonKeyModifiers.includes("middle")) {
  27220. key = transformClick(key, `onMouseup`);
  27221. }
  27222. if (nonKeyModifiers.length) {
  27223. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  27224. handlerExp,
  27225. JSON.stringify(nonKeyModifiers)
  27226. ]);
  27227. }
  27228. if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard
  27229. (!isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) {
  27230. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  27231. handlerExp,
  27232. JSON.stringify(keyModifiers)
  27233. ]);
  27234. }
  27235. if (eventOptionModifiers.length) {
  27236. const modifierPostfix = eventOptionModifiers.map(capitalize).join("");
  27237. key = isStaticExp(key) ? createSimpleExpression(`${key.content}${modifierPostfix}`, true) : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  27238. }
  27239. return {
  27240. props: [createObjectProperty(key, handlerExp)]
  27241. };
  27242. });
  27243. };
  27244. const transformShow = (dir, node, context) => {
  27245. const { exp, loc } = dir;
  27246. if (!exp) {
  27247. context.onError(
  27248. createDOMCompilerError(62, loc)
  27249. );
  27250. }
  27251. return {
  27252. props: [],
  27253. needRuntime: context.helper(V_SHOW)
  27254. };
  27255. };
  27256. const transformTransition = (node, context) => {
  27257. if (node.type === 1 && node.tagType === 1) {
  27258. const component = context.isBuiltInComponent(node.tag);
  27259. if (component === TRANSITION) {
  27260. return () => {
  27261. if (!node.children.length) {
  27262. return;
  27263. }
  27264. if (hasMultipleChildren(node)) {
  27265. context.onError(
  27266. createDOMCompilerError(
  27267. 63,
  27268. {
  27269. start: node.children[0].loc.start,
  27270. end: node.children[node.children.length - 1].loc.end,
  27271. source: ""
  27272. }
  27273. )
  27274. );
  27275. }
  27276. const child = node.children[0];
  27277. if (child.type === 1) {
  27278. for (const p of child.props) {
  27279. if (p.type === 7 && p.name === "show") {
  27280. node.props.push({
  27281. type: 6,
  27282. name: "persisted",
  27283. nameLoc: node.loc,
  27284. value: void 0,
  27285. loc: node.loc
  27286. });
  27287. }
  27288. }
  27289. }
  27290. };
  27291. }
  27292. }
  27293. };
  27294. function hasMultipleChildren(node) {
  27295. const children = node.children = node.children.filter(
  27296. (c) => !isCommentOrWhitespace(c)
  27297. );
  27298. const child = children[0];
  27299. return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren);
  27300. }
  27301. const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
  27302. const stringifyStatic = (children, context, parent) => {
  27303. if (context.scopes.vSlot > 0) {
  27304. return;
  27305. }
  27306. const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !isArray$3(parent.codegenNode.children) && parent.codegenNode.children.type === 20;
  27307. let nc = 0;
  27308. let ec = 0;
  27309. const currentChunk = [];
  27310. const stringifyCurrentChunk = (currentIndex) => {
  27311. if (nc >= 20 || ec >= 5) {
  27312. const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
  27313. JSON.stringify(
  27314. currentChunk.map((node) => stringifyNode(node, context)).join("")
  27315. ).replace(expReplaceRE, `" + $1 + "`),
  27316. // the 2nd argument indicates the number of DOM nodes this static vnode
  27317. // will insert / hydrate
  27318. String(currentChunk.length)
  27319. ]);
  27320. const deleteCount = currentChunk.length - 1;
  27321. if (isParentCached) {
  27322. children.splice(
  27323. currentIndex - currentChunk.length,
  27324. currentChunk.length,
  27325. // @ts-expect-error
  27326. staticCall
  27327. );
  27328. } else {
  27329. currentChunk[0].codegenNode.value = staticCall;
  27330. if (currentChunk.length > 1) {
  27331. children.splice(currentIndex - currentChunk.length + 1, deleteCount);
  27332. const cacheIndex = context.cached.indexOf(
  27333. currentChunk[currentChunk.length - 1].codegenNode
  27334. );
  27335. if (cacheIndex > -1) {
  27336. for (let i2 = cacheIndex; i2 < context.cached.length; i2++) {
  27337. const c = context.cached[i2];
  27338. if (c) c.index -= deleteCount;
  27339. }
  27340. context.cached.splice(cacheIndex - deleteCount + 1, deleteCount);
  27341. }
  27342. }
  27343. }
  27344. return deleteCount;
  27345. }
  27346. return 0;
  27347. };
  27348. let i = 0;
  27349. for (; i < children.length; i++) {
  27350. const child = children[i];
  27351. const isCached = isParentCached || getCachedNode(child);
  27352. if (isCached) {
  27353. const result = analyzeNode(child);
  27354. if (result) {
  27355. nc += result[0];
  27356. ec += result[1];
  27357. currentChunk.push(child);
  27358. continue;
  27359. }
  27360. }
  27361. i -= stringifyCurrentChunk(i);
  27362. nc = 0;
  27363. ec = 0;
  27364. currentChunk.length = 0;
  27365. }
  27366. stringifyCurrentChunk(i);
  27367. };
  27368. const getCachedNode = (node) => {
  27369. if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) {
  27370. return node.codegenNode;
  27371. }
  27372. };
  27373. const dataAriaRE = /^(?:data|aria)-/;
  27374. const isStringifiableAttr = (name, ns) => {
  27375. return (ns === 0 ? isKnownHtmlAttr(name) : ns === 1 ? isKnownSvgAttr(name) : ns === 2 ? isKnownMathMLAttr(name) : false) || dataAriaRE.test(name);
  27376. };
  27377. const isNonStringifiable = /* @__PURE__ */ makeMap(
  27378. `caption,thead,tr,th,tbody,td,tfoot,colgroup,col`
  27379. );
  27380. function analyzeNode(node) {
  27381. if (node.type === 1 && isNonStringifiable(node.tag)) {
  27382. return false;
  27383. }
  27384. if (node.type === 1 && findDir(node, "once", true)) {
  27385. return false;
  27386. }
  27387. if (node.type === 12) {
  27388. return [1, 0];
  27389. }
  27390. let nc = 1;
  27391. let ec = node.props.length > 0 ? 1 : 0;
  27392. let bailed = false;
  27393. const bail = () => {
  27394. bailed = true;
  27395. return false;
  27396. };
  27397. function walk(node2) {
  27398. const isOptionTag = node2.tag === "option" && node2.ns === 0;
  27399. for (let i = 0; i < node2.props.length; i++) {
  27400. const p = node2.props[i];
  27401. if (p.type === 6 && !isStringifiableAttr(p.name, node2.ns)) {
  27402. return bail();
  27403. }
  27404. if (p.type === 7 && p.name === "bind") {
  27405. if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node2.ns))) {
  27406. return bail();
  27407. }
  27408. if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) {
  27409. return bail();
  27410. }
  27411. if (isOptionTag && isStaticArgOf(p.arg, "value") && p.exp && !p.exp.isStatic) {
  27412. return bail();
  27413. }
  27414. }
  27415. }
  27416. for (let i = 0; i < node2.children.length; i++) {
  27417. nc++;
  27418. const child = node2.children[i];
  27419. if (child.type === 1) {
  27420. if (child.props.length > 0) {
  27421. ec++;
  27422. }
  27423. walk(child);
  27424. if (bailed) {
  27425. return false;
  27426. }
  27427. }
  27428. }
  27429. return true;
  27430. }
  27431. return walk(node) ? [nc, ec] : false;
  27432. }
  27433. function stringifyNode(node, context) {
  27434. if (isString$1(node)) {
  27435. return node;
  27436. }
  27437. if (isSymbol$1(node)) {
  27438. return ``;
  27439. }
  27440. switch (node.type) {
  27441. case 1:
  27442. return stringifyElement(node, context);
  27443. case 2:
  27444. return escapeHtml(node.content);
  27445. case 3:
  27446. return `<!--${escapeHtml(node.content)}-->`;
  27447. case 5:
  27448. return escapeHtml(toDisplayString(evaluateConstant(node.content)));
  27449. case 8:
  27450. return escapeHtml(evaluateConstant(node));
  27451. case 12:
  27452. return stringifyNode(node.content, context);
  27453. default:
  27454. return "";
  27455. }
  27456. }
  27457. function stringifyElement(node, context) {
  27458. let res = `<${node.tag}`;
  27459. let innerHTML = "";
  27460. for (let i = 0; i < node.props.length; i++) {
  27461. const p = node.props[i];
  27462. if (p.type === 6) {
  27463. res += ` ${p.name}`;
  27464. if (p.value) {
  27465. res += `="${escapeHtml(p.value.content)}"`;
  27466. }
  27467. } else if (p.type === 7) {
  27468. if (p.name === "bind") {
  27469. const exp = p.exp;
  27470. if (exp.content[0] === "_") {
  27471. res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
  27472. continue;
  27473. }
  27474. if (isBooleanAttr(p.arg.content) && exp.content === "false") {
  27475. continue;
  27476. }
  27477. let evaluated = evaluateConstant(exp);
  27478. if (evaluated != null) {
  27479. const arg = p.arg && p.arg.content;
  27480. if (arg === "class") {
  27481. evaluated = normalizeClass(evaluated);
  27482. } else if (arg === "style") {
  27483. evaluated = stringifyStyle(normalizeStyle(evaluated));
  27484. }
  27485. res += ` ${p.arg.content}="${escapeHtml(
  27486. evaluated
  27487. )}"`;
  27488. }
  27489. } else if (p.name === "html") {
  27490. innerHTML = evaluateConstant(p.exp);
  27491. } else if (p.name === "text") {
  27492. innerHTML = escapeHtml(
  27493. toDisplayString(evaluateConstant(p.exp))
  27494. );
  27495. }
  27496. }
  27497. }
  27498. if (context.scopeId) {
  27499. res += ` ${context.scopeId}`;
  27500. }
  27501. res += `>`;
  27502. if (innerHTML) {
  27503. res += innerHTML;
  27504. } else {
  27505. for (let i = 0; i < node.children.length; i++) {
  27506. res += stringifyNode(node.children[i], context);
  27507. }
  27508. }
  27509. if (!isVoidTag(node.tag)) {
  27510. res += `</${node.tag}>`;
  27511. }
  27512. return res;
  27513. }
  27514. function evaluateConstant(exp) {
  27515. if (exp.type === 4) {
  27516. return new Function(`return (${exp.content})`)();
  27517. } else {
  27518. let res = ``;
  27519. exp.children.forEach((c) => {
  27520. if (isString$1(c) || isSymbol$1(c)) {
  27521. return;
  27522. }
  27523. if (c.type === 2) {
  27524. res += c.content;
  27525. } else if (c.type === 5) {
  27526. res += toDisplayString(evaluateConstant(c.content));
  27527. } else {
  27528. res += evaluateConstant(c);
  27529. }
  27530. });
  27531. return res;
  27532. }
  27533. }
  27534. const ignoreSideEffectTags = (node, context) => {
  27535. if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) {
  27536. context.onError(
  27537. createDOMCompilerError(
  27538. 64,
  27539. node.loc
  27540. )
  27541. );
  27542. context.removeNode();
  27543. }
  27544. };
  27545. function isValidHTMLNesting(parent, child) {
  27546. if (parent === "template") {
  27547. return true;
  27548. }
  27549. if (parent in onlyValidChildren) {
  27550. return onlyValidChildren[parent].has(child);
  27551. }
  27552. if (child in onlyValidParents) {
  27553. return onlyValidParents[child].has(parent);
  27554. }
  27555. if (parent in knownInvalidChildren) {
  27556. if (knownInvalidChildren[parent].has(child)) return false;
  27557. }
  27558. if (child in knownInvalidParents) {
  27559. if (knownInvalidParents[child].has(parent)) return false;
  27560. }
  27561. return true;
  27562. }
  27563. const headings = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
  27564. const emptySet = /* @__PURE__ */ new Set([]);
  27565. const onlyValidChildren = {
  27566. head: /* @__PURE__ */ new Set([
  27567. "base",
  27568. "basefront",
  27569. "bgsound",
  27570. "link",
  27571. "meta",
  27572. "title",
  27573. "noscript",
  27574. "noframes",
  27575. "style",
  27576. "script",
  27577. "template"
  27578. ]),
  27579. optgroup: /* @__PURE__ */ new Set(["option"]),
  27580. select: /* @__PURE__ */ new Set(["optgroup", "option", "hr"]),
  27581. // table
  27582. table: /* @__PURE__ */ new Set(["caption", "colgroup", "tbody", "tfoot", "thead"]),
  27583. tr: /* @__PURE__ */ new Set(["td", "th"]),
  27584. colgroup: /* @__PURE__ */ new Set(["col"]),
  27585. tbody: /* @__PURE__ */ new Set(["tr"]),
  27586. thead: /* @__PURE__ */ new Set(["tr"]),
  27587. tfoot: /* @__PURE__ */ new Set(["tr"]),
  27588. // these elements can not have any children elements
  27589. script: emptySet,
  27590. iframe: emptySet,
  27591. option: emptySet,
  27592. textarea: emptySet,
  27593. style: emptySet,
  27594. title: emptySet
  27595. };
  27596. const onlyValidParents = {
  27597. // sections
  27598. html: emptySet,
  27599. body: /* @__PURE__ */ new Set(["html"]),
  27600. head: /* @__PURE__ */ new Set(["html"]),
  27601. // table
  27602. td: /* @__PURE__ */ new Set(["tr"]),
  27603. colgroup: /* @__PURE__ */ new Set(["table"]),
  27604. caption: /* @__PURE__ */ new Set(["table"]),
  27605. tbody: /* @__PURE__ */ new Set(["table"]),
  27606. tfoot: /* @__PURE__ */ new Set(["table"]),
  27607. col: /* @__PURE__ */ new Set(["colgroup"]),
  27608. th: /* @__PURE__ */ new Set(["tr"]),
  27609. thead: /* @__PURE__ */ new Set(["table"]),
  27610. tr: /* @__PURE__ */ new Set(["tbody", "thead", "tfoot"]),
  27611. // data list
  27612. dd: /* @__PURE__ */ new Set(["dl", "div"]),
  27613. dt: /* @__PURE__ */ new Set(["dl", "div"]),
  27614. // other
  27615. figcaption: /* @__PURE__ */ new Set(["figure"]),
  27616. // li: new Set(["ul", "ol"]),
  27617. summary: /* @__PURE__ */ new Set(["details"]),
  27618. area: /* @__PURE__ */ new Set(["map"])
  27619. };
  27620. const knownInvalidChildren = {
  27621. p: /* @__PURE__ */ new Set([
  27622. "address",
  27623. "article",
  27624. "aside",
  27625. "blockquote",
  27626. "center",
  27627. "details",
  27628. "dialog",
  27629. "dir",
  27630. "div",
  27631. "dl",
  27632. "fieldset",
  27633. "figure",
  27634. "footer",
  27635. "form",
  27636. "h1",
  27637. "h2",
  27638. "h3",
  27639. "h4",
  27640. "h5",
  27641. "h6",
  27642. "header",
  27643. "hgroup",
  27644. "hr",
  27645. "li",
  27646. "main",
  27647. "nav",
  27648. "menu",
  27649. "ol",
  27650. "p",
  27651. "pre",
  27652. "section",
  27653. "table",
  27654. "ul"
  27655. ]),
  27656. svg: /* @__PURE__ */ new Set([
  27657. "b",
  27658. "blockquote",
  27659. "br",
  27660. "code",
  27661. "dd",
  27662. "div",
  27663. "dl",
  27664. "dt",
  27665. "em",
  27666. "embed",
  27667. "h1",
  27668. "h2",
  27669. "h3",
  27670. "h4",
  27671. "h5",
  27672. "h6",
  27673. "hr",
  27674. "i",
  27675. "img",
  27676. "li",
  27677. "menu",
  27678. "meta",
  27679. "ol",
  27680. "p",
  27681. "pre",
  27682. "ruby",
  27683. "s",
  27684. "small",
  27685. "span",
  27686. "strong",
  27687. "sub",
  27688. "sup",
  27689. "table",
  27690. "u",
  27691. "ul",
  27692. "var"
  27693. ])
  27694. };
  27695. const knownInvalidParents = {
  27696. a: /* @__PURE__ */ new Set(["a"]),
  27697. button: /* @__PURE__ */ new Set(["button"]),
  27698. dd: /* @__PURE__ */ new Set(["dd", "dt"]),
  27699. dt: /* @__PURE__ */ new Set(["dd", "dt"]),
  27700. form: /* @__PURE__ */ new Set(["form"]),
  27701. li: /* @__PURE__ */ new Set(["li"]),
  27702. h1: headings,
  27703. h2: headings,
  27704. h3: headings,
  27705. h4: headings,
  27706. h5: headings,
  27707. h6: headings
  27708. };
  27709. const validateHtmlNesting = (node, context) => {
  27710. if (node.type === 1 && node.tagType === 0 && context.parent && context.parent.type === 1 && context.parent.tagType === 0 && !isValidHTMLNesting(context.parent.tag, node.tag)) {
  27711. const error = new SyntaxError(
  27712. `<${node.tag}> cannot be child of <${context.parent.tag}>, according to HTML specifications. This can cause hydration errors or potentially disrupt future functionality.`
  27713. );
  27714. error.loc = node.loc;
  27715. context.onWarn(error);
  27716. }
  27717. };
  27718. const DOMNodeTransforms = [
  27719. transformStyle,
  27720. ...[transformTransition, validateHtmlNesting]
  27721. ];
  27722. const DOMDirectiveTransforms = {
  27723. cloak: noopDirectiveTransform,
  27724. html: transformVHtml,
  27725. text: transformVText,
  27726. model: transformModel,
  27727. // override compiler-core
  27728. on: transformOn,
  27729. // override compiler-core
  27730. show: transformShow
  27731. };
  27732. function compile$1(src, options = {}) {
  27733. return baseCompile(
  27734. src,
  27735. extend({}, parserOptions, options, {
  27736. nodeTransforms: [
  27737. // ignore <script> and <tag>
  27738. // this is not put inside DOMNodeTransforms because that list is used
  27739. // by compiler-ssr to generate vnode fallback branches
  27740. ignoreSideEffectTags,
  27741. ...DOMNodeTransforms,
  27742. ...options.nodeTransforms || []
  27743. ],
  27744. directiveTransforms: extend(
  27745. {},
  27746. DOMDirectiveTransforms,
  27747. options.directiveTransforms || {}
  27748. ),
  27749. transformHoist: stringifyStatic
  27750. })
  27751. );
  27752. }
  27753. function parse$3(template, options = {}) {
  27754. return baseParse(template, extend({}, parserOptions, options));
  27755. }
  27756. var CompilerDOM = /*#__PURE__*/Object.freeze({
  27757. __proto__: null,
  27758. BASE_TRANSITION: BASE_TRANSITION,
  27759. BindingTypes: BindingTypes,
  27760. CAMELIZE: CAMELIZE,
  27761. CAPITALIZE: CAPITALIZE,
  27762. CREATE_BLOCK: CREATE_BLOCK,
  27763. CREATE_COMMENT: CREATE_COMMENT,
  27764. CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK,
  27765. CREATE_ELEMENT_VNODE: CREATE_ELEMENT_VNODE,
  27766. CREATE_SLOTS: CREATE_SLOTS,
  27767. CREATE_STATIC: CREATE_STATIC,
  27768. CREATE_TEXT: CREATE_TEXT,
  27769. CREATE_VNODE: CREATE_VNODE,
  27770. CompilerDeprecationTypes: CompilerDeprecationTypes,
  27771. ConstantTypes: ConstantTypes,
  27772. DOMDirectiveTransforms: DOMDirectiveTransforms,
  27773. DOMErrorCodes: DOMErrorCodes,
  27774. DOMErrorMessages: DOMErrorMessages,
  27775. DOMNodeTransforms: DOMNodeTransforms,
  27776. ElementTypes: ElementTypes,
  27777. ErrorCodes: ErrorCodes,
  27778. FRAGMENT: FRAGMENT,
  27779. GUARD_REACTIVE_PROPS: GUARD_REACTIVE_PROPS,
  27780. IS_MEMO_SAME: IS_MEMO_SAME,
  27781. IS_REF: IS_REF,
  27782. KEEP_ALIVE: KEEP_ALIVE,
  27783. MERGE_PROPS: MERGE_PROPS,
  27784. NORMALIZE_CLASS: NORMALIZE_CLASS,
  27785. NORMALIZE_PROPS: NORMALIZE_PROPS,
  27786. NORMALIZE_STYLE: NORMALIZE_STYLE,
  27787. Namespaces: Namespaces,
  27788. NodeTypes: NodeTypes,
  27789. OPEN_BLOCK: OPEN_BLOCK,
  27790. POP_SCOPE_ID: POP_SCOPE_ID,
  27791. PUSH_SCOPE_ID: PUSH_SCOPE_ID,
  27792. RENDER_LIST: RENDER_LIST,
  27793. RENDER_SLOT: RENDER_SLOT,
  27794. RESOLVE_COMPONENT: RESOLVE_COMPONENT,
  27795. RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
  27796. RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
  27797. RESOLVE_FILTER: RESOLVE_FILTER,
  27798. SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
  27799. SUSPENSE: SUSPENSE,
  27800. TELEPORT: TELEPORT,
  27801. TO_DISPLAY_STRING: TO_DISPLAY_STRING,
  27802. TO_HANDLERS: TO_HANDLERS,
  27803. TO_HANDLER_KEY: TO_HANDLER_KEY,
  27804. TRANSITION: TRANSITION,
  27805. TRANSITION_GROUP: TRANSITION_GROUP,
  27806. TS_NODE_TYPES: TS_NODE_TYPES,
  27807. UNREF: UNREF,
  27808. V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
  27809. V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
  27810. V_MODEL_RADIO: V_MODEL_RADIO,
  27811. V_MODEL_SELECT: V_MODEL_SELECT,
  27812. V_MODEL_TEXT: V_MODEL_TEXT,
  27813. V_ON_WITH_KEYS: V_ON_WITH_KEYS,
  27814. V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
  27815. V_SHOW: V_SHOW,
  27816. WITH_CTX: WITH_CTX,
  27817. WITH_DIRECTIVES: WITH_DIRECTIVES,
  27818. WITH_MEMO: WITH_MEMO,
  27819. advancePositionWithClone: advancePositionWithClone,
  27820. advancePositionWithMutation: advancePositionWithMutation,
  27821. assert: assert,
  27822. baseCompile: baseCompile,
  27823. baseParse: baseParse,
  27824. buildDirectiveArgs: buildDirectiveArgs,
  27825. buildProps: buildProps,
  27826. buildSlots: buildSlots,
  27827. checkCompatEnabled: checkCompatEnabled,
  27828. compile: compile$1,
  27829. convertToBlock: convertToBlock,
  27830. createArrayExpression: createArrayExpression,
  27831. createAssignmentExpression: createAssignmentExpression,
  27832. createBlockStatement: createBlockStatement,
  27833. createCacheExpression: createCacheExpression,
  27834. createCallExpression: createCallExpression,
  27835. createCompilerError: createCompilerError,
  27836. createCompoundExpression: createCompoundExpression,
  27837. createConditionalExpression: createConditionalExpression,
  27838. createDOMCompilerError: createDOMCompilerError,
  27839. createForLoopParams: createForLoopParams,
  27840. createFunctionExpression: createFunctionExpression,
  27841. createIfStatement: createIfStatement,
  27842. createInterpolation: createInterpolation,
  27843. createObjectExpression: createObjectExpression,
  27844. createObjectProperty: createObjectProperty,
  27845. createReturnStatement: createReturnStatement,
  27846. createRoot: createRoot,
  27847. createSequenceExpression: createSequenceExpression,
  27848. createSimpleExpression: createSimpleExpression,
  27849. createStructuralDirectiveTransform: createStructuralDirectiveTransform,
  27850. createTemplateLiteral: createTemplateLiteral,
  27851. createTransformContext: createTransformContext,
  27852. createVNodeCall: createVNodeCall,
  27853. errorMessages: errorMessages$1,
  27854. extractIdentifiers: extractIdentifiers$1,
  27855. findDir: findDir,
  27856. findProp: findProp,
  27857. forAliasRE: forAliasRE,
  27858. generate: generate,
  27859. generateCodeFrame: generateCodeFrame,
  27860. getBaseTransformPreset: getBaseTransformPreset,
  27861. getConstantType: getConstantType,
  27862. getMemoedVNodeCall: getMemoedVNodeCall,
  27863. getVNodeBlockHelper: getVNodeBlockHelper,
  27864. getVNodeHelper: getVNodeHelper,
  27865. hasDynamicKeyVBind: hasDynamicKeyVBind,
  27866. hasScopeRef: hasScopeRef,
  27867. helperNameMap: helperNameMap,
  27868. injectProp: injectProp,
  27869. isAllWhitespace: isAllWhitespace,
  27870. isCommentOrWhitespace: isCommentOrWhitespace,
  27871. isCoreComponent: isCoreComponent,
  27872. isFnExpression: isFnExpression,
  27873. isFnExpressionBrowser: isFnExpressionBrowser,
  27874. isFnExpressionNode: isFnExpressionNode,
  27875. isFunctionType: isFunctionType,
  27876. isInDestructureAssignment: isInDestructureAssignment,
  27877. isInNewExpression: isInNewExpression,
  27878. isMemberExpression: isMemberExpression,
  27879. isMemberExpressionBrowser: isMemberExpressionBrowser,
  27880. isMemberExpressionNode: isMemberExpressionNode,
  27881. isReferencedIdentifier: isReferencedIdentifier,
  27882. isSimpleIdentifier: isSimpleIdentifier,
  27883. isSlotOutlet: isSlotOutlet,
  27884. isStaticArgOf: isStaticArgOf,
  27885. isStaticExp: isStaticExp,
  27886. isStaticProperty: isStaticProperty,
  27887. isStaticPropertyKey: isStaticPropertyKey,
  27888. isTemplateNode: isTemplateNode,
  27889. isText: isText$1,
  27890. isVPre: isVPre,
  27891. isVSlot: isVSlot,
  27892. isWhitespaceText: isWhitespaceText,
  27893. locStub: locStub,
  27894. noopDirectiveTransform: noopDirectiveTransform,
  27895. parse: parse$3,
  27896. parserOptions: parserOptions,
  27897. processExpression: processExpression,
  27898. processFor: processFor,
  27899. processIf: processIf,
  27900. processSlotOutlet: processSlotOutlet,
  27901. registerRuntimeHelpers: registerRuntimeHelpers,
  27902. resolveComponentType: resolveComponentType,
  27903. stringifyExpression: stringifyExpression,
  27904. toValidAssetId: toValidAssetId,
  27905. trackSlotScopes: trackSlotScopes,
  27906. trackVForSlotScopes: trackVForSlotScopes,
  27907. transform: transform,
  27908. transformBind: transformBind,
  27909. transformElement: transformElement,
  27910. transformExpression: transformExpression,
  27911. transformModel: transformModel$1,
  27912. transformOn: transformOn$1,
  27913. transformStyle: transformStyle,
  27914. transformVBindShorthand: transformVBindShorthand,
  27915. traverseNode: traverseNode,
  27916. unwrapTSNode: unwrapTSNode,
  27917. validFirstIdentCharRE: validFirstIdentCharRE,
  27918. walkBlockDeclarations: walkBlockDeclarations,
  27919. walkFunctionParams: walkFunctionParams,
  27920. walkIdentifiers: walkIdentifiers,
  27921. warnDeprecation: warnDeprecation
  27922. });
  27923. var hashSum;
  27924. var hasRequiredHashSum;
  27925. function requireHashSum () {
  27926. if (hasRequiredHashSum) return hashSum;
  27927. hasRequiredHashSum = 1;
  27928. function pad (hash, len) {
  27929. while (hash.length < len) {
  27930. hash = '0' + hash;
  27931. }
  27932. return hash;
  27933. }
  27934. function fold (hash, text) {
  27935. var i;
  27936. var chr;
  27937. var len;
  27938. if (text.length === 0) {
  27939. return hash;
  27940. }
  27941. for (i = 0, len = text.length; i < len; i++) {
  27942. chr = text.charCodeAt(i);
  27943. hash = ((hash << 5) - hash) + chr;
  27944. hash |= 0;
  27945. }
  27946. return hash < 0 ? hash * -2 : hash;
  27947. }
  27948. function foldObject (hash, o, seen) {
  27949. return Object.keys(o).sort().reduce(foldKey, hash);
  27950. function foldKey (hash, key) {
  27951. return foldValue(hash, o[key], key, seen);
  27952. }
  27953. }
  27954. function foldValue (input, value, key, seen) {
  27955. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  27956. if (value === null) {
  27957. return fold(hash, 'null');
  27958. }
  27959. if (value === undefined) {
  27960. return fold(hash, 'undefined');
  27961. }
  27962. if (typeof value === 'object' || typeof value === 'function') {
  27963. if (seen.indexOf(value) !== -1) {
  27964. return fold(hash, '[Circular]' + key);
  27965. }
  27966. seen.push(value);
  27967. var objHash = foldObject(hash, value, seen);
  27968. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  27969. return objHash;
  27970. }
  27971. try {
  27972. return fold(objHash, String(value.valueOf()))
  27973. } catch (err) {
  27974. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  27975. }
  27976. }
  27977. return fold(hash, value.toString());
  27978. }
  27979. function toString (o) {
  27980. return Object.prototype.toString.call(o);
  27981. }
  27982. function sum (o) {
  27983. return pad(foldValue(0, o, '', []).toString(16), 8);
  27984. }
  27985. hashSum = sum;
  27986. return hashSum;
  27987. }
  27988. var hashSumExports = /*@__PURE__*/ requireHashSum();
  27989. var hash = /*@__PURE__*/getDefaultExportFromCjs(hashSumExports);
  27990. const CSS_VARS_HELPER = `useCssVars`;
  27991. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  27992. return `{
  27993. ${vars.map(
  27994. (key) => (
  27995. // The `:` prefix here is used in `ssrRenderStyle` to distinguish whether
  27996. // a custom property comes from `ssrCssVars`. If it does, we need to reset
  27997. // its value to `initial` on the component instance to avoid unintentionally
  27998. // inheriting the same property value from a different instance of the same
  27999. // component in the outer scope.
  28000. `"${isSSR ? `:--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  28001. )
  28002. ).join(",\n ")}
  28003. }`;
  28004. }
  28005. function genVarName(id, raw, isProd, isSSR = false) {
  28006. if (isProd) {
  28007. return hash(id + raw).replace(/^\d/, (r) => `v${r}`);
  28008. } else {
  28009. return `${id}-${getEscapedCssVarName(raw, isSSR)}`;
  28010. }
  28011. }
  28012. function normalizeExpression(exp) {
  28013. exp = exp.trim();
  28014. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  28015. return exp.slice(1, -1);
  28016. }
  28017. return exp;
  28018. }
  28019. const vBindRE = /v-bind\s*\(/g;
  28020. function parseCssVars(sfc) {
  28021. const vars = [];
  28022. sfc.styles.forEach((style) => {
  28023. let match;
  28024. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  28025. while (match = vBindRE.exec(content)) {
  28026. const start = match.index + match[0].length;
  28027. const end = lexBinding(content, start);
  28028. if (end !== null) {
  28029. const variable = normalizeExpression(content.slice(start, end));
  28030. if (!vars.includes(variable)) {
  28031. vars.push(variable);
  28032. }
  28033. }
  28034. }
  28035. });
  28036. return vars;
  28037. }
  28038. function lexBinding(content, start) {
  28039. let state = 0 /* inParens */;
  28040. let parenDepth = 0;
  28041. for (let i = start; i < content.length; i++) {
  28042. const char = content.charAt(i);
  28043. switch (state) {
  28044. case 0 /* inParens */:
  28045. if (char === `'`) {
  28046. state = 1 /* inSingleQuoteString */;
  28047. } else if (char === `"`) {
  28048. state = 2 /* inDoubleQuoteString */;
  28049. } else if (char === `(`) {
  28050. parenDepth++;
  28051. } else if (char === `)`) {
  28052. if (parenDepth > 0) {
  28053. parenDepth--;
  28054. } else {
  28055. return i;
  28056. }
  28057. }
  28058. break;
  28059. case 1 /* inSingleQuoteString */:
  28060. if (char === `'`) {
  28061. state = 0 /* inParens */;
  28062. }
  28063. break;
  28064. case 2 /* inDoubleQuoteString */:
  28065. if (char === `"`) {
  28066. state = 0 /* inParens */;
  28067. }
  28068. break;
  28069. }
  28070. }
  28071. return null;
  28072. }
  28073. const cssVarsPlugin = (opts) => {
  28074. const { id, isProd } = opts;
  28075. return {
  28076. postcssPlugin: "vue-sfc-vars",
  28077. Declaration(decl) {
  28078. const value = decl.value;
  28079. if (vBindRE.test(value)) {
  28080. vBindRE.lastIndex = 0;
  28081. let transformed = "";
  28082. let lastIndex = 0;
  28083. let match;
  28084. while (match = vBindRE.exec(value)) {
  28085. const start = match.index + match[0].length;
  28086. const end = lexBinding(value, start);
  28087. if (end !== null) {
  28088. const variable = normalizeExpression(value.slice(start, end));
  28089. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  28090. lastIndex = end + 1;
  28091. }
  28092. }
  28093. decl.value = transformed + value.slice(lastIndex);
  28094. }
  28095. }
  28096. };
  28097. };
  28098. cssVarsPlugin.postcss = true;
  28099. function genCssVarsCode(vars, bindings, id, isProd) {
  28100. const varsExp = genCssVarsFromList(vars, id, isProd);
  28101. const exp = createSimpleExpression(varsExp, false);
  28102. const context = createTransformContext(createRoot([]), {
  28103. prefixIdentifiers: true,
  28104. inline: true,
  28105. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  28106. });
  28107. const transformed = processExpression(exp, context);
  28108. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  28109. return typeof c === "string" ? c : c.content;
  28110. }).join("");
  28111. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  28112. }
  28113. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  28114. return `
  28115. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  28116. const __injectCSSVars__ = () => {
  28117. ${genCssVarsCode(
  28118. cssVars,
  28119. bindings,
  28120. id,
  28121. isProd
  28122. )}}
  28123. const __setup__ = ${defaultVar}.setup
  28124. ${defaultVar}.setup = __setup__
  28125. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  28126. : __injectCSSVars__
  28127. `;
  28128. }
  28129. // shim for using process in browser
  28130. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  28131. function defaultSetTimout() {
  28132. throw new Error('setTimeout has not been defined');
  28133. }
  28134. function defaultClearTimeout () {
  28135. throw new Error('clearTimeout has not been defined');
  28136. }
  28137. var cachedSetTimeout = defaultSetTimout;
  28138. var cachedClearTimeout = defaultClearTimeout;
  28139. if (typeof global$1.setTimeout === 'function') {
  28140. cachedSetTimeout = setTimeout;
  28141. }
  28142. if (typeof global$1.clearTimeout === 'function') {
  28143. cachedClearTimeout = clearTimeout;
  28144. }
  28145. function runTimeout(fun) {
  28146. if (cachedSetTimeout === setTimeout) {
  28147. //normal enviroments in sane situations
  28148. return setTimeout(fun, 0);
  28149. }
  28150. // if setTimeout wasn't available but was latter defined
  28151. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  28152. cachedSetTimeout = setTimeout;
  28153. return setTimeout(fun, 0);
  28154. }
  28155. try {
  28156. // when when somebody has screwed with setTimeout but no I.E. maddness
  28157. return cachedSetTimeout(fun, 0);
  28158. } catch(e){
  28159. try {
  28160. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  28161. return cachedSetTimeout.call(null, fun, 0);
  28162. } catch(e){
  28163. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  28164. return cachedSetTimeout.call(this, fun, 0);
  28165. }
  28166. }
  28167. }
  28168. function runClearTimeout(marker) {
  28169. if (cachedClearTimeout === clearTimeout) {
  28170. //normal enviroments in sane situations
  28171. return clearTimeout(marker);
  28172. }
  28173. // if clearTimeout wasn't available but was latter defined
  28174. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  28175. cachedClearTimeout = clearTimeout;
  28176. return clearTimeout(marker);
  28177. }
  28178. try {
  28179. // when when somebody has screwed with setTimeout but no I.E. maddness
  28180. return cachedClearTimeout(marker);
  28181. } catch (e){
  28182. try {
  28183. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  28184. return cachedClearTimeout.call(null, marker);
  28185. } catch (e){
  28186. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  28187. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  28188. return cachedClearTimeout.call(this, marker);
  28189. }
  28190. }
  28191. }
  28192. var queue = [];
  28193. var draining = false;
  28194. var currentQueue;
  28195. var queueIndex = -1;
  28196. function cleanUpNextTick() {
  28197. if (!draining || !currentQueue) {
  28198. return;
  28199. }
  28200. draining = false;
  28201. if (currentQueue.length) {
  28202. queue = currentQueue.concat(queue);
  28203. } else {
  28204. queueIndex = -1;
  28205. }
  28206. if (queue.length) {
  28207. drainQueue();
  28208. }
  28209. }
  28210. function drainQueue() {
  28211. if (draining) {
  28212. return;
  28213. }
  28214. var timeout = runTimeout(cleanUpNextTick);
  28215. draining = true;
  28216. var len = queue.length;
  28217. while(len) {
  28218. currentQueue = queue;
  28219. queue = [];
  28220. while (++queueIndex < len) {
  28221. if (currentQueue) {
  28222. currentQueue[queueIndex].run();
  28223. }
  28224. }
  28225. queueIndex = -1;
  28226. len = queue.length;
  28227. }
  28228. currentQueue = null;
  28229. draining = false;
  28230. runClearTimeout(timeout);
  28231. }
  28232. function nextTick(fun) {
  28233. var args = new Array(arguments.length - 1);
  28234. if (arguments.length > 1) {
  28235. for (var i = 1; i < arguments.length; i++) {
  28236. args[i - 1] = arguments[i];
  28237. }
  28238. }
  28239. queue.push(new Item(fun, args));
  28240. if (queue.length === 1 && !draining) {
  28241. runTimeout(drainQueue);
  28242. }
  28243. }
  28244. // v8 likes predictible objects
  28245. function Item(fun, array) {
  28246. this.fun = fun;
  28247. this.array = array;
  28248. }
  28249. Item.prototype.run = function () {
  28250. this.fun.apply(null, this.array);
  28251. };
  28252. var title = 'browser';
  28253. var platform = 'browser';
  28254. var browser = true;
  28255. var env = {};
  28256. var argv = [];
  28257. var version$1 = ''; // empty string to avoid regexp issues
  28258. var versions = {};
  28259. var release = {};
  28260. var config = {};
  28261. function noop() {}
  28262. var on = noop;
  28263. var addListener = noop;
  28264. var once = noop;
  28265. var off = noop;
  28266. var removeListener = noop;
  28267. var removeAllListeners = noop;
  28268. var emit = noop;
  28269. function binding(name) {
  28270. throw new Error('process.binding is not supported');
  28271. }
  28272. function cwd () { return '/' }
  28273. function chdir (dir) {
  28274. throw new Error('process.chdir is not supported');
  28275. }function umask() { return 0; }
  28276. // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  28277. var performance = global$1.performance || {};
  28278. var performanceNow =
  28279. performance.now ||
  28280. performance.mozNow ||
  28281. performance.msNow ||
  28282. performance.oNow ||
  28283. performance.webkitNow ||
  28284. function(){ return (new Date()).getTime() };
  28285. // generate timestamp or delta
  28286. // see http://nodejs.org/api/process.html#process_process_hrtime
  28287. function hrtime(previousTimestamp){
  28288. var clocktime = performanceNow.call(performance)*1e-3;
  28289. var seconds = Math.floor(clocktime);
  28290. var nanoseconds = Math.floor((clocktime%1)*1e9);
  28291. if (previousTimestamp) {
  28292. seconds = seconds - previousTimestamp[0];
  28293. nanoseconds = nanoseconds - previousTimestamp[1];
  28294. if (nanoseconds<0) {
  28295. seconds--;
  28296. nanoseconds += 1e9;
  28297. }
  28298. }
  28299. return [seconds,nanoseconds]
  28300. }
  28301. var startTime = new Date();
  28302. function uptime() {
  28303. var currentTime = new Date();
  28304. var dif = currentTime - startTime;
  28305. return dif / 1000;
  28306. }
  28307. var browser$1 = {
  28308. nextTick: nextTick,
  28309. title: title,
  28310. browser: browser,
  28311. env: env,
  28312. argv: argv,
  28313. version: version$1,
  28314. versions: versions,
  28315. on: on,
  28316. addListener: addListener,
  28317. once: once,
  28318. off: off,
  28319. removeListener: removeListener,
  28320. removeAllListeners: removeAllListeners,
  28321. emit: emit,
  28322. binding: binding,
  28323. cwd: cwd,
  28324. chdir: chdir,
  28325. umask: umask,
  28326. hrtime: hrtime,
  28327. platform: platform,
  28328. release: release,
  28329. config: config,
  28330. uptime: uptime
  28331. };
  28332. function createCache(max = 500) {
  28333. {
  28334. return /* @__PURE__ */ new Map();
  28335. }
  28336. }
  28337. function isImportUsed(local, sfc) {
  28338. return resolveTemplateUsedIdentifiers(sfc).has(local);
  28339. }
  28340. const templateAnalysisCache = createCache();
  28341. function resolveTemplateVModelIdentifiers(sfc) {
  28342. return resolveTemplateAnalysisResult(sfc, false).vModelIds;
  28343. }
  28344. function resolveTemplateUsedIdentifiers(sfc) {
  28345. return resolveTemplateAnalysisResult(sfc).usedIds;
  28346. }
  28347. function resolveTemplateAnalysisResult(sfc, collectUsedIds = true) {
  28348. const { content, ast } = sfc.template;
  28349. const cached = templateAnalysisCache.get(content);
  28350. if (cached && (!collectUsedIds || cached.usedIds)) {
  28351. return cached;
  28352. }
  28353. const ids = collectUsedIds ? /* @__PURE__ */ new Set() : void 0;
  28354. const vModelIds = /* @__PURE__ */ new Set();
  28355. ast.children.forEach(walk);
  28356. function walk(node) {
  28357. var _a;
  28358. switch (node.type) {
  28359. case 1:
  28360. let tag = node.tag;
  28361. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  28362. if (!parserOptions.isNativeTag(tag) && !parserOptions.isBuiltInComponent(tag)) {
  28363. if (ids) {
  28364. ids.add(camelize(tag));
  28365. ids.add(capitalize(camelize(tag)));
  28366. }
  28367. }
  28368. for (let i = 0; i < node.props.length; i++) {
  28369. const prop = node.props[i];
  28370. if (prop.type === 7) {
  28371. if (ids) {
  28372. if (!isBuiltInDirective(prop.name)) {
  28373. ids.add(`v${capitalize(camelize(prop.name))}`);
  28374. }
  28375. }
  28376. if (prop.name === "model") {
  28377. const exp = prop.exp;
  28378. if (exp && exp.type === 4) {
  28379. const expString = exp.content.trim();
  28380. if (isSimpleIdentifier(expString) && expString !== "undefined") {
  28381. vModelIds.add(expString);
  28382. }
  28383. }
  28384. }
  28385. if (ids && prop.arg && !prop.arg.isStatic) {
  28386. extractIdentifiers(ids, prop.arg);
  28387. }
  28388. if (ids) {
  28389. if (prop.name === "for") {
  28390. extractIdentifiers(ids, prop.forParseResult.source);
  28391. } else if (prop.exp) {
  28392. extractIdentifiers(ids, prop.exp);
  28393. } else if (prop.name === "bind" && !prop.exp) {
  28394. ids.add(camelize(prop.arg.content));
  28395. }
  28396. }
  28397. }
  28398. if (ids && prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  28399. ids.add(prop.value.content);
  28400. }
  28401. }
  28402. node.children.forEach(walk);
  28403. break;
  28404. case 5:
  28405. if (ids) extractIdentifiers(ids, node.content);
  28406. break;
  28407. }
  28408. }
  28409. const result = { usedIds: ids, vModelIds };
  28410. templateAnalysisCache.set(content, result);
  28411. return result;
  28412. }
  28413. function extractIdentifiers(ids, node) {
  28414. if (node.ast) {
  28415. walkIdentifiers(node.ast, (n) => ids.add(n.name));
  28416. } else if (node.ast === null) {
  28417. ids.add(node.content);
  28418. }
  28419. }
  28420. var __defProp$a = Object.defineProperty;
  28421. var __defProps$9 = Object.defineProperties;
  28422. var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
  28423. var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
  28424. var __hasOwnProp$a = Object.prototype.hasOwnProperty;
  28425. var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
  28426. var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  28427. var __spreadValues$a = (a, b) => {
  28428. for (var prop in b || (b = {}))
  28429. if (__hasOwnProp$a.call(b, prop))
  28430. __defNormalProp$a(a, prop, b[prop]);
  28431. if (__getOwnPropSymbols$a)
  28432. for (var prop of __getOwnPropSymbols$a(b)) {
  28433. if (__propIsEnum$a.call(b, prop))
  28434. __defNormalProp$a(a, prop, b[prop]);
  28435. }
  28436. return a;
  28437. };
  28438. var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
  28439. const DEFAULT_FILENAME = "anonymous.vue";
  28440. const parseCache$1 = createCache();
  28441. function parse$2(source, options = {}) {
  28442. var _a;
  28443. const sourceKey = genCacheKey(source, __spreadProps$9(__spreadValues$a({}, options), {
  28444. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  28445. }));
  28446. const cache = parseCache$1.get(sourceKey);
  28447. if (cache) {
  28448. return cache;
  28449. }
  28450. const {
  28451. sourceMap = true,
  28452. filename = DEFAULT_FILENAME,
  28453. sourceRoot = "",
  28454. pad = false,
  28455. ignoreEmpty = true,
  28456. compiler = CompilerDOM,
  28457. templateParseOptions = {}
  28458. } = options;
  28459. const descriptor = {
  28460. filename,
  28461. source,
  28462. template: null,
  28463. script: null,
  28464. scriptSetup: null,
  28465. styles: [],
  28466. customBlocks: [],
  28467. cssVars: [],
  28468. slotted: false,
  28469. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  28470. };
  28471. const errors = [];
  28472. const ast = compiler.parse(source, __spreadProps$9(__spreadValues$a({
  28473. parseMode: "sfc",
  28474. prefixIdentifiers: true
  28475. }, templateParseOptions), {
  28476. onError: (e) => {
  28477. errors.push(e);
  28478. }
  28479. }));
  28480. ast.children.forEach((node) => {
  28481. if (node.type !== 1) {
  28482. return;
  28483. }
  28484. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  28485. return;
  28486. }
  28487. switch (node.tag) {
  28488. case "template":
  28489. if (!descriptor.template) {
  28490. const templateBlock = descriptor.template = createBlock(
  28491. node,
  28492. source,
  28493. false
  28494. );
  28495. if (!templateBlock.attrs.src) {
  28496. templateBlock.ast = createRoot(node.children, source);
  28497. }
  28498. if (templateBlock.attrs.functional) {
  28499. const err = new SyntaxError(
  28500. `<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.`
  28501. );
  28502. err.loc = node.props.find(
  28503. (p) => p.type === 6 && p.name === "functional"
  28504. ).loc;
  28505. errors.push(err);
  28506. }
  28507. } else {
  28508. errors.push(createDuplicateBlockError(node));
  28509. }
  28510. break;
  28511. case "script":
  28512. const scriptBlock = createBlock(node, source, pad);
  28513. const isSetup = !!scriptBlock.attrs.setup;
  28514. if (isSetup && !descriptor.scriptSetup) {
  28515. descriptor.scriptSetup = scriptBlock;
  28516. break;
  28517. }
  28518. if (!isSetup && !descriptor.script) {
  28519. descriptor.script = scriptBlock;
  28520. break;
  28521. }
  28522. errors.push(createDuplicateBlockError(node, isSetup));
  28523. break;
  28524. case "style":
  28525. const styleBlock = createBlock(node, source, pad);
  28526. if (styleBlock.attrs.vars) {
  28527. errors.push(
  28528. new SyntaxError(
  28529. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  28530. )
  28531. );
  28532. }
  28533. descriptor.styles.push(styleBlock);
  28534. break;
  28535. default:
  28536. descriptor.customBlocks.push(createBlock(node, source, pad));
  28537. break;
  28538. }
  28539. });
  28540. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  28541. errors.push(
  28542. new SyntaxError(
  28543. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  28544. )
  28545. );
  28546. }
  28547. if (descriptor.scriptSetup) {
  28548. if (descriptor.scriptSetup.src) {
  28549. errors.push(
  28550. new SyntaxError(
  28551. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  28552. )
  28553. );
  28554. descriptor.scriptSetup = null;
  28555. }
  28556. if (descriptor.script && descriptor.script.src) {
  28557. errors.push(
  28558. new SyntaxError(
  28559. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  28560. )
  28561. );
  28562. descriptor.script = null;
  28563. }
  28564. }
  28565. let templateColumnOffset = 0;
  28566. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  28567. [descriptor.template.content, templateColumnOffset] = dedent(
  28568. descriptor.template.content
  28569. );
  28570. }
  28571. if (sourceMap) {
  28572. const genMap = (block, columnOffset = 0) => {
  28573. if (block && !block.src) {
  28574. block.map = generateSourceMap(
  28575. filename,
  28576. source,
  28577. block.content,
  28578. sourceRoot,
  28579. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  28580. columnOffset
  28581. );
  28582. }
  28583. };
  28584. genMap(descriptor.template, templateColumnOffset);
  28585. genMap(descriptor.script);
  28586. descriptor.styles.forEach((s) => genMap(s));
  28587. descriptor.customBlocks.forEach((s) => genMap(s));
  28588. }
  28589. descriptor.cssVars = parseCssVars(descriptor);
  28590. const slottedRE = /(?:::v-|:)slotted\(/;
  28591. descriptor.slotted = descriptor.styles.some(
  28592. (s) => s.scoped && slottedRE.test(s.content)
  28593. );
  28594. const result = {
  28595. descriptor,
  28596. errors
  28597. };
  28598. parseCache$1.set(sourceKey, result);
  28599. return result;
  28600. }
  28601. function createDuplicateBlockError(node, isScriptSetup = false) {
  28602. const err = new SyntaxError(
  28603. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  28604. );
  28605. err.loc = node.loc;
  28606. return err;
  28607. }
  28608. function createBlock(node, source, pad) {
  28609. const type = node.tag;
  28610. const loc = node.innerLoc;
  28611. const attrs = {};
  28612. const block = {
  28613. type,
  28614. content: source.slice(loc.start.offset, loc.end.offset),
  28615. loc,
  28616. attrs
  28617. };
  28618. if (pad) {
  28619. block.content = padContent(source, block, pad) + block.content;
  28620. }
  28621. node.props.forEach((p) => {
  28622. if (p.type === 6) {
  28623. const name = p.name;
  28624. attrs[name] = p.value ? p.value.content || true : true;
  28625. if (name === "lang") {
  28626. block.lang = p.value && p.value.content;
  28627. } else if (name === "src") {
  28628. block.src = p.value && p.value.content;
  28629. } else if (type === "style") {
  28630. if (name === "scoped") {
  28631. block.scoped = true;
  28632. } else if (name === "module") {
  28633. block.module = attrs[name];
  28634. }
  28635. } else if (type === "script" && name === "setup") {
  28636. block.setup = attrs.setup;
  28637. }
  28638. }
  28639. });
  28640. return block;
  28641. }
  28642. const splitRE = /\r?\n/g;
  28643. const emptyRE = /^(?:\/\/)?\s*$/;
  28644. const replaceRE = /./g;
  28645. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  28646. const map = new sourceMapExports.SourceMapGenerator({
  28647. file: filename.replace(/\\/g, "/"),
  28648. sourceRoot: sourceRoot.replace(/\\/g, "/")
  28649. });
  28650. map.setSourceContent(filename, source);
  28651. map._sources.add(filename);
  28652. generated.split(splitRE).forEach((line, index) => {
  28653. if (!emptyRE.test(line)) {
  28654. const originalLine = index + 1 + lineOffset;
  28655. const generatedLine = index + 1;
  28656. for (let i = 0; i < line.length; i++) {
  28657. if (!/\s/.test(line[i])) {
  28658. map._mappings.add({
  28659. originalLine,
  28660. originalColumn: i + columnOffset,
  28661. generatedLine,
  28662. generatedColumn: i,
  28663. source: filename,
  28664. name: null
  28665. });
  28666. }
  28667. }
  28668. }
  28669. });
  28670. return map.toJSON();
  28671. }
  28672. function padContent(content, block, pad) {
  28673. content = content.slice(0, block.loc.start.offset);
  28674. if (pad === "space") {
  28675. return content.replace(replaceRE, " ");
  28676. } else {
  28677. const offset = content.split(splitRE).length;
  28678. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  28679. return Array(offset).join(padChar);
  28680. }
  28681. }
  28682. function hasSrc(node) {
  28683. return node.props.some((p) => {
  28684. if (p.type !== 6) {
  28685. return false;
  28686. }
  28687. return p.name === "src";
  28688. });
  28689. }
  28690. function isEmpty(node) {
  28691. for (let i = 0; i < node.children.length; i++) {
  28692. const child = node.children[i];
  28693. if (child.type !== 2 || child.content.trim() !== "") {
  28694. return false;
  28695. }
  28696. }
  28697. return true;
  28698. }
  28699. function hmrShouldReload(prevImports, next) {
  28700. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  28701. return false;
  28702. }
  28703. for (const key in prevImports) {
  28704. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  28705. return true;
  28706. }
  28707. }
  28708. return false;
  28709. }
  28710. function dedent(s) {
  28711. const lines = s.split("\n");
  28712. const minIndent = lines.reduce(function(minIndent2, line) {
  28713. var _a, _b;
  28714. if (line.trim() === "") {
  28715. return minIndent2;
  28716. }
  28717. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  28718. return Math.min(indent, minIndent2);
  28719. }, Infinity);
  28720. if (minIndent === 0) {
  28721. return [s, minIndent];
  28722. }
  28723. return [
  28724. lines.map(function(line) {
  28725. return line.slice(minIndent);
  28726. }).join("\n"),
  28727. minIndent
  28728. ];
  28729. }
  28730. // Copyright Joyent, Inc. and other Node contributors.
  28731. //
  28732. // Permission is hereby granted, free of charge, to any person obtaining a
  28733. // copy of this software and associated documentation files (the
  28734. // "Software"), to deal in the Software without restriction, including
  28735. // without limitation the rights to use, copy, modify, merge, publish,
  28736. // distribute, sublicense, and/or sell copies of the Software, and to permit
  28737. // persons to whom the Software is furnished to do so, subject to the
  28738. // following conditions:
  28739. //
  28740. // The above copyright notice and this permission notice shall be included
  28741. // in all copies or substantial portions of the Software.
  28742. //
  28743. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  28744. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28745. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  28746. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  28747. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  28748. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  28749. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  28750. // resolves . and .. elements in a path array with directory names there
  28751. // must be no slashes, empty elements, or device names (c:\) in the array
  28752. // (so also no leading and trailing slashes - it does not distinguish
  28753. // relative and absolute paths)
  28754. function normalizeArray(parts, allowAboveRoot) {
  28755. // if the path tries to go above the root, `up` ends up > 0
  28756. var up = 0;
  28757. for (var i = parts.length - 1; i >= 0; i--) {
  28758. var last = parts[i];
  28759. if (last === '.') {
  28760. parts.splice(i, 1);
  28761. } else if (last === '..') {
  28762. parts.splice(i, 1);
  28763. up++;
  28764. } else if (up) {
  28765. parts.splice(i, 1);
  28766. up--;
  28767. }
  28768. }
  28769. // if the path is allowed to go above the root, restore leading ..s
  28770. if (allowAboveRoot) {
  28771. for (; up--; up) {
  28772. parts.unshift('..');
  28773. }
  28774. }
  28775. return parts;
  28776. }
  28777. // Split a filename into [root, dir, basename, ext], unix version
  28778. // 'root' is just a slash, or nothing.
  28779. var splitPathRe =
  28780. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  28781. var splitPath = function(filename) {
  28782. return splitPathRe.exec(filename).slice(1);
  28783. };
  28784. // path.resolve([from ...], to)
  28785. // posix version
  28786. function resolve() {
  28787. var resolvedPath = '',
  28788. resolvedAbsolute = false;
  28789. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  28790. var path = (i >= 0) ? arguments[i] : '/';
  28791. // Skip empty and invalid entries
  28792. if (typeof path !== 'string') {
  28793. throw new TypeError('Arguments to path.resolve must be strings');
  28794. } else if (!path) {
  28795. continue;
  28796. }
  28797. resolvedPath = path + '/' + resolvedPath;
  28798. resolvedAbsolute = path.charAt(0) === '/';
  28799. }
  28800. // At this point the path should be resolved to a full absolute path, but
  28801. // handle relative paths to be safe (might happen when process.cwd() fails)
  28802. // Normalize the path
  28803. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  28804. return !!p;
  28805. }), !resolvedAbsolute).join('/');
  28806. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  28807. }
  28808. // path.normalize(path)
  28809. // posix version
  28810. function normalize$1(path) {
  28811. var isPathAbsolute = isAbsolute(path),
  28812. trailingSlash = substr(path, -1) === '/';
  28813. // Normalize the path
  28814. path = normalizeArray(filter(path.split('/'), function(p) {
  28815. return !!p;
  28816. }), !isPathAbsolute).join('/');
  28817. if (!path && !isPathAbsolute) {
  28818. path = '.';
  28819. }
  28820. if (path && trailingSlash) {
  28821. path += '/';
  28822. }
  28823. return (isPathAbsolute ? '/' : '') + path;
  28824. }
  28825. // posix version
  28826. function isAbsolute(path) {
  28827. return path.charAt(0) === '/';
  28828. }
  28829. // posix version
  28830. function join() {
  28831. var paths = Array.prototype.slice.call(arguments, 0);
  28832. return normalize$1(filter(paths, function(p, index) {
  28833. if (typeof p !== 'string') {
  28834. throw new TypeError('Arguments to path.join must be strings');
  28835. }
  28836. return p;
  28837. }).join('/'));
  28838. }
  28839. // path.relative(from, to)
  28840. // posix version
  28841. function relative(from, to) {
  28842. from = resolve(from).substr(1);
  28843. to = resolve(to).substr(1);
  28844. function trim(arr) {
  28845. var start = 0;
  28846. for (; start < arr.length; start++) {
  28847. if (arr[start] !== '') break;
  28848. }
  28849. var end = arr.length - 1;
  28850. for (; end >= 0; end--) {
  28851. if (arr[end] !== '') break;
  28852. }
  28853. if (start > end) return [];
  28854. return arr.slice(start, end - start + 1);
  28855. }
  28856. var fromParts = trim(from.split('/'));
  28857. var toParts = trim(to.split('/'));
  28858. var length = Math.min(fromParts.length, toParts.length);
  28859. var samePartsLength = length;
  28860. for (var i = 0; i < length; i++) {
  28861. if (fromParts[i] !== toParts[i]) {
  28862. samePartsLength = i;
  28863. break;
  28864. }
  28865. }
  28866. var outputParts = [];
  28867. for (var i = samePartsLength; i < fromParts.length; i++) {
  28868. outputParts.push('..');
  28869. }
  28870. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  28871. return outputParts.join('/');
  28872. }
  28873. var sep = '/';
  28874. var delimiter$1 = ':';
  28875. function dirname(path) {
  28876. var result = splitPath(path),
  28877. root = result[0],
  28878. dir = result[1];
  28879. if (!root && !dir) {
  28880. // No dirname whatsoever
  28881. return '.';
  28882. }
  28883. if (dir) {
  28884. // It has a dirname, strip trailing slash
  28885. dir = dir.substr(0, dir.length - 1);
  28886. }
  28887. return root + dir;
  28888. }
  28889. function basename(path, ext) {
  28890. var f = splitPath(path)[2];
  28891. // TODO: make this comparison case-insensitive on windows?
  28892. if (ext && f.substr(-1 * ext.length) === ext) {
  28893. f = f.substr(0, f.length - ext.length);
  28894. }
  28895. return f;
  28896. }
  28897. function extname(path) {
  28898. return splitPath(path)[3];
  28899. }
  28900. var path = {
  28901. extname: extname,
  28902. basename: basename,
  28903. dirname: dirname,
  28904. sep: sep,
  28905. delimiter: delimiter$1,
  28906. relative: relative,
  28907. join: join,
  28908. isAbsolute: isAbsolute,
  28909. normalize: normalize$1,
  28910. resolve: resolve
  28911. };
  28912. function filter (xs, f) {
  28913. if (xs.filter) return xs.filter(f);
  28914. var res = [];
  28915. for (var i = 0; i < xs.length; i++) {
  28916. if (f(xs[i], i, xs)) res.push(xs[i]);
  28917. }
  28918. return res;
  28919. }
  28920. // String.prototype.substr - negative index don't work in IE8
  28921. var substr = 'ab'.substr(-1) === 'b' ?
  28922. function (str, start, len) { return str.substr(start, len) } :
  28923. function (str, start, len) {
  28924. if (start < 0) start = str.length + start;
  28925. return str.substr(start, len);
  28926. }
  28927. ;
  28928. var _polyfillNode_path = /*#__PURE__*/Object.freeze({
  28929. __proto__: null,
  28930. basename: basename,
  28931. default: path,
  28932. delimiter: delimiter$1,
  28933. dirname: dirname,
  28934. extname: extname,
  28935. isAbsolute: isAbsolute,
  28936. join: join,
  28937. normalize: normalize$1,
  28938. relative: relative,
  28939. resolve: resolve,
  28940. sep: sep
  28941. });
  28942. /*! https://mths.be/punycode v1.4.1 by @mathias */
  28943. /** Highest positive signed 32-bit float value */
  28944. var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  28945. /** Bootstring parameters */
  28946. var base = 36;
  28947. var tMin = 1;
  28948. var tMax = 26;
  28949. var skew = 38;
  28950. var damp = 700;
  28951. var initialBias = 72;
  28952. var initialN = 128; // 0x80
  28953. var delimiter = '-'; // '\x2D'
  28954. var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
  28955. var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  28956. /** Error messages */
  28957. var errors = {
  28958. 'overflow': 'Overflow: input needs wider integers to process',
  28959. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  28960. 'invalid-input': 'Invalid input'
  28961. };
  28962. /** Convenience shortcuts */
  28963. var baseMinusTMin = base - tMin;
  28964. var floor = Math.floor;
  28965. var stringFromCharCode = String.fromCharCode;
  28966. /*--------------------------------------------------------------------------*/
  28967. /**
  28968. * A generic error utility function.
  28969. * @private
  28970. * @param {String} type The error type.
  28971. * @returns {Error} Throws a `RangeError` with the applicable error message.
  28972. */
  28973. function error(type) {
  28974. throw new RangeError(errors[type]);
  28975. }
  28976. /**
  28977. * A generic `Array#map` utility function.
  28978. * @private
  28979. * @param {Array} array The array to iterate over.
  28980. * @param {Function} callback The function that gets called for every array
  28981. * item.
  28982. * @returns {Array} A new array of values returned by the callback function.
  28983. */
  28984. function map$1(array, fn) {
  28985. var length = array.length;
  28986. var result = [];
  28987. while (length--) {
  28988. result[length] = fn(array[length]);
  28989. }
  28990. return result;
  28991. }
  28992. /**
  28993. * A simple `Array#map`-like wrapper to work with domain name strings or email
  28994. * addresses.
  28995. * @private
  28996. * @param {String} domain The domain name or email address.
  28997. * @param {Function} callback The function that gets called for every
  28998. * character.
  28999. * @returns {Array} A new string of characters returned by the callback
  29000. * function.
  29001. */
  29002. function mapDomain(string, fn) {
  29003. var parts = string.split('@');
  29004. var result = '';
  29005. if (parts.length > 1) {
  29006. // In email addresses, only the domain name should be punycoded. Leave
  29007. // the local part (i.e. everything up to `@`) intact.
  29008. result = parts[0] + '@';
  29009. string = parts[1];
  29010. }
  29011. // Avoid `split(regex)` for IE8 compatibility. See #17.
  29012. string = string.replace(regexSeparators, '\x2E');
  29013. var labels = string.split('.');
  29014. var encoded = map$1(labels, fn).join('.');
  29015. return result + encoded;
  29016. }
  29017. /**
  29018. * Creates an array containing the numeric code points of each Unicode
  29019. * character in the string. While JavaScript uses UCS-2 internally,
  29020. * this function will convert a pair of surrogate halves (each of which
  29021. * UCS-2 exposes as separate characters) into a single code point,
  29022. * matching UTF-16.
  29023. * @see `punycode.ucs2.encode`
  29024. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  29025. * @memberOf punycode.ucs2
  29026. * @name decode
  29027. * @param {String} string The Unicode input string (UCS-2).
  29028. * @returns {Array} The new array of code points.
  29029. */
  29030. function ucs2decode(string) {
  29031. var output = [],
  29032. counter = 0,
  29033. length = string.length,
  29034. value,
  29035. extra;
  29036. while (counter < length) {
  29037. value = string.charCodeAt(counter++);
  29038. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  29039. // high surrogate, and there is a next character
  29040. extra = string.charCodeAt(counter++);
  29041. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  29042. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  29043. } else {
  29044. // unmatched surrogate; only append this code unit, in case the next
  29045. // code unit is the high surrogate of a surrogate pair
  29046. output.push(value);
  29047. counter--;
  29048. }
  29049. } else {
  29050. output.push(value);
  29051. }
  29052. }
  29053. return output;
  29054. }
  29055. /**
  29056. * Converts a digit/integer into a basic code point.
  29057. * @see `basicToDigit()`
  29058. * @private
  29059. * @param {Number} digit The numeric value of a basic code point.
  29060. * @returns {Number} The basic code point whose value (when used for
  29061. * representing integers) is `digit`, which needs to be in the range
  29062. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  29063. * used; else, the lowercase form is used. The behavior is undefined
  29064. * if `flag` is non-zero and `digit` has no uppercase form.
  29065. */
  29066. function digitToBasic(digit, flag) {
  29067. // 0..25 map to ASCII a..z or A..Z
  29068. // 26..35 map to ASCII 0..9
  29069. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  29070. }
  29071. /**
  29072. * Bias adaptation function as per section 3.4 of RFC 3492.
  29073. * https://tools.ietf.org/html/rfc3492#section-3.4
  29074. * @private
  29075. */
  29076. function adapt(delta, numPoints, firstTime) {
  29077. var k = 0;
  29078. delta = firstTime ? floor(delta / damp) : delta >> 1;
  29079. delta += floor(delta / numPoints);
  29080. for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
  29081. delta = floor(delta / baseMinusTMin);
  29082. }
  29083. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  29084. }
  29085. /**
  29086. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  29087. * Punycode string of ASCII-only symbols.
  29088. * @memberOf punycode
  29089. * @param {String} input The string of Unicode symbols.
  29090. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  29091. */
  29092. function encode$1(input) {
  29093. var n,
  29094. delta,
  29095. handledCPCount,
  29096. basicLength,
  29097. bias,
  29098. j,
  29099. m,
  29100. q,
  29101. k,
  29102. t,
  29103. currentValue,
  29104. output = [],
  29105. /** `inputLength` will hold the number of code points in `input`. */
  29106. inputLength,
  29107. /** Cached calculation results */
  29108. handledCPCountPlusOne,
  29109. baseMinusT,
  29110. qMinusT;
  29111. // Convert the input in UCS-2 to Unicode
  29112. input = ucs2decode(input);
  29113. // Cache the length
  29114. inputLength = input.length;
  29115. // Initialize the state
  29116. n = initialN;
  29117. delta = 0;
  29118. bias = initialBias;
  29119. // Handle the basic code points
  29120. for (j = 0; j < inputLength; ++j) {
  29121. currentValue = input[j];
  29122. if (currentValue < 0x80) {
  29123. output.push(stringFromCharCode(currentValue));
  29124. }
  29125. }
  29126. handledCPCount = basicLength = output.length;
  29127. // `handledCPCount` is the number of code points that have been handled;
  29128. // `basicLength` is the number of basic code points.
  29129. // Finish the basic string - if it is not empty - with a delimiter
  29130. if (basicLength) {
  29131. output.push(delimiter);
  29132. }
  29133. // Main encoding loop:
  29134. while (handledCPCount < inputLength) {
  29135. // All non-basic code points < n have been handled already. Find the next
  29136. // larger one:
  29137. for (m = maxInt, j = 0; j < inputLength; ++j) {
  29138. currentValue = input[j];
  29139. if (currentValue >= n && currentValue < m) {
  29140. m = currentValue;
  29141. }
  29142. }
  29143. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  29144. // but guard against overflow
  29145. handledCPCountPlusOne = handledCPCount + 1;
  29146. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  29147. error('overflow');
  29148. }
  29149. delta += (m - n) * handledCPCountPlusOne;
  29150. n = m;
  29151. for (j = 0; j < inputLength; ++j) {
  29152. currentValue = input[j];
  29153. if (currentValue < n && ++delta > maxInt) {
  29154. error('overflow');
  29155. }
  29156. if (currentValue == n) {
  29157. // Represent delta as a generalized variable-length integer
  29158. for (q = delta, k = base; /* no condition */ ; k += base) {
  29159. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  29160. if (q < t) {
  29161. break;
  29162. }
  29163. qMinusT = q - t;
  29164. baseMinusT = base - t;
  29165. output.push(
  29166. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  29167. );
  29168. q = floor(qMinusT / baseMinusT);
  29169. }
  29170. output.push(stringFromCharCode(digitToBasic(q, 0)));
  29171. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  29172. delta = 0;
  29173. ++handledCPCount;
  29174. }
  29175. }
  29176. ++delta;
  29177. ++n;
  29178. }
  29179. return output.join('');
  29180. }
  29181. /**
  29182. * Converts a Unicode string representing a domain name or an email address to
  29183. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  29184. * i.e. it doesn't matter if you call it with a domain that's already in
  29185. * ASCII.
  29186. * @memberOf punycode
  29187. * @param {String} input The domain name or email address to convert, as a
  29188. * Unicode string.
  29189. * @returns {String} The Punycode representation of the given domain name or
  29190. * email address.
  29191. */
  29192. function toASCII(input) {
  29193. return mapDomain(input, function(string) {
  29194. return regexNonASCII.test(string) ?
  29195. 'xn--' + encode$1(string) :
  29196. string;
  29197. });
  29198. }
  29199. var inherits;
  29200. if (typeof Object.create === 'function'){
  29201. inherits = function inherits(ctor, superCtor) {
  29202. // implementation from standard node.js 'util' module
  29203. ctor.super_ = superCtor;
  29204. ctor.prototype = Object.create(superCtor.prototype, {
  29205. constructor: {
  29206. value: ctor,
  29207. enumerable: false,
  29208. writable: true,
  29209. configurable: true
  29210. }
  29211. });
  29212. };
  29213. } else {
  29214. inherits = function inherits(ctor, superCtor) {
  29215. ctor.super_ = superCtor;
  29216. var TempCtor = function () {};
  29217. TempCtor.prototype = superCtor.prototype;
  29218. ctor.prototype = new TempCtor();
  29219. ctor.prototype.constructor = ctor;
  29220. };
  29221. }
  29222. var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
  29223. function getOwnPropertyDescriptors(obj) {
  29224. var keys = Object.keys(obj);
  29225. var descriptors = {};
  29226. for (var i = 0; i < keys.length; i++) {
  29227. descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
  29228. }
  29229. return descriptors;
  29230. };
  29231. var formatRegExp = /%[sdj%]/g;
  29232. function format$1(f) {
  29233. if (!isString(f)) {
  29234. var objects = [];
  29235. for (var i = 0; i < arguments.length; i++) {
  29236. objects.push(inspect(arguments[i]));
  29237. }
  29238. return objects.join(' ');
  29239. }
  29240. var i = 1;
  29241. var args = arguments;
  29242. var len = args.length;
  29243. var str = String(f).replace(formatRegExp, function(x) {
  29244. if (x === '%%') return '%';
  29245. if (i >= len) return x;
  29246. switch (x) {
  29247. case '%s': return String(args[i++]);
  29248. case '%d': return Number(args[i++]);
  29249. case '%j':
  29250. try {
  29251. return JSON.stringify(args[i++]);
  29252. } catch (_) {
  29253. return '[Circular]';
  29254. }
  29255. default:
  29256. return x;
  29257. }
  29258. });
  29259. for (var x = args[i]; i < len; x = args[++i]) {
  29260. if (isNull(x) || !isObject$1(x)) {
  29261. str += ' ' + x;
  29262. } else {
  29263. str += ' ' + inspect(x);
  29264. }
  29265. }
  29266. return str;
  29267. }
  29268. // Mark that a method should not be used.
  29269. // Returns a modified function which warns once by default.
  29270. // If --no-deprecation is set, then it is a no-op.
  29271. function deprecate(fn, msg) {
  29272. // Allow for deprecating things in the process of starting up.
  29273. if (isUndefined(global$1.process)) {
  29274. return function() {
  29275. return deprecate(fn, msg).apply(this, arguments);
  29276. };
  29277. }
  29278. if (browser$1.noDeprecation === true) {
  29279. return fn;
  29280. }
  29281. var warned = false;
  29282. function deprecated() {
  29283. if (!warned) {
  29284. if (browser$1.throwDeprecation) {
  29285. throw new Error(msg);
  29286. } else if (browser$1.traceDeprecation) {
  29287. console.trace(msg);
  29288. } else {
  29289. console.error(msg);
  29290. }
  29291. warned = true;
  29292. }
  29293. return fn.apply(this, arguments);
  29294. }
  29295. return deprecated;
  29296. }
  29297. var debugs = {};
  29298. var debugEnviron;
  29299. function debuglog(set) {
  29300. if (isUndefined(debugEnviron))
  29301. debugEnviron = browser$1.env.NODE_DEBUG || '';
  29302. set = set.toUpperCase();
  29303. if (!debugs[set]) {
  29304. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  29305. var pid = 0;
  29306. debugs[set] = function() {
  29307. var msg = format$1.apply(null, arguments);
  29308. console.error('%s %d: %s', set, pid, msg);
  29309. };
  29310. } else {
  29311. debugs[set] = function() {};
  29312. }
  29313. }
  29314. return debugs[set];
  29315. }
  29316. /**
  29317. * Echos the value of a value. Trys to print the value out
  29318. * in the best way possible given the different types.
  29319. *
  29320. * @param {Object} obj The object to print out.
  29321. * @param {Object} opts Optional options object that alters the output.
  29322. */
  29323. /* legacy: obj, showHidden, depth, colors*/
  29324. function inspect(obj, opts) {
  29325. // default options
  29326. var ctx = {
  29327. seen: [],
  29328. stylize: stylizeNoColor
  29329. };
  29330. // legacy...
  29331. if (arguments.length >= 3) ctx.depth = arguments[2];
  29332. if (arguments.length >= 4) ctx.colors = arguments[3];
  29333. if (isBoolean(opts)) {
  29334. // legacy...
  29335. ctx.showHidden = opts;
  29336. } else if (opts) {
  29337. // got an "options" object
  29338. _extend(ctx, opts);
  29339. }
  29340. // set default options
  29341. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  29342. if (isUndefined(ctx.depth)) ctx.depth = 2;
  29343. if (isUndefined(ctx.colors)) ctx.colors = false;
  29344. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  29345. if (ctx.colors) ctx.stylize = stylizeWithColor;
  29346. return formatValue(ctx, obj, ctx.depth);
  29347. }
  29348. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  29349. inspect.colors = {
  29350. 'bold' : [1, 22],
  29351. 'italic' : [3, 23],
  29352. 'underline' : [4, 24],
  29353. 'inverse' : [7, 27],
  29354. 'white' : [37, 39],
  29355. 'grey' : [90, 39],
  29356. 'black' : [30, 39],
  29357. 'blue' : [34, 39],
  29358. 'cyan' : [36, 39],
  29359. 'green' : [32, 39],
  29360. 'magenta' : [35, 39],
  29361. 'red' : [31, 39],
  29362. 'yellow' : [33, 39]
  29363. };
  29364. // Don't use 'blue' not visible on cmd.exe
  29365. inspect.styles = {
  29366. 'special': 'cyan',
  29367. 'number': 'yellow',
  29368. 'boolean': 'yellow',
  29369. 'undefined': 'grey',
  29370. 'null': 'bold',
  29371. 'string': 'green',
  29372. 'date': 'magenta',
  29373. // "name": intentionally not styling
  29374. 'regexp': 'red'
  29375. };
  29376. function stylizeWithColor(str, styleType) {
  29377. var style = inspect.styles[styleType];
  29378. if (style) {
  29379. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  29380. '\u001b[' + inspect.colors[style][1] + 'm';
  29381. } else {
  29382. return str;
  29383. }
  29384. }
  29385. function stylizeNoColor(str, styleType) {
  29386. return str;
  29387. }
  29388. function arrayToHash(array) {
  29389. var hash = {};
  29390. array.forEach(function(val, idx) {
  29391. hash[val] = true;
  29392. });
  29393. return hash;
  29394. }
  29395. function formatValue(ctx, value, recurseTimes) {
  29396. // Provide a hook for user-specified inspect functions.
  29397. // Check that value is an object with an inspect function on it
  29398. if (ctx.customInspect &&
  29399. value &&
  29400. isFunction(value.inspect) &&
  29401. // Filter out the util module, it's inspect function is special
  29402. value.inspect !== inspect &&
  29403. // Also filter out any prototype objects using the circular check.
  29404. !(value.constructor && value.constructor.prototype === value)) {
  29405. var ret = value.inspect(recurseTimes, ctx);
  29406. if (!isString(ret)) {
  29407. ret = formatValue(ctx, ret, recurseTimes);
  29408. }
  29409. return ret;
  29410. }
  29411. // Primitive types cannot have properties
  29412. var primitive = formatPrimitive(ctx, value);
  29413. if (primitive) {
  29414. return primitive;
  29415. }
  29416. // Look up the keys of the object.
  29417. var keys = Object.keys(value);
  29418. var visibleKeys = arrayToHash(keys);
  29419. if (ctx.showHidden) {
  29420. keys = Object.getOwnPropertyNames(value);
  29421. }
  29422. // IE doesn't make error fields non-enumerable
  29423. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  29424. if (isError(value)
  29425. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  29426. return formatError(value);
  29427. }
  29428. // Some type of object without properties can be shortcutted.
  29429. if (keys.length === 0) {
  29430. if (isFunction(value)) {
  29431. var name = value.name ? ': ' + value.name : '';
  29432. return ctx.stylize('[Function' + name + ']', 'special');
  29433. }
  29434. if (isRegExp(value)) {
  29435. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  29436. }
  29437. if (isDate(value)) {
  29438. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  29439. }
  29440. if (isError(value)) {
  29441. return formatError(value);
  29442. }
  29443. }
  29444. var base = '', array = false, braces = ['{', '}'];
  29445. // Make Array say that they are Array
  29446. if (isArray$1(value)) {
  29447. array = true;
  29448. braces = ['[', ']'];
  29449. }
  29450. // Make functions say that they are functions
  29451. if (isFunction(value)) {
  29452. var n = value.name ? ': ' + value.name : '';
  29453. base = ' [Function' + n + ']';
  29454. }
  29455. // Make RegExps say that they are RegExps
  29456. if (isRegExp(value)) {
  29457. base = ' ' + RegExp.prototype.toString.call(value);
  29458. }
  29459. // Make dates with properties first say the date
  29460. if (isDate(value)) {
  29461. base = ' ' + Date.prototype.toUTCString.call(value);
  29462. }
  29463. // Make error with message first say the error
  29464. if (isError(value)) {
  29465. base = ' ' + formatError(value);
  29466. }
  29467. if (keys.length === 0 && (!array || value.length == 0)) {
  29468. return braces[0] + base + braces[1];
  29469. }
  29470. if (recurseTimes < 0) {
  29471. if (isRegExp(value)) {
  29472. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  29473. } else {
  29474. return ctx.stylize('[Object]', 'special');
  29475. }
  29476. }
  29477. ctx.seen.push(value);
  29478. var output;
  29479. if (array) {
  29480. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  29481. } else {
  29482. output = keys.map(function(key) {
  29483. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  29484. });
  29485. }
  29486. ctx.seen.pop();
  29487. return reduceToSingleString(output, base, braces);
  29488. }
  29489. function formatPrimitive(ctx, value) {
  29490. if (isUndefined(value))
  29491. return ctx.stylize('undefined', 'undefined');
  29492. if (isString(value)) {
  29493. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  29494. .replace(/'/g, "\\'")
  29495. .replace(/\\"/g, '"') + '\'';
  29496. return ctx.stylize(simple, 'string');
  29497. }
  29498. if (isNumber(value))
  29499. return ctx.stylize('' + value, 'number');
  29500. if (isBoolean(value))
  29501. return ctx.stylize('' + value, 'boolean');
  29502. // For some reason typeof null is "object", so special case here.
  29503. if (isNull(value))
  29504. return ctx.stylize('null', 'null');
  29505. }
  29506. function formatError(value) {
  29507. return '[' + Error.prototype.toString.call(value) + ']';
  29508. }
  29509. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  29510. var output = [];
  29511. for (var i = 0, l = value.length; i < l; ++i) {
  29512. if (hasOwnProperty$2(value, String(i))) {
  29513. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  29514. String(i), true));
  29515. } else {
  29516. output.push('');
  29517. }
  29518. }
  29519. keys.forEach(function(key) {
  29520. if (!key.match(/^\d+$/)) {
  29521. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  29522. key, true));
  29523. }
  29524. });
  29525. return output;
  29526. }
  29527. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  29528. var name, str, desc;
  29529. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  29530. if (desc.get) {
  29531. if (desc.set) {
  29532. str = ctx.stylize('[Getter/Setter]', 'special');
  29533. } else {
  29534. str = ctx.stylize('[Getter]', 'special');
  29535. }
  29536. } else {
  29537. if (desc.set) {
  29538. str = ctx.stylize('[Setter]', 'special');
  29539. }
  29540. }
  29541. if (!hasOwnProperty$2(visibleKeys, key)) {
  29542. name = '[' + key + ']';
  29543. }
  29544. if (!str) {
  29545. if (ctx.seen.indexOf(desc.value) < 0) {
  29546. if (isNull(recurseTimes)) {
  29547. str = formatValue(ctx, desc.value, null);
  29548. } else {
  29549. str = formatValue(ctx, desc.value, recurseTimes - 1);
  29550. }
  29551. if (str.indexOf('\n') > -1) {
  29552. if (array) {
  29553. str = str.split('\n').map(function(line) {
  29554. return ' ' + line;
  29555. }).join('\n').substr(2);
  29556. } else {
  29557. str = '\n' + str.split('\n').map(function(line) {
  29558. return ' ' + line;
  29559. }).join('\n');
  29560. }
  29561. }
  29562. } else {
  29563. str = ctx.stylize('[Circular]', 'special');
  29564. }
  29565. }
  29566. if (isUndefined(name)) {
  29567. if (array && key.match(/^\d+$/)) {
  29568. return str;
  29569. }
  29570. name = JSON.stringify('' + key);
  29571. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  29572. name = name.substr(1, name.length - 2);
  29573. name = ctx.stylize(name, 'name');
  29574. } else {
  29575. name = name.replace(/'/g, "\\'")
  29576. .replace(/\\"/g, '"')
  29577. .replace(/(^"|"$)/g, "'");
  29578. name = ctx.stylize(name, 'string');
  29579. }
  29580. }
  29581. return name + ': ' + str;
  29582. }
  29583. function reduceToSingleString(output, base, braces) {
  29584. var length = output.reduce(function(prev, cur) {
  29585. if (cur.indexOf('\n') >= 0) ;
  29586. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  29587. }, 0);
  29588. if (length > 60) {
  29589. return braces[0] +
  29590. (base === '' ? '' : base + '\n ') +
  29591. ' ' +
  29592. output.join(',\n ') +
  29593. ' ' +
  29594. braces[1];
  29595. }
  29596. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  29597. }
  29598. // NOTE: These type checking functions intentionally don't use `instanceof`
  29599. // because it is fragile and can be easily faked with `Object.create()`.
  29600. function isArray$1(ar) {
  29601. return Array.isArray(ar);
  29602. }
  29603. function isBoolean(arg) {
  29604. return typeof arg === 'boolean';
  29605. }
  29606. function isNull(arg) {
  29607. return arg === null;
  29608. }
  29609. function isNullOrUndefined(arg) {
  29610. return arg == null;
  29611. }
  29612. function isNumber(arg) {
  29613. return typeof arg === 'number';
  29614. }
  29615. function isString(arg) {
  29616. return typeof arg === 'string';
  29617. }
  29618. function isSymbol(arg) {
  29619. return typeof arg === 'symbol';
  29620. }
  29621. function isUndefined(arg) {
  29622. return arg === void 0;
  29623. }
  29624. function isRegExp(re) {
  29625. return isObject$1(re) && objectToString(re) === '[object RegExp]';
  29626. }
  29627. function isObject$1(arg) {
  29628. return typeof arg === 'object' && arg !== null;
  29629. }
  29630. function isDate(d) {
  29631. return isObject$1(d) && objectToString(d) === '[object Date]';
  29632. }
  29633. function isError(e) {
  29634. return isObject$1(e) &&
  29635. (objectToString(e) === '[object Error]' || e instanceof Error);
  29636. }
  29637. function isFunction(arg) {
  29638. return typeof arg === 'function';
  29639. }
  29640. function isPrimitive(arg) {
  29641. return arg === null ||
  29642. typeof arg === 'boolean' ||
  29643. typeof arg === 'number' ||
  29644. typeof arg === 'string' ||
  29645. typeof arg === 'symbol' || // ES6 symbol
  29646. typeof arg === 'undefined';
  29647. }
  29648. function isBuffer(maybeBuf) {
  29649. return Buffer$1.isBuffer(maybeBuf);
  29650. }
  29651. function objectToString(o) {
  29652. return Object.prototype.toString.call(o);
  29653. }
  29654. function pad(n) {
  29655. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  29656. }
  29657. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  29658. 'Oct', 'Nov', 'Dec'];
  29659. // 26 Feb 16:19:34
  29660. function timestamp() {
  29661. var d = new Date();
  29662. var time = [pad(d.getHours()),
  29663. pad(d.getMinutes()),
  29664. pad(d.getSeconds())].join(':');
  29665. return [d.getDate(), months[d.getMonth()], time].join(' ');
  29666. }
  29667. // log is just a thin wrapper to console.log that prepends a timestamp
  29668. function log() {
  29669. console.log('%s - %s', timestamp(), format$1.apply(null, arguments));
  29670. }
  29671. function _extend(origin, add) {
  29672. // Don't do anything if add isn't an object
  29673. if (!add || !isObject$1(add)) return origin;
  29674. var keys = Object.keys(add);
  29675. var i = keys.length;
  29676. while (i--) {
  29677. origin[keys[i]] = add[keys[i]];
  29678. }
  29679. return origin;
  29680. }
  29681. function hasOwnProperty$2(obj, prop) {
  29682. return Object.prototype.hasOwnProperty.call(obj, prop);
  29683. }
  29684. var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
  29685. function promisify(original) {
  29686. if (typeof original !== 'function')
  29687. throw new TypeError('The "original" argument must be of type Function');
  29688. if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
  29689. var fn = original[kCustomPromisifiedSymbol];
  29690. if (typeof fn !== 'function') {
  29691. throw new TypeError('The "util.promisify.custom" argument must be of type Function');
  29692. }
  29693. Object.defineProperty(fn, kCustomPromisifiedSymbol, {
  29694. value: fn, enumerable: false, writable: false, configurable: true
  29695. });
  29696. return fn;
  29697. }
  29698. function fn() {
  29699. var promiseResolve, promiseReject;
  29700. var promise = new Promise(function (resolve, reject) {
  29701. promiseResolve = resolve;
  29702. promiseReject = reject;
  29703. });
  29704. var args = [];
  29705. for (var i = 0; i < arguments.length; i++) {
  29706. args.push(arguments[i]);
  29707. }
  29708. args.push(function (err, value) {
  29709. if (err) {
  29710. promiseReject(err);
  29711. } else {
  29712. promiseResolve(value);
  29713. }
  29714. });
  29715. try {
  29716. original.apply(this, args);
  29717. } catch (err) {
  29718. promiseReject(err);
  29719. }
  29720. return promise;
  29721. }
  29722. Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
  29723. if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
  29724. value: fn, enumerable: false, writable: false, configurable: true
  29725. });
  29726. return Object.defineProperties(
  29727. fn,
  29728. getOwnPropertyDescriptors(original)
  29729. );
  29730. }
  29731. promisify.custom = kCustomPromisifiedSymbol;
  29732. function callbackifyOnRejected(reason, cb) {
  29733. // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
  29734. // Because `null` is a special error value in callbacks which means "no error
  29735. // occurred", we error-wrap so the callback consumer can distinguish between
  29736. // "the promise rejected with null" or "the promise fulfilled with undefined".
  29737. if (!reason) {
  29738. var newReason = new Error('Promise was rejected with a falsy value');
  29739. newReason.reason = reason;
  29740. reason = newReason;
  29741. }
  29742. return cb(reason);
  29743. }
  29744. function callbackify(original) {
  29745. if (typeof original !== 'function') {
  29746. throw new TypeError('The "original" argument must be of type Function');
  29747. }
  29748. // We DO NOT return the promise as it gives the user a false sense that
  29749. // the promise is actually somehow related to the callback's execution
  29750. // and that the callback throwing will reject the promise.
  29751. function callbackified() {
  29752. var args = [];
  29753. for (var i = 0; i < arguments.length; i++) {
  29754. args.push(arguments[i]);
  29755. }
  29756. var maybeCb = args.pop();
  29757. if (typeof maybeCb !== 'function') {
  29758. throw new TypeError('The last argument must be of type Function');
  29759. }
  29760. var self = this;
  29761. var cb = function() {
  29762. return maybeCb.apply(self, arguments);
  29763. };
  29764. // In true node style we process the callback on `nextTick` with all the
  29765. // implications (stack, `uncaughtException`, `async_hooks`)
  29766. original.apply(this, args)
  29767. .then(function(ret) { browser$1.nextTick(cb.bind(null, null, ret)); },
  29768. function(rej) { browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); });
  29769. }
  29770. Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
  29771. Object.defineProperties(callbackified, getOwnPropertyDescriptors(original));
  29772. return callbackified;
  29773. }
  29774. var _polyfillNode_util = {
  29775. inherits: inherits,
  29776. _extend: _extend,
  29777. log: log,
  29778. isBuffer: isBuffer,
  29779. isPrimitive: isPrimitive,
  29780. isFunction: isFunction,
  29781. isError: isError,
  29782. isDate: isDate,
  29783. isObject: isObject$1,
  29784. isRegExp: isRegExp,
  29785. isUndefined: isUndefined,
  29786. isSymbol: isSymbol,
  29787. isString: isString,
  29788. isNumber: isNumber,
  29789. isNullOrUndefined: isNullOrUndefined,
  29790. isNull: isNull,
  29791. isBoolean: isBoolean,
  29792. isArray: isArray$1,
  29793. inspect: inspect,
  29794. deprecate: deprecate,
  29795. format: format$1,
  29796. debuglog: debuglog,
  29797. promisify: promisify,
  29798. callbackify: callbackify,
  29799. };
  29800. var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
  29801. __proto__: null,
  29802. _extend: _extend,
  29803. callbackify: callbackify,
  29804. debuglog: debuglog,
  29805. default: _polyfillNode_util,
  29806. deprecate: deprecate,
  29807. format: format$1,
  29808. inherits: inherits,
  29809. inspect: inspect,
  29810. isArray: isArray$1,
  29811. isBoolean: isBoolean,
  29812. isBuffer: isBuffer,
  29813. isDate: isDate,
  29814. isError: isError,
  29815. isFunction: isFunction,
  29816. isNull: isNull,
  29817. isNullOrUndefined: isNullOrUndefined,
  29818. isNumber: isNumber,
  29819. isObject: isObject$1,
  29820. isPrimitive: isPrimitive,
  29821. isRegExp: isRegExp,
  29822. isString: isString,
  29823. isSymbol: isSymbol,
  29824. isUndefined: isUndefined,
  29825. log: log,
  29826. promisify: promisify
  29827. });
  29828. // Copyright Joyent, Inc. and other Node contributors.
  29829. //
  29830. // Permission is hereby granted, free of charge, to any person obtaining a
  29831. // copy of this software and associated documentation files (the
  29832. // "Software"), to deal in the Software without restriction, including
  29833. // without limitation the rights to use, copy, modify, merge, publish,
  29834. // distribute, sublicense, and/or sell copies of the Software, and to permit
  29835. // persons to whom the Software is furnished to do so, subject to the
  29836. // following conditions:
  29837. //
  29838. // The above copyright notice and this permission notice shall be included
  29839. // in all copies or substantial portions of the Software.
  29840. //
  29841. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  29842. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  29843. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  29844. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  29845. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  29846. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  29847. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  29848. // If obj.hasOwnProperty has been overridden, then calling
  29849. // obj.hasOwnProperty(prop) will break.
  29850. // See: https://github.com/joyent/node/issues/1707
  29851. function hasOwnProperty$1(obj, prop) {
  29852. return Object.prototype.hasOwnProperty.call(obj, prop);
  29853. }
  29854. var isArray = Array.isArray || function (xs) {
  29855. return Object.prototype.toString.call(xs) === '[object Array]';
  29856. };
  29857. function stringifyPrimitive(v) {
  29858. switch (typeof v) {
  29859. case 'string':
  29860. return v;
  29861. case 'boolean':
  29862. return v ? 'true' : 'false';
  29863. case 'number':
  29864. return isFinite(v) ? v : '';
  29865. default:
  29866. return '';
  29867. }
  29868. }
  29869. function stringify (obj, sep, eq, name) {
  29870. sep = sep || '&';
  29871. eq = eq || '=';
  29872. if (obj === null) {
  29873. obj = undefined;
  29874. }
  29875. if (typeof obj === 'object') {
  29876. return map(objectKeys(obj), function(k) {
  29877. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  29878. if (isArray(obj[k])) {
  29879. return map(obj[k], function(v) {
  29880. return ks + encodeURIComponent(stringifyPrimitive(v));
  29881. }).join(sep);
  29882. } else {
  29883. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  29884. }
  29885. }).join(sep);
  29886. }
  29887. if (!name) return '';
  29888. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  29889. encodeURIComponent(stringifyPrimitive(obj));
  29890. }
  29891. function map (xs, f) {
  29892. if (xs.map) return xs.map(f);
  29893. var res = [];
  29894. for (var i = 0; i < xs.length; i++) {
  29895. res.push(f(xs[i], i));
  29896. }
  29897. return res;
  29898. }
  29899. var objectKeys = Object.keys || function (obj) {
  29900. var res = [];
  29901. for (var key in obj) {
  29902. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  29903. }
  29904. return res;
  29905. };
  29906. function parse$1(qs, sep, eq, options) {
  29907. sep = sep || '&';
  29908. eq = eq || '=';
  29909. var obj = {};
  29910. if (typeof qs !== 'string' || qs.length === 0) {
  29911. return obj;
  29912. }
  29913. var regexp = /\+/g;
  29914. qs = qs.split(sep);
  29915. var maxKeys = 1000;
  29916. if (options && typeof options.maxKeys === 'number') {
  29917. maxKeys = options.maxKeys;
  29918. }
  29919. var len = qs.length;
  29920. // maxKeys <= 0 means that we should not limit keys count
  29921. if (maxKeys > 0 && len > maxKeys) {
  29922. len = maxKeys;
  29923. }
  29924. for (var i = 0; i < len; ++i) {
  29925. var x = qs[i].replace(regexp, '%20'),
  29926. idx = x.indexOf(eq),
  29927. kstr, vstr, k, v;
  29928. if (idx >= 0) {
  29929. kstr = x.substr(0, idx);
  29930. vstr = x.substr(idx + 1);
  29931. } else {
  29932. kstr = x;
  29933. vstr = '';
  29934. }
  29935. k = decodeURIComponent(kstr);
  29936. v = decodeURIComponent(vstr);
  29937. if (!hasOwnProperty$1(obj, k)) {
  29938. obj[k] = v;
  29939. } else if (isArray(obj[k])) {
  29940. obj[k].push(v);
  29941. } else {
  29942. obj[k] = [obj[k], v];
  29943. }
  29944. }
  29945. return obj;
  29946. }
  29947. // WHATWG API
  29948. const URL$1 = global$1.URL;
  29949. const URLSearchParams = global$1.URLSearchParams;
  29950. var _polyfillNode_url = {
  29951. parse: urlParse,
  29952. resolve: urlResolve,
  29953. resolveObject: urlResolveObject,
  29954. fileURLToPath: urlFileURLToPath,
  29955. format: urlFormat,
  29956. Url: Url,
  29957. // WHATWG API
  29958. URL: URL$1,
  29959. URLSearchParams,
  29960. };
  29961. function Url() {
  29962. this.protocol = null;
  29963. this.slashes = null;
  29964. this.auth = null;
  29965. this.host = null;
  29966. this.port = null;
  29967. this.hostname = null;
  29968. this.hash = null;
  29969. this.search = null;
  29970. this.query = null;
  29971. this.pathname = null;
  29972. this.path = null;
  29973. this.href = null;
  29974. }
  29975. // Reference: RFC 3986, RFC 1808, RFC 2396
  29976. // define these here so at least they only have to be
  29977. // compiled once on the first module load.
  29978. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  29979. portPattern = /:[0-9]*$/,
  29980. // Special case for a simple path URL
  29981. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  29982. // RFC 2396: characters reserved for delimiting URLs.
  29983. // We actually just auto-escape these.
  29984. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  29985. // RFC 2396: characters not allowed for various reasons.
  29986. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  29987. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  29988. autoEscape = ['\''].concat(unwise),
  29989. // Characters that are never ever allowed in a hostname.
  29990. // Note that any invalid chars are also handled, but these
  29991. // are the ones that are *expected* to be seen, so we fast-path
  29992. // them.
  29993. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  29994. hostEndingChars = ['/', '?', '#'],
  29995. hostnameMaxLen = 255,
  29996. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  29997. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  29998. // protocols that can allow "unsafe" and "unwise" chars.
  29999. unsafeProtocol = {
  30000. 'javascript': true,
  30001. 'javascript:': true
  30002. },
  30003. // protocols that never have a hostname.
  30004. hostlessProtocol = {
  30005. 'javascript': true,
  30006. 'javascript:': true
  30007. },
  30008. // protocols that always contain a // bit.
  30009. slashedProtocol = {
  30010. 'http': true,
  30011. 'https': true,
  30012. 'ftp': true,
  30013. 'gopher': true,
  30014. 'file': true,
  30015. 'http:': true,
  30016. 'https:': true,
  30017. 'ftp:': true,
  30018. 'gopher:': true,
  30019. 'file:': true
  30020. };
  30021. function urlParse(url, parseQueryString, slashesDenoteHost) {
  30022. if (url && isObject$1(url) && url instanceof Url) return url;
  30023. var u = new Url;
  30024. u.parse(url, parseQueryString, slashesDenoteHost);
  30025. return u;
  30026. }
  30027. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  30028. return parse(this, url, parseQueryString, slashesDenoteHost);
  30029. };
  30030. function parse(self, url, parseQueryString, slashesDenoteHost) {
  30031. if (!isString(url)) {
  30032. throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url);
  30033. }
  30034. // Copy chrome, IE, opera backslash-handling behavior.
  30035. // Back slashes before the query string get converted to forward slashes
  30036. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  30037. var queryIndex = url.indexOf('?'),
  30038. splitter =
  30039. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  30040. uSplit = url.split(splitter),
  30041. slashRegex = /\\/g;
  30042. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  30043. url = uSplit.join(splitter);
  30044. var rest = url;
  30045. // trim before proceeding.
  30046. // This is to support parse stuff like " http://foo.com \n"
  30047. rest = rest.trim();
  30048. if (!slashesDenoteHost && url.split('#').length === 1) {
  30049. // Try fast path regexp
  30050. var simplePath = simplePathPattern.exec(rest);
  30051. if (simplePath) {
  30052. self.path = rest;
  30053. self.href = rest;
  30054. self.pathname = simplePath[1];
  30055. if (simplePath[2]) {
  30056. self.search = simplePath[2];
  30057. if (parseQueryString) {
  30058. self.query = parse$1(self.search.substr(1));
  30059. } else {
  30060. self.query = self.search.substr(1);
  30061. }
  30062. } else if (parseQueryString) {
  30063. self.search = '';
  30064. self.query = {};
  30065. }
  30066. return self;
  30067. }
  30068. }
  30069. var proto = protocolPattern.exec(rest);
  30070. if (proto) {
  30071. proto = proto[0];
  30072. var lowerProto = proto.toLowerCase();
  30073. self.protocol = lowerProto;
  30074. rest = rest.substr(proto.length);
  30075. }
  30076. // figure out if it's got a host
  30077. // user@server is *always* interpreted as a hostname, and url
  30078. // resolution will treat //foo/bar as host=foo,path=bar because that's
  30079. // how the browser resolves relative URLs.
  30080. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  30081. var slashes = rest.substr(0, 2) === '//';
  30082. if (slashes && !(proto && hostlessProtocol[proto])) {
  30083. rest = rest.substr(2);
  30084. self.slashes = true;
  30085. }
  30086. }
  30087. var i, hec, l, p;
  30088. if (!hostlessProtocol[proto] &&
  30089. (slashes || (proto && !slashedProtocol[proto]))) {
  30090. // there's a hostname.
  30091. // the first instance of /, ?, ;, or # ends the host.
  30092. //
  30093. // If there is an @ in the hostname, then non-host chars *are* allowed
  30094. // to the left of the last @ sign, unless some host-ending character
  30095. // comes *before* the @-sign.
  30096. // URLs are obnoxious.
  30097. //
  30098. // ex:
  30099. // http://a@b@c/ => user:a@b host:c
  30100. // http://a@b?@c => user:a host:c path:/?@c
  30101. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  30102. // Review our test case against browsers more comprehensively.
  30103. // find the first instance of any hostEndingChars
  30104. var hostEnd = -1;
  30105. for (i = 0; i < hostEndingChars.length; i++) {
  30106. hec = rest.indexOf(hostEndingChars[i]);
  30107. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  30108. hostEnd = hec;
  30109. }
  30110. // at this point, either we have an explicit point where the
  30111. // auth portion cannot go past, or the last @ char is the decider.
  30112. var auth, atSign;
  30113. if (hostEnd === -1) {
  30114. // atSign can be anywhere.
  30115. atSign = rest.lastIndexOf('@');
  30116. } else {
  30117. // atSign must be in auth portion.
  30118. // http://a@b/c@d => host:b auth:a path:/c@d
  30119. atSign = rest.lastIndexOf('@', hostEnd);
  30120. }
  30121. // Now we have a portion which is definitely the auth.
  30122. // Pull that off.
  30123. if (atSign !== -1) {
  30124. auth = rest.slice(0, atSign);
  30125. rest = rest.slice(atSign + 1);
  30126. self.auth = decodeURIComponent(auth);
  30127. }
  30128. // the host is the remaining to the left of the first non-host char
  30129. hostEnd = -1;
  30130. for (i = 0; i < nonHostChars.length; i++) {
  30131. hec = rest.indexOf(nonHostChars[i]);
  30132. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  30133. hostEnd = hec;
  30134. }
  30135. // if we still have not hit it, then the entire thing is a host.
  30136. if (hostEnd === -1)
  30137. hostEnd = rest.length;
  30138. self.host = rest.slice(0, hostEnd);
  30139. rest = rest.slice(hostEnd);
  30140. // pull out port.
  30141. parseHost(self);
  30142. // we've indicated that there is a hostname,
  30143. // so even if it's empty, it has to be present.
  30144. self.hostname = self.hostname || '';
  30145. // if hostname begins with [ and ends with ]
  30146. // assume that it's an IPv6 address.
  30147. var ipv6Hostname = self.hostname[0] === '[' &&
  30148. self.hostname[self.hostname.length - 1] === ']';
  30149. // validate a little.
  30150. if (!ipv6Hostname) {
  30151. var hostparts = self.hostname.split(/\./);
  30152. for (i = 0, l = hostparts.length; i < l; i++) {
  30153. var part = hostparts[i];
  30154. if (!part) continue;
  30155. if (!part.match(hostnamePartPattern)) {
  30156. var newpart = '';
  30157. for (var j = 0, k = part.length; j < k; j++) {
  30158. if (part.charCodeAt(j) > 127) {
  30159. // we replace non-ASCII char with a temporary placeholder
  30160. // we need this to make sure size of hostname is not
  30161. // broken by replacing non-ASCII by nothing
  30162. newpart += 'x';
  30163. } else {
  30164. newpart += part[j];
  30165. }
  30166. }
  30167. // we test again with ASCII char only
  30168. if (!newpart.match(hostnamePartPattern)) {
  30169. var validParts = hostparts.slice(0, i);
  30170. var notHost = hostparts.slice(i + 1);
  30171. var bit = part.match(hostnamePartStart);
  30172. if (bit) {
  30173. validParts.push(bit[1]);
  30174. notHost.unshift(bit[2]);
  30175. }
  30176. if (notHost.length) {
  30177. rest = '/' + notHost.join('.') + rest;
  30178. }
  30179. self.hostname = validParts.join('.');
  30180. break;
  30181. }
  30182. }
  30183. }
  30184. }
  30185. if (self.hostname.length > hostnameMaxLen) {
  30186. self.hostname = '';
  30187. } else {
  30188. // hostnames are always lower case.
  30189. self.hostname = self.hostname.toLowerCase();
  30190. }
  30191. if (!ipv6Hostname) {
  30192. // IDNA Support: Returns a punycoded representation of "domain".
  30193. // It only converts parts of the domain name that
  30194. // have non-ASCII characters, i.e. it doesn't matter if
  30195. // you call it with a domain that already is ASCII-only.
  30196. self.hostname = toASCII(self.hostname);
  30197. }
  30198. p = self.port ? ':' + self.port : '';
  30199. var h = self.hostname || '';
  30200. self.host = h + p;
  30201. self.href += self.host;
  30202. // strip [ and ] from the hostname
  30203. // the host field still retains them, though
  30204. if (ipv6Hostname) {
  30205. self.hostname = self.hostname.substr(1, self.hostname.length - 2);
  30206. if (rest[0] !== '/') {
  30207. rest = '/' + rest;
  30208. }
  30209. }
  30210. }
  30211. // now rest is set to the post-host stuff.
  30212. // chop off any delim chars.
  30213. if (!unsafeProtocol[lowerProto]) {
  30214. // First, make 100% sure that any "autoEscape" chars get
  30215. // escaped, even if encodeURIComponent doesn't think they
  30216. // need to be.
  30217. for (i = 0, l = autoEscape.length; i < l; i++) {
  30218. var ae = autoEscape[i];
  30219. if (rest.indexOf(ae) === -1)
  30220. continue;
  30221. var esc = encodeURIComponent(ae);
  30222. if (esc === ae) {
  30223. esc = escape(ae);
  30224. }
  30225. rest = rest.split(ae).join(esc);
  30226. }
  30227. }
  30228. // chop off from the tail first.
  30229. var hash = rest.indexOf('#');
  30230. if (hash !== -1) {
  30231. // got a fragment string.
  30232. self.hash = rest.substr(hash);
  30233. rest = rest.slice(0, hash);
  30234. }
  30235. var qm = rest.indexOf('?');
  30236. if (qm !== -1) {
  30237. self.search = rest.substr(qm);
  30238. self.query = rest.substr(qm + 1);
  30239. if (parseQueryString) {
  30240. self.query = parse$1(self.query);
  30241. }
  30242. rest = rest.slice(0, qm);
  30243. } else if (parseQueryString) {
  30244. // no query string, but parseQueryString still requested
  30245. self.search = '';
  30246. self.query = {};
  30247. }
  30248. if (rest) self.pathname = rest;
  30249. if (slashedProtocol[lowerProto] &&
  30250. self.hostname && !self.pathname) {
  30251. self.pathname = '/';
  30252. }
  30253. //to support http.request
  30254. if (self.pathname || self.search) {
  30255. p = self.pathname || '';
  30256. var s = self.search || '';
  30257. self.path = p + s;
  30258. }
  30259. // finally, reconstruct the href based on what has been validated.
  30260. self.href = format(self);
  30261. return self;
  30262. }
  30263. function urlFileURLToPath(path) {
  30264. if (typeof path === 'string')
  30265. path = new Url().parse(path);
  30266. else if (!(path instanceof Url))
  30267. throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path));
  30268. if (path.protocol !== 'file:')
  30269. throw new TypeError('The URL must be of scheme file');
  30270. return getPathFromURLPosix(path);
  30271. }
  30272. function getPathFromURLPosix(url) {
  30273. const pathname = url.pathname;
  30274. for (let n = 0; n < pathname.length; n++) {
  30275. if (pathname[n] === '%') {
  30276. const third = pathname.codePointAt(n + 2) | 0x20;
  30277. if (pathname[n + 1] === '2' && third === 102) {
  30278. throw new TypeError(
  30279. 'must not include encoded / characters'
  30280. );
  30281. }
  30282. }
  30283. }
  30284. return decodeURIComponent(pathname);
  30285. }
  30286. // format a parsed object into a url string
  30287. function urlFormat(obj) {
  30288. // ensure it's an object, and not a string url.
  30289. // If it's an obj, this is a no-op.
  30290. // this way, you can call url_format() on strings
  30291. // to clean up potentially wonky urls.
  30292. if (isString(obj)) obj = parse({}, obj);
  30293. return format(obj);
  30294. }
  30295. function format(self) {
  30296. var auth = self.auth || '';
  30297. if (auth) {
  30298. auth = encodeURIComponent(auth);
  30299. auth = auth.replace(/%3A/i, ':');
  30300. auth += '@';
  30301. }
  30302. var protocol = self.protocol || '',
  30303. pathname = self.pathname || '',
  30304. hash = self.hash || '',
  30305. host = false,
  30306. query = '';
  30307. if (self.host) {
  30308. host = auth + self.host;
  30309. } else if (self.hostname) {
  30310. host = auth + (self.hostname.indexOf(':') === -1 ?
  30311. self.hostname :
  30312. '[' + this.hostname + ']');
  30313. if (self.port) {
  30314. host += ':' + self.port;
  30315. }
  30316. }
  30317. if (self.query &&
  30318. isObject$1(self.query) &&
  30319. Object.keys(self.query).length) {
  30320. query = stringify(self.query);
  30321. }
  30322. var search = self.search || (query && ('?' + query)) || '';
  30323. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  30324. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  30325. // unless they had them to begin with.
  30326. if (self.slashes ||
  30327. (!protocol || slashedProtocol[protocol]) && host !== false) {
  30328. host = '//' + (host || '');
  30329. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  30330. } else if (!host) {
  30331. host = '';
  30332. }
  30333. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  30334. if (search && search.charAt(0) !== '?') search = '?' + search;
  30335. pathname = pathname.replace(/[?#]/g, function(match) {
  30336. return encodeURIComponent(match);
  30337. });
  30338. search = search.replace('#', '%23');
  30339. return protocol + host + pathname + search + hash;
  30340. }
  30341. Url.prototype.format = function() {
  30342. return format(this);
  30343. };
  30344. function urlResolve(source, relative) {
  30345. return urlParse(source, false, true).resolve(relative);
  30346. }
  30347. Url.prototype.resolve = function(relative) {
  30348. return this.resolveObject(urlParse(relative, false, true)).format();
  30349. };
  30350. function urlResolveObject(source, relative) {
  30351. if (!source) return relative;
  30352. return urlParse(source, false, true).resolveObject(relative);
  30353. }
  30354. Url.prototype.resolveObject = function(relative) {
  30355. if (isString(relative)) {
  30356. var rel = new Url();
  30357. rel.parse(relative, false, true);
  30358. relative = rel;
  30359. }
  30360. var result = new Url();
  30361. var tkeys = Object.keys(this);
  30362. for (var tk = 0; tk < tkeys.length; tk++) {
  30363. var tkey = tkeys[tk];
  30364. result[tkey] = this[tkey];
  30365. }
  30366. // hash is always overridden, no matter what.
  30367. // even href="" will remove it.
  30368. result.hash = relative.hash;
  30369. // if the relative url is empty, then there's nothing left to do here.
  30370. if (relative.href === '') {
  30371. result.href = result.format();
  30372. return result;
  30373. }
  30374. // hrefs like //foo/bar always cut to the protocol.
  30375. if (relative.slashes && !relative.protocol) {
  30376. // take everything except the protocol from relative
  30377. var rkeys = Object.keys(relative);
  30378. for (var rk = 0; rk < rkeys.length; rk++) {
  30379. var rkey = rkeys[rk];
  30380. if (rkey !== 'protocol')
  30381. result[rkey] = relative[rkey];
  30382. }
  30383. //urlParse appends trailing / to urls like http://www.example.com
  30384. if (slashedProtocol[result.protocol] &&
  30385. result.hostname && !result.pathname) {
  30386. result.path = result.pathname = '/';
  30387. }
  30388. result.href = result.format();
  30389. return result;
  30390. }
  30391. var relPath;
  30392. if (relative.protocol && relative.protocol !== result.protocol) {
  30393. // if it's a known url protocol, then changing
  30394. // the protocol does weird things
  30395. // first, if it's not file:, then we MUST have a host,
  30396. // and if there was a path
  30397. // to begin with, then we MUST have a path.
  30398. // if it is file:, then the host is dropped,
  30399. // because that's known to be hostless.
  30400. // anything else is assumed to be absolute.
  30401. if (!slashedProtocol[relative.protocol]) {
  30402. var keys = Object.keys(relative);
  30403. for (var v = 0; v < keys.length; v++) {
  30404. var k = keys[v];
  30405. result[k] = relative[k];
  30406. }
  30407. result.href = result.format();
  30408. return result;
  30409. }
  30410. result.protocol = relative.protocol;
  30411. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  30412. relPath = (relative.pathname || '').split('/');
  30413. while (relPath.length && !(relative.host = relPath.shift()));
  30414. if (!relative.host) relative.host = '';
  30415. if (!relative.hostname) relative.hostname = '';
  30416. if (relPath[0] !== '') relPath.unshift('');
  30417. if (relPath.length < 2) relPath.unshift('');
  30418. result.pathname = relPath.join('/');
  30419. } else {
  30420. result.pathname = relative.pathname;
  30421. }
  30422. result.search = relative.search;
  30423. result.query = relative.query;
  30424. result.host = relative.host || '';
  30425. result.auth = relative.auth;
  30426. result.hostname = relative.hostname || relative.host;
  30427. result.port = relative.port;
  30428. // to support http.request
  30429. if (result.pathname || result.search) {
  30430. var p = result.pathname || '';
  30431. var s = result.search || '';
  30432. result.path = p + s;
  30433. }
  30434. result.slashes = result.slashes || relative.slashes;
  30435. result.href = result.format();
  30436. return result;
  30437. }
  30438. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  30439. isRelAbs = (
  30440. relative.host ||
  30441. relative.pathname && relative.pathname.charAt(0) === '/'
  30442. ),
  30443. mustEndAbs = (isRelAbs || isSourceAbs ||
  30444. (result.host && relative.pathname)),
  30445. removeAllDots = mustEndAbs,
  30446. srcPath = result.pathname && result.pathname.split('/') || [],
  30447. psychotic = result.protocol && !slashedProtocol[result.protocol];
  30448. relPath = relative.pathname && relative.pathname.split('/') || [];
  30449. // if the url is a non-slashed url, then relative
  30450. // links like ../.. should be able
  30451. // to crawl up to the hostname, as well. This is strange.
  30452. // result.protocol has already been set by now.
  30453. // Later on, put the first path part into the host field.
  30454. if (psychotic) {
  30455. result.hostname = '';
  30456. result.port = null;
  30457. if (result.host) {
  30458. if (srcPath[0] === '') srcPath[0] = result.host;
  30459. else srcPath.unshift(result.host);
  30460. }
  30461. result.host = '';
  30462. if (relative.protocol) {
  30463. relative.hostname = null;
  30464. relative.port = null;
  30465. if (relative.host) {
  30466. if (relPath[0] === '') relPath[0] = relative.host;
  30467. else relPath.unshift(relative.host);
  30468. }
  30469. relative.host = null;
  30470. }
  30471. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  30472. }
  30473. var authInHost;
  30474. if (isRelAbs) {
  30475. // it's absolute.
  30476. result.host = (relative.host || relative.host === '') ?
  30477. relative.host : result.host;
  30478. result.hostname = (relative.hostname || relative.hostname === '') ?
  30479. relative.hostname : result.hostname;
  30480. result.search = relative.search;
  30481. result.query = relative.query;
  30482. srcPath = relPath;
  30483. // fall through to the dot-handling below.
  30484. } else if (relPath.length) {
  30485. // it's relative
  30486. // throw away the existing file, and take the new path instead.
  30487. if (!srcPath) srcPath = [];
  30488. srcPath.pop();
  30489. srcPath = srcPath.concat(relPath);
  30490. result.search = relative.search;
  30491. result.query = relative.query;
  30492. } else if (!isNullOrUndefined(relative.search)) {
  30493. // just pull out the search.
  30494. // like href='?foo'.
  30495. // Put this after the other two cases because it simplifies the booleans
  30496. if (psychotic) {
  30497. result.hostname = result.host = srcPath.shift();
  30498. //occationaly the auth can get stuck only in host
  30499. //this especially happens in cases like
  30500. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  30501. authInHost = result.host && result.host.indexOf('@') > 0 ?
  30502. result.host.split('@') : false;
  30503. if (authInHost) {
  30504. result.auth = authInHost.shift();
  30505. result.host = result.hostname = authInHost.shift();
  30506. }
  30507. }
  30508. result.search = relative.search;
  30509. result.query = relative.query;
  30510. //to support http.request
  30511. if (!isNull(result.pathname) || !isNull(result.search)) {
  30512. result.path = (result.pathname ? result.pathname : '') +
  30513. (result.search ? result.search : '');
  30514. }
  30515. result.href = result.format();
  30516. return result;
  30517. }
  30518. if (!srcPath.length) {
  30519. // no path at all. easy.
  30520. // we've already handled the other stuff above.
  30521. result.pathname = null;
  30522. //to support http.request
  30523. if (result.search) {
  30524. result.path = '/' + result.search;
  30525. } else {
  30526. result.path = null;
  30527. }
  30528. result.href = result.format();
  30529. return result;
  30530. }
  30531. // if a url ENDs in . or .., then it must get a trailing slash.
  30532. // however, if it ends in anything else non-slashy,
  30533. // then it must NOT get a trailing slash.
  30534. var last = srcPath.slice(-1)[0];
  30535. var hasTrailingSlash = (
  30536. (result.host || relative.host || srcPath.length > 1) &&
  30537. (last === '.' || last === '..') || last === '');
  30538. // strip single dots, resolve double dots to parent dir
  30539. // if the path tries to go above the root, `up` ends up > 0
  30540. var up = 0;
  30541. for (var i = srcPath.length; i >= 0; i--) {
  30542. last = srcPath[i];
  30543. if (last === '.') {
  30544. srcPath.splice(i, 1);
  30545. } else if (last === '..') {
  30546. srcPath.splice(i, 1);
  30547. up++;
  30548. } else if (up) {
  30549. srcPath.splice(i, 1);
  30550. up--;
  30551. }
  30552. }
  30553. // if the path is allowed to go above the root, restore leading ..s
  30554. if (!mustEndAbs && !removeAllDots) {
  30555. for (; up--; up) {
  30556. srcPath.unshift('..');
  30557. }
  30558. }
  30559. if (mustEndAbs && srcPath[0] !== '' &&
  30560. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  30561. srcPath.unshift('');
  30562. }
  30563. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  30564. srcPath.push('');
  30565. }
  30566. var isAbsolute = srcPath[0] === '' ||
  30567. (srcPath[0] && srcPath[0].charAt(0) === '/');
  30568. // put the host back
  30569. if (psychotic) {
  30570. result.hostname = result.host = isAbsolute ? '' :
  30571. srcPath.length ? srcPath.shift() : '';
  30572. //occationaly the auth can get stuck only in host
  30573. //this especially happens in cases like
  30574. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  30575. authInHost = result.host && result.host.indexOf('@') > 0 ?
  30576. result.host.split('@') : false;
  30577. if (authInHost) {
  30578. result.auth = authInHost.shift();
  30579. result.host = result.hostname = authInHost.shift();
  30580. }
  30581. }
  30582. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  30583. if (mustEndAbs && !isAbsolute) {
  30584. srcPath.unshift('');
  30585. }
  30586. if (!srcPath.length) {
  30587. result.pathname = null;
  30588. result.path = null;
  30589. } else {
  30590. result.pathname = srcPath.join('/');
  30591. }
  30592. //to support request.http
  30593. if (!isNull(result.pathname) || !isNull(result.search)) {
  30594. result.path = (result.pathname ? result.pathname : '') +
  30595. (result.search ? result.search : '');
  30596. }
  30597. result.auth = relative.auth || result.auth;
  30598. result.slashes = result.slashes || relative.slashes;
  30599. result.href = result.format();
  30600. return result;
  30601. };
  30602. Url.prototype.parseHost = function() {
  30603. return parseHost(this);
  30604. };
  30605. function parseHost(self) {
  30606. var host = self.host;
  30607. var port = portPattern.exec(host);
  30608. if (port) {
  30609. port = port[0];
  30610. if (port !== ':') {
  30611. self.port = port.substr(1);
  30612. }
  30613. host = host.substr(0, host.length - port.length);
  30614. }
  30615. if (host) self.hostname = host;
  30616. }
  30617. var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({
  30618. __proto__: null,
  30619. URL: URL$1,
  30620. URLSearchParams: URLSearchParams,
  30621. Url: Url,
  30622. default: _polyfillNode_url,
  30623. fileURLToPath: urlFileURLToPath,
  30624. format: urlFormat,
  30625. parse: urlParse,
  30626. resolve: urlResolve,
  30627. resolveObject: urlResolveObject
  30628. });
  30629. function isRelativeUrl(url) {
  30630. const firstChar = url.charAt(0);
  30631. return firstChar === "." || firstChar === "~" || firstChar === "@" || firstChar === "#";
  30632. }
  30633. const externalRE = /^(?:https?:)?\/\//;
  30634. function isExternalUrl(url) {
  30635. return externalRE.test(url);
  30636. }
  30637. const dataUrlRE = /^\s*data:/i;
  30638. function isDataUrl(url) {
  30639. return dataUrlRE.test(url);
  30640. }
  30641. function normalizeDecodedImportPath(source) {
  30642. try {
  30643. return decodeURIComponent(source);
  30644. } catch (e) {
  30645. return source;
  30646. }
  30647. }
  30648. function parseUrl(url) {
  30649. const firstChar = url.charAt(0);
  30650. if (firstChar === "~") {
  30651. const secondChar = url.charAt(1);
  30652. url = url.slice(secondChar === "/" ? 2 : 1);
  30653. }
  30654. return parseUriParts(url);
  30655. }
  30656. function parseUriParts(urlString) {
  30657. return urlParse(isString$1(urlString) ? urlString : "", false, true);
  30658. }
  30659. var __defProp$9 = Object.defineProperty;
  30660. var __defProps$8 = Object.defineProperties;
  30661. var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
  30662. var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
  30663. var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
  30664. var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
  30665. var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  30666. var __spreadValues$9 = (a, b) => {
  30667. for (var prop in b || (b = {}))
  30668. if (__hasOwnProp$9.call(b, prop))
  30669. __defNormalProp$9(a, prop, b[prop]);
  30670. if (__getOwnPropSymbols$9)
  30671. for (var prop of __getOwnPropSymbols$9(b)) {
  30672. if (__propIsEnum$9.call(b, prop))
  30673. __defNormalProp$9(a, prop, b[prop]);
  30674. }
  30675. return a;
  30676. };
  30677. var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
  30678. const resourceUrlTagConfig = {
  30679. video: ["src", "poster"],
  30680. source: ["src"],
  30681. img: ["src"]
  30682. };
  30683. const defaultAssetUrlOptions = {
  30684. base: null,
  30685. includeAbsolute: false,
  30686. tags: __spreadProps$8(__spreadValues$9({}, resourceUrlTagConfig), {
  30687. image: ["xlink:href", "href"],
  30688. use: ["xlink:href", "href"]
  30689. })
  30690. };
  30691. const normalizeOptions = (options) => {
  30692. if (Object.keys(options).some((key) => isArray$3(options[key]))) {
  30693. return __spreadProps$8(__spreadValues$9({}, defaultAssetUrlOptions), {
  30694. tags: options
  30695. });
  30696. }
  30697. return __spreadValues$9(__spreadValues$9({}, defaultAssetUrlOptions), options);
  30698. };
  30699. const createAssetUrlTransformWithOptions = (options) => {
  30700. return (node, context) => transformAssetUrl(node, context, options);
  30701. };
  30702. function canTransformHashImport(tag, attrName) {
  30703. var _a;
  30704. return !!((_a = resourceUrlTagConfig[tag]) == null ? void 0 : _a.includes(attrName));
  30705. }
  30706. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  30707. if (node.type === 1) {
  30708. if (!node.props.length) {
  30709. return;
  30710. }
  30711. const tags = options.tags || defaultAssetUrlOptions.tags;
  30712. const attrs = tags[node.tag];
  30713. const wildCardAttrs = tags["*"];
  30714. if (!attrs && !wildCardAttrs) {
  30715. return;
  30716. }
  30717. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  30718. node.props.forEach((attr, index) => {
  30719. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value) {
  30720. return;
  30721. }
  30722. const urlValue = attr.value.content;
  30723. const isHashOnlyValue = urlValue[0] === "#";
  30724. if (isExternalUrl(urlValue) || isDataUrl(urlValue) || // a bare `#` is never a valid import specifier
  30725. urlValue === "#" || isHashOnlyValue && !canTransformHashImport(node.tag, attr.name) || !options.includeAbsolute && !isRelativeUrl(urlValue)) {
  30726. return;
  30727. }
  30728. const url = parseUrl(urlValue);
  30729. if (options.base && urlValue[0] === ".") {
  30730. const base = parseUrl(options.base);
  30731. const protocol = base.protocol || "";
  30732. const host = base.host ? protocol + "//" + base.host : "";
  30733. const basePath = base.path || "/";
  30734. attr.value.content = host + (path.posix || path).join(basePath, url.path + (url.hash || ""));
  30735. return;
  30736. }
  30737. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  30738. node.props[index] = {
  30739. type: 7,
  30740. name: "bind",
  30741. arg: createSimpleExpression(attr.name, true, attr.loc),
  30742. exp,
  30743. modifiers: [],
  30744. loc: attr.loc
  30745. };
  30746. });
  30747. }
  30748. };
  30749. function resolveOrRegisterImport(source, loc, context) {
  30750. const normalizedSource = normalizeDecodedImportPath(source);
  30751. const existingIndex = context.imports.findIndex(
  30752. (i) => i.path === normalizedSource
  30753. );
  30754. if (existingIndex > -1) {
  30755. return {
  30756. name: `_imports_${existingIndex}`,
  30757. exp: context.imports[existingIndex].exp
  30758. };
  30759. }
  30760. const name = `_imports_${context.imports.length}`;
  30761. const exp = createSimpleExpression(
  30762. name,
  30763. false,
  30764. loc,
  30765. 3
  30766. );
  30767. context.imports.push({
  30768. exp,
  30769. path: normalizedSource
  30770. });
  30771. return { name, exp };
  30772. }
  30773. function getImportsExpressionExp(path2, hash, loc, context) {
  30774. if (!path2 && !hash) {
  30775. return createSimpleExpression(`''`, false, loc, 3);
  30776. }
  30777. if (!path2 && hash) {
  30778. const { exp } = resolveOrRegisterImport(hash, loc, context);
  30779. return exp;
  30780. }
  30781. if (path2 && !hash) {
  30782. const { exp } = resolveOrRegisterImport(path2, loc, context);
  30783. return exp;
  30784. }
  30785. const { name } = resolveOrRegisterImport(path2, loc, context);
  30786. const hashExp = `${name} + '${hash}'`;
  30787. const finalExp = createSimpleExpression(
  30788. hashExp,
  30789. false,
  30790. loc,
  30791. 3
  30792. );
  30793. if (!context.hoistStatic) {
  30794. return finalExp;
  30795. }
  30796. const existingHoistIndex = context.hoists.findIndex((h) => {
  30797. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  30798. });
  30799. if (existingHoistIndex > -1) {
  30800. return createSimpleExpression(
  30801. `_hoisted_${existingHoistIndex + 1}`,
  30802. false,
  30803. loc,
  30804. 3
  30805. );
  30806. }
  30807. return context.hoist(finalExp);
  30808. }
  30809. const srcsetTags = ["img", "source"];
  30810. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  30811. const createSrcsetTransformWithOptions = (options) => {
  30812. return (node, context) => transformSrcset(node, context, options);
  30813. };
  30814. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  30815. if (node.type === 1) {
  30816. if (srcsetTags.includes(node.tag) && node.props.length) {
  30817. node.props.forEach((attr, index) => {
  30818. if (attr.name === "srcset" && attr.type === 6) {
  30819. if (!attr.value) return;
  30820. const value = attr.value.content;
  30821. if (!value) return;
  30822. const imageCandidates = value.split(",").map((s) => {
  30823. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  30824. return { url, descriptor };
  30825. });
  30826. for (let i = 0; i < imageCandidates.length; i++) {
  30827. const { url } = imageCandidates[i];
  30828. if (isDataUrl(url)) {
  30829. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  30830. imageCandidates.splice(i, 1);
  30831. }
  30832. }
  30833. const shouldProcessUrl = (url) => {
  30834. return url && !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  30835. };
  30836. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  30837. return;
  30838. }
  30839. if (options.base) {
  30840. const base = options.base;
  30841. const set = [];
  30842. let needImportTransform = false;
  30843. imageCandidates.forEach((candidate) => {
  30844. let { url, descriptor } = candidate;
  30845. descriptor = descriptor ? ` ${descriptor}` : ``;
  30846. if (url[0] === ".") {
  30847. candidate.url = (path.posix || path).join(base, url);
  30848. set.push(candidate.url + descriptor);
  30849. } else if (shouldProcessUrl(url)) {
  30850. needImportTransform = true;
  30851. } else {
  30852. set.push(url + descriptor);
  30853. }
  30854. });
  30855. if (!needImportTransform) {
  30856. attr.value.content = set.join(", ");
  30857. return;
  30858. }
  30859. }
  30860. const compoundExpression = createCompoundExpression([], attr.loc);
  30861. imageCandidates.forEach(({ url, descriptor }, index2) => {
  30862. if (shouldProcessUrl(url)) {
  30863. const { path: path2, hash } = parseUrl(url);
  30864. const source = path2 ? path2 : hash;
  30865. if (source) {
  30866. const normalizedSource = normalizeDecodedImportPath(source);
  30867. const existingImportsIndex = context.imports.findIndex(
  30868. (i) => i.path === normalizedSource
  30869. );
  30870. let exp2;
  30871. if (existingImportsIndex > -1) {
  30872. exp2 = createSimpleExpression(
  30873. `_imports_${existingImportsIndex}`,
  30874. false,
  30875. attr.loc,
  30876. 3
  30877. );
  30878. } else {
  30879. exp2 = createSimpleExpression(
  30880. `_imports_${context.imports.length}`,
  30881. false,
  30882. attr.loc,
  30883. 3
  30884. );
  30885. context.imports.push({ exp: exp2, path: normalizedSource });
  30886. }
  30887. if (path2 && hash) {
  30888. exp2 = createSimpleExpression(
  30889. `${exp2.content} + '${hash}'`,
  30890. false,
  30891. attr.loc,
  30892. 3
  30893. );
  30894. }
  30895. compoundExpression.children.push(exp2);
  30896. }
  30897. } else {
  30898. const exp2 = createSimpleExpression(
  30899. `"${url}"`,
  30900. false,
  30901. attr.loc,
  30902. 3
  30903. );
  30904. compoundExpression.children.push(exp2);
  30905. }
  30906. const isNotLast = imageCandidates.length - 1 > index2;
  30907. if (descriptor && isNotLast) {
  30908. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  30909. } else if (descriptor) {
  30910. compoundExpression.children.push(` + ' ${descriptor}'`);
  30911. } else if (isNotLast) {
  30912. compoundExpression.children.push(` + ', ' + `);
  30913. }
  30914. });
  30915. let exp = compoundExpression;
  30916. if (context.hoistStatic) {
  30917. exp = context.hoist(compoundExpression);
  30918. exp.constType = 3;
  30919. }
  30920. node.props[index] = {
  30921. type: 7,
  30922. name: "bind",
  30923. arg: createSimpleExpression("srcset", true, attr.loc),
  30924. exp,
  30925. modifiers: [],
  30926. loc: attr.loc
  30927. };
  30928. }
  30929. });
  30930. }
  30931. }
  30932. };
  30933. const SSR_INTERPOLATE = /* @__PURE__ */ Symbol(`ssrInterpolate`);
  30934. const SSR_RENDER_VNODE = /* @__PURE__ */ Symbol(`ssrRenderVNode`);
  30935. const SSR_RENDER_COMPONENT = /* @__PURE__ */ Symbol(`ssrRenderComponent`);
  30936. const SSR_RENDER_SLOT = /* @__PURE__ */ Symbol(`ssrRenderSlot`);
  30937. const SSR_RENDER_SLOT_INNER = /* @__PURE__ */ Symbol(`ssrRenderSlotInner`);
  30938. const SSR_RENDER_CLASS = /* @__PURE__ */ Symbol(`ssrRenderClass`);
  30939. const SSR_RENDER_STYLE = /* @__PURE__ */ Symbol(`ssrRenderStyle`);
  30940. const SSR_RENDER_ATTRS = /* @__PURE__ */ Symbol(`ssrRenderAttrs`);
  30941. const SSR_RENDER_ATTR = /* @__PURE__ */ Symbol(`ssrRenderAttr`);
  30942. const SSR_RENDER_DYNAMIC_ATTR = /* @__PURE__ */ Symbol(`ssrRenderDynamicAttr`);
  30943. const SSR_RENDER_LIST = /* @__PURE__ */ Symbol(`ssrRenderList`);
  30944. const SSR_INCLUDE_BOOLEAN_ATTR = /* @__PURE__ */ Symbol(
  30945. `ssrIncludeBooleanAttr`
  30946. );
  30947. const SSR_LOOSE_EQUAL = /* @__PURE__ */ Symbol(`ssrLooseEqual`);
  30948. const SSR_LOOSE_CONTAIN = /* @__PURE__ */ Symbol(`ssrLooseContain`);
  30949. const SSR_RENDER_DYNAMIC_MODEL = /* @__PURE__ */ Symbol(
  30950. `ssrRenderDynamicModel`
  30951. );
  30952. const SSR_GET_DYNAMIC_MODEL_PROPS = /* @__PURE__ */ Symbol(
  30953. `ssrGetDynamicModelProps`
  30954. );
  30955. const SSR_RENDER_TELEPORT = /* @__PURE__ */ Symbol(`ssrRenderTeleport`);
  30956. const SSR_RENDER_SUSPENSE = /* @__PURE__ */ Symbol(`ssrRenderSuspense`);
  30957. const SSR_GET_DIRECTIVE_PROPS = /* @__PURE__ */ Symbol(`ssrGetDirectiveProps`);
  30958. const ssrHelpers = {
  30959. [SSR_INTERPOLATE]: `ssrInterpolate`,
  30960. [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  30961. [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  30962. [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  30963. [SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`,
  30964. [SSR_RENDER_CLASS]: `ssrRenderClass`,
  30965. [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  30966. [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  30967. [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  30968. [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  30969. [SSR_RENDER_LIST]: `ssrRenderList`,
  30970. [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
  30971. [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  30972. [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  30973. [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  30974. [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  30975. [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  30976. [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`,
  30977. [SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps`
  30978. };
  30979. registerRuntimeHelpers(ssrHelpers);
  30980. const ssrTransformIf = createStructuralDirectiveTransform(
  30981. /^(?:if|else|else-if)$/,
  30982. processIf
  30983. );
  30984. function ssrProcessIf(node, context, disableNestedFragments = false, disableComment = false) {
  30985. const [rootBranch] = node.branches;
  30986. const ifStatement = createIfStatement(
  30987. rootBranch.condition,
  30988. processIfBranch(rootBranch, context, disableNestedFragments)
  30989. );
  30990. context.pushStatement(ifStatement);
  30991. let currentIf = ifStatement;
  30992. for (let i = 1; i < node.branches.length; i++) {
  30993. const branch = node.branches[i];
  30994. const branchBlockStatement = processIfBranch(
  30995. branch,
  30996. context,
  30997. disableNestedFragments
  30998. );
  30999. if (branch.condition) {
  31000. currentIf = currentIf.alternate = createIfStatement(
  31001. branch.condition,
  31002. branchBlockStatement
  31003. );
  31004. } else {
  31005. currentIf.alternate = branchBlockStatement;
  31006. }
  31007. }
  31008. if (!currentIf.alternate && !disableComment) {
  31009. currentIf.alternate = createBlockStatement([
  31010. createCallExpression(`_push`, ["`<!---->`"])
  31011. ]);
  31012. }
  31013. }
  31014. function processIfBranch(branch, context, disableNestedFragments = false) {
  31015. const { children } = branch;
  31016. const needFragmentWrapper = !disableNestedFragments && (children.length !== 1 || children[0].type !== 1) && // optimize away nested fragments when the only child is a ForNode
  31017. !(children.length === 1 && children[0].type === 11);
  31018. return processChildrenAsStatement(branch, context, needFragmentWrapper);
  31019. }
  31020. const ssrTransformFor = createStructuralDirectiveTransform("for", processFor);
  31021. function ssrProcessFor(node, context, disableNestedFragments = false) {
  31022. const needFragmentWrapper = !disableNestedFragments && (node.children.length !== 1 || node.children[0].type !== 1);
  31023. const renderLoop = createFunctionExpression(
  31024. createForLoopParams(node.parseResult)
  31025. );
  31026. renderLoop.body = processChildrenAsStatement(
  31027. node,
  31028. context,
  31029. needFragmentWrapper
  31030. );
  31031. if (!disableNestedFragments) {
  31032. context.pushStringPart(`<!--[-->`);
  31033. }
  31034. context.pushStatement(
  31035. createCallExpression(context.helper(SSR_RENDER_LIST), [
  31036. node.source,
  31037. renderLoop
  31038. ])
  31039. );
  31040. if (!disableNestedFragments) {
  31041. context.pushStringPart(`<!--]-->`);
  31042. }
  31043. }
  31044. const ssrTransformSlotOutlet = (node, context) => {
  31045. if (isSlotOutlet(node)) {
  31046. const { slotName, slotProps } = processSlotOutlet(node, context);
  31047. const args = [
  31048. `_ctx.$slots`,
  31049. slotName,
  31050. slotProps || `{}`,
  31051. // fallback content placeholder. will be replaced in the process phase
  31052. `null`,
  31053. `_push`,
  31054. `_parent`
  31055. ];
  31056. if (context.scopeId && context.slotted !== false) {
  31057. args.push(`"${context.scopeId}-s"`);
  31058. }
  31059. let method = SSR_RENDER_SLOT;
  31060. let parent = context.parent;
  31061. if (parent) {
  31062. const children = parent.children;
  31063. if (parent.type === 10) {
  31064. parent = context.grandParent;
  31065. }
  31066. let componentType;
  31067. if (parent.type === 1 && parent.tagType === 1 && ((componentType = resolveComponentType(parent, context, true)) === TRANSITION || componentType === TRANSITION_GROUP) && children.filter((c) => c.type === 1).length === 1) {
  31068. method = SSR_RENDER_SLOT_INNER;
  31069. if (!(context.scopeId && context.slotted !== false)) {
  31070. args.push("null");
  31071. }
  31072. args.push("true");
  31073. }
  31074. }
  31075. node.ssrCodegenNode = createCallExpression(context.helper(method), args);
  31076. }
  31077. };
  31078. function ssrProcessSlotOutlet(node, context) {
  31079. const renderCall = node.ssrCodegenNode;
  31080. if (node.children.length) {
  31081. const fallbackRenderFn = createFunctionExpression([]);
  31082. fallbackRenderFn.body = processChildrenAsStatement(node, context);
  31083. renderCall.arguments[3] = fallbackRenderFn;
  31084. }
  31085. if (context.withSlotScopeId) {
  31086. const slotScopeId = renderCall.arguments[6];
  31087. renderCall.arguments[6] = slotScopeId ? `${slotScopeId} + _scopeId` : `_scopeId`;
  31088. }
  31089. context.pushStatement(node.ssrCodegenNode);
  31090. }
  31091. function createSSRCompilerError(code, loc) {
  31092. return createCompilerError(code, loc, SSRErrorMessages);
  31093. }
  31094. const SSRErrorMessages = {
  31095. [65]: `Unsafe attribute name for SSR.`,
  31096. [66]: `Missing the 'to' prop on teleport element.`,
  31097. [67]: `Invalid AST node during SSR transform.`
  31098. };
  31099. function ssrProcessTeleport(node, context) {
  31100. const targetProp = findProp(node, "to");
  31101. if (!targetProp) {
  31102. context.onError(
  31103. createSSRCompilerError(66, node.loc)
  31104. );
  31105. return;
  31106. }
  31107. let target;
  31108. if (targetProp.type === 6) {
  31109. target = targetProp.value && createSimpleExpression(targetProp.value.content, true);
  31110. } else {
  31111. target = targetProp.exp;
  31112. }
  31113. if (!target) {
  31114. context.onError(
  31115. createSSRCompilerError(
  31116. 66,
  31117. targetProp.loc
  31118. )
  31119. );
  31120. return;
  31121. }
  31122. const disabledProp = findProp(
  31123. node,
  31124. "disabled",
  31125. false,
  31126. true
  31127. /* allow empty */
  31128. );
  31129. const disabled = disabledProp ? disabledProp.type === 6 ? `true` : disabledProp.exp || `false` : `false`;
  31130. const contentRenderFn = createFunctionExpression(
  31131. [`_push`],
  31132. void 0,
  31133. // Body is added later
  31134. true,
  31135. // newline
  31136. false,
  31137. // isSlot
  31138. node.loc
  31139. );
  31140. contentRenderFn.body = processChildrenAsStatement(node, context);
  31141. context.pushStatement(
  31142. createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
  31143. `_push`,
  31144. contentRenderFn,
  31145. target,
  31146. disabled,
  31147. `_parent`
  31148. ])
  31149. );
  31150. }
  31151. const wipMap$3 = /* @__PURE__ */ new WeakMap();
  31152. function ssrTransformSuspense(node, context) {
  31153. return () => {
  31154. if (node.children.length) {
  31155. const wipEntry = {
  31156. slotsExp: null,
  31157. // to be immediately set
  31158. wipSlots: []
  31159. };
  31160. wipMap$3.set(node, wipEntry);
  31161. wipEntry.slotsExp = buildSlots(
  31162. node,
  31163. context,
  31164. (_props, _vForExp, children, loc) => {
  31165. const fn = createFunctionExpression(
  31166. [],
  31167. void 0,
  31168. // no return, assign body later
  31169. true,
  31170. // newline
  31171. false,
  31172. // suspense slots are not treated as normal slots
  31173. loc
  31174. );
  31175. wipEntry.wipSlots.push({
  31176. fn,
  31177. children
  31178. });
  31179. return fn;
  31180. }
  31181. ).slots;
  31182. }
  31183. };
  31184. }
  31185. function ssrProcessSuspense(node, context) {
  31186. const wipEntry = wipMap$3.get(node);
  31187. if (!wipEntry) {
  31188. return;
  31189. }
  31190. const { slotsExp, wipSlots } = wipEntry;
  31191. for (let i = 0; i < wipSlots.length; i++) {
  31192. const slot = wipSlots[i];
  31193. slot.fn.body = processChildrenAsStatement(slot, context);
  31194. }
  31195. context.pushStatement(
  31196. createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
  31197. `_push`,
  31198. slotsExp
  31199. ])
  31200. );
  31201. }
  31202. const rawChildrenMap = /* @__PURE__ */ new WeakMap();
  31203. const ssrTransformElement = (node, context) => {
  31204. if (node.type !== 1 || node.tagType !== 0) {
  31205. return;
  31206. }
  31207. return function ssrPostTransformElement() {
  31208. const openTag = [`<${node.tag}`];
  31209. const needTagForRuntime = node.tag === "textarea" || node.tag.indexOf("-") > 0;
  31210. const hasDynamicVBind = hasDynamicKeyVBind(node);
  31211. const hasCustomDir = node.props.some(
  31212. (p) => p.type === 7 && !isBuiltInDirective(p.name)
  31213. );
  31214. const vShowPropIndex = node.props.findIndex(
  31215. (i) => i.type === 7 && i.name === "show"
  31216. );
  31217. if (vShowPropIndex !== -1) {
  31218. const vShowProp = node.props[vShowPropIndex];
  31219. node.props.splice(vShowPropIndex, 1);
  31220. node.props.push(vShowProp);
  31221. }
  31222. const needMergeProps = hasDynamicVBind || hasCustomDir;
  31223. if (needMergeProps) {
  31224. const { props, directives } = buildProps(
  31225. node,
  31226. context,
  31227. node.props,
  31228. false,
  31229. false,
  31230. true
  31231. );
  31232. if (props || directives.length) {
  31233. const mergedProps = buildSSRProps(props, directives, context);
  31234. const propsExp = createCallExpression(
  31235. context.helper(SSR_RENDER_ATTRS),
  31236. [mergedProps]
  31237. );
  31238. if (node.tag === "textarea") {
  31239. const existingText = node.children[0];
  31240. if (!hasContentOverrideDirective(node) && (!existingText || existingText.type !== 5)) {
  31241. const tempId = `_temp${context.temps++}`;
  31242. propsExp.arguments = [
  31243. createAssignmentExpression(
  31244. createSimpleExpression(tempId, false),
  31245. mergedProps
  31246. )
  31247. ];
  31248. rawChildrenMap.set(
  31249. node,
  31250. createCallExpression(context.helper(SSR_INTERPOLATE), [
  31251. createConditionalExpression(
  31252. createSimpleExpression(`"value" in ${tempId}`, false),
  31253. createSimpleExpression(`${tempId}.value`, false),
  31254. createSimpleExpression(
  31255. existingText ? existingText.content : ``,
  31256. true
  31257. ),
  31258. false
  31259. )
  31260. ])
  31261. );
  31262. }
  31263. } else if (node.tag === "input") {
  31264. const vModel = findVModel(node);
  31265. if (vModel) {
  31266. const tempId = `_temp${context.temps++}`;
  31267. const tempExp = createSimpleExpression(tempId, false);
  31268. propsExp.arguments = [
  31269. createSequenceExpression([
  31270. createAssignmentExpression(tempExp, mergedProps),
  31271. createCallExpression(context.helper(MERGE_PROPS), [
  31272. tempExp,
  31273. createCallExpression(
  31274. context.helper(SSR_GET_DYNAMIC_MODEL_PROPS),
  31275. [
  31276. tempExp,
  31277. // existing props
  31278. vModel.exp
  31279. // model
  31280. ]
  31281. )
  31282. ])
  31283. ])
  31284. ];
  31285. }
  31286. } else if (directives.length && !node.children.length) {
  31287. if (!hasContentOverrideDirective(node)) {
  31288. const tempId = `_temp${context.temps++}`;
  31289. propsExp.arguments = [
  31290. createAssignmentExpression(
  31291. createSimpleExpression(tempId, false),
  31292. mergedProps
  31293. )
  31294. ];
  31295. rawChildrenMap.set(
  31296. node,
  31297. createConditionalExpression(
  31298. createSimpleExpression(`"textContent" in ${tempId}`, false),
  31299. createCallExpression(context.helper(SSR_INTERPOLATE), [
  31300. createSimpleExpression(`${tempId}.textContent`, false)
  31301. ]),
  31302. createSimpleExpression(`${tempId}.innerHTML ?? ''`, false),
  31303. false
  31304. )
  31305. );
  31306. }
  31307. }
  31308. if (needTagForRuntime) {
  31309. propsExp.arguments.push(`"${node.tag}"`);
  31310. }
  31311. openTag.push(propsExp);
  31312. }
  31313. }
  31314. let dynamicClassBinding = void 0;
  31315. let staticClassBinding = void 0;
  31316. let dynamicStyleBinding = void 0;
  31317. for (let i = 0; i < node.props.length; i++) {
  31318. const prop = node.props[i];
  31319. if (node.tag === "input" && isTrueFalseValue(prop)) {
  31320. continue;
  31321. }
  31322. if (prop.type === 7) {
  31323. if (prop.name === "html" && prop.exp) {
  31324. rawChildrenMap.set(
  31325. node,
  31326. createCompoundExpression([`(`, prop.exp, `) ?? ''`])
  31327. );
  31328. } else if (prop.name === "text" && prop.exp) {
  31329. node.children = [createInterpolation(prop.exp, prop.loc)];
  31330. } else if (prop.name === "slot") {
  31331. context.onError(
  31332. createCompilerError(40, prop.loc)
  31333. );
  31334. } else if (isTextareaWithValue(node, prop) && prop.exp) {
  31335. if (!needMergeProps) {
  31336. node.children = [createInterpolation(prop.exp, prop.loc)];
  31337. }
  31338. } else if (!needMergeProps && prop.name !== "on") {
  31339. const directiveTransform = context.directiveTransforms[prop.name];
  31340. if (directiveTransform) {
  31341. const { props, ssrTagParts } = directiveTransform(
  31342. prop,
  31343. node,
  31344. context
  31345. );
  31346. if (ssrTagParts) {
  31347. openTag.push(...ssrTagParts);
  31348. }
  31349. for (let j = 0; j < props.length; j++) {
  31350. const { key, value } = props[j];
  31351. if (isStaticExp(key)) {
  31352. let attrName = key.content;
  31353. if (attrName === "key" || attrName === "ref") {
  31354. continue;
  31355. }
  31356. if (attrName === "class") {
  31357. openTag.push(
  31358. ` class="`,
  31359. dynamicClassBinding = createCallExpression(
  31360. context.helper(SSR_RENDER_CLASS),
  31361. [value]
  31362. ),
  31363. `"`
  31364. );
  31365. } else if (attrName === "style") {
  31366. if (dynamicStyleBinding) {
  31367. mergeCall(dynamicStyleBinding, value);
  31368. } else {
  31369. openTag.push(
  31370. ` style="`,
  31371. dynamicStyleBinding = createCallExpression(
  31372. context.helper(SSR_RENDER_STYLE),
  31373. [value]
  31374. ),
  31375. `"`
  31376. );
  31377. }
  31378. } else {
  31379. attrName = node.tag.indexOf("-") > 0 ? attrName : propsToAttrMap[attrName] || attrName.toLowerCase();
  31380. if (isBooleanAttr(attrName)) {
  31381. openTag.push(
  31382. createConditionalExpression(
  31383. createCallExpression(
  31384. context.helper(SSR_INCLUDE_BOOLEAN_ATTR),
  31385. [value]
  31386. ),
  31387. createSimpleExpression(" " + attrName, true),
  31388. createSimpleExpression("", true),
  31389. false
  31390. )
  31391. );
  31392. } else if (isSSRSafeAttrName(attrName)) {
  31393. openTag.push(
  31394. createCallExpression(context.helper(SSR_RENDER_ATTR), [
  31395. key,
  31396. value
  31397. ])
  31398. );
  31399. } else {
  31400. context.onError(
  31401. createSSRCompilerError(
  31402. 65,
  31403. key.loc
  31404. )
  31405. );
  31406. }
  31407. }
  31408. } else {
  31409. const args = [key, value];
  31410. if (needTagForRuntime) {
  31411. args.push(`"${node.tag}"`);
  31412. }
  31413. openTag.push(
  31414. createCallExpression(
  31415. context.helper(SSR_RENDER_DYNAMIC_ATTR),
  31416. args
  31417. )
  31418. );
  31419. }
  31420. }
  31421. }
  31422. }
  31423. } else {
  31424. const name = prop.name;
  31425. if (node.tag === "textarea" && name === "value" && prop.value) {
  31426. rawChildrenMap.set(node, escapeHtml(prop.value.content));
  31427. } else if (!needMergeProps) {
  31428. if (name === "key" || name === "ref") {
  31429. continue;
  31430. }
  31431. if (name === "class" && prop.value) {
  31432. staticClassBinding = JSON.stringify(prop.value.content);
  31433. }
  31434. openTag.push(
  31435. ` ${prop.name}` + (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``)
  31436. );
  31437. }
  31438. }
  31439. }
  31440. if (dynamicClassBinding && staticClassBinding) {
  31441. mergeCall(dynamicClassBinding, staticClassBinding);
  31442. removeStaticBinding(openTag, "class");
  31443. }
  31444. if (context.scopeId) {
  31445. openTag.push(` ${context.scopeId}`);
  31446. }
  31447. node.ssrCodegenNode = createTemplateLiteral(openTag);
  31448. };
  31449. };
  31450. function buildSSRProps(props, directives, context) {
  31451. let mergePropsArgs = [];
  31452. if (props) {
  31453. if (props.type === 14) {
  31454. mergePropsArgs = props.arguments;
  31455. } else {
  31456. mergePropsArgs.push(props);
  31457. }
  31458. }
  31459. if (directives.length) {
  31460. for (const dir of directives) {
  31461. mergePropsArgs.push(
  31462. createCallExpression(context.helper(SSR_GET_DIRECTIVE_PROPS), [
  31463. `_ctx`,
  31464. ...buildDirectiveArgs(dir, context).elements
  31465. ])
  31466. );
  31467. }
  31468. }
  31469. return mergePropsArgs.length > 1 ? createCallExpression(context.helper(MERGE_PROPS), mergePropsArgs) : mergePropsArgs[0];
  31470. }
  31471. function isTrueFalseValue(prop) {
  31472. if (prop.type === 7) {
  31473. return prop.name === "bind" && prop.arg && isStaticExp(prop.arg) && (prop.arg.content === "true-value" || prop.arg.content === "false-value");
  31474. } else {
  31475. return prop.name === "true-value" || prop.name === "false-value";
  31476. }
  31477. }
  31478. function isTextareaWithValue(node, prop) {
  31479. return !!(node.tag === "textarea" && prop.name === "bind" && isStaticArgOf(prop.arg, "value"));
  31480. }
  31481. function mergeCall(call, arg) {
  31482. const existing = call.arguments[0];
  31483. if (existing.type === 17) {
  31484. existing.elements.push(arg);
  31485. } else {
  31486. call.arguments[0] = createArrayExpression([existing, arg]);
  31487. }
  31488. }
  31489. function removeStaticBinding(tag, binding) {
  31490. const regExp = new RegExp(`^ ${binding}=".+"$`);
  31491. const i = tag.findIndex((e) => typeof e === "string" && regExp.test(e));
  31492. if (i > -1) {
  31493. tag.splice(i, 1);
  31494. }
  31495. }
  31496. function findVModel(node) {
  31497. return node.props.find(
  31498. (p) => p.type === 7 && p.name === "model" && p.exp
  31499. );
  31500. }
  31501. function hasContentOverrideDirective(node) {
  31502. return !!findDir(node, "text") || !!findDir(node, "html");
  31503. }
  31504. function ssrProcessElement(node, context) {
  31505. const isVoidTag = context.options.isVoidTag || NO;
  31506. const elementsToAdd = node.ssrCodegenNode.elements;
  31507. for (let j = 0; j < elementsToAdd.length; j++) {
  31508. context.pushStringPart(elementsToAdd[j]);
  31509. }
  31510. if (context.withSlotScopeId) {
  31511. context.pushStringPart(createSimpleExpression(`_scopeId`, false));
  31512. }
  31513. context.pushStringPart(`>`);
  31514. const rawChildren = rawChildrenMap.get(node);
  31515. if (rawChildren) {
  31516. context.pushStringPart(rawChildren);
  31517. } else if (node.children.length) {
  31518. processChildren(node, context);
  31519. }
  31520. if (!isVoidTag(node.tag)) {
  31521. context.pushStringPart(`</${node.tag}>`);
  31522. }
  31523. }
  31524. const wipMap$2 = /* @__PURE__ */ new WeakMap();
  31525. function ssrTransformTransitionGroup(node, context) {
  31526. return () => {
  31527. const tag = findProp(node, "tag");
  31528. if (tag) {
  31529. const otherProps = node.props.filter((p) => p !== tag);
  31530. const { props, directives } = buildProps(
  31531. node,
  31532. context,
  31533. otherProps,
  31534. true,
  31535. false,
  31536. true
  31537. );
  31538. let propsExp = null;
  31539. if (props || directives.length) {
  31540. propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [
  31541. buildSSRProps(props, directives, context)
  31542. ]);
  31543. }
  31544. wipMap$2.set(node, {
  31545. tag,
  31546. propsExp,
  31547. scopeId: context.scopeId || null
  31548. });
  31549. }
  31550. };
  31551. }
  31552. function ssrProcessTransitionGroup(node, context) {
  31553. const entry = wipMap$2.get(node);
  31554. if (entry) {
  31555. const { tag, propsExp, scopeId } = entry;
  31556. if (tag.type === 7) {
  31557. context.pushStringPart(`<`);
  31558. context.pushStringPart(tag.exp);
  31559. if (propsExp) {
  31560. context.pushStringPart(propsExp);
  31561. }
  31562. if (scopeId) {
  31563. context.pushStringPart(` ${scopeId}`);
  31564. }
  31565. context.pushStringPart(`>`);
  31566. processChildren(
  31567. node,
  31568. context,
  31569. false,
  31570. /**
  31571. * TransitionGroup has the special runtime behavior of flattening and
  31572. * concatenating all children into a single fragment (in order for them to
  31573. * be patched using the same key map) so we need to account for that here
  31574. * by disabling nested fragment wrappers from being generated.
  31575. */
  31576. true,
  31577. /**
  31578. * TransitionGroup filters out comment children at runtime and thus
  31579. * doesn't expect comments to be present during hydration. We need to
  31580. * account for that by disabling the empty comment that is otherwise
  31581. * rendered for a falsy v-if that has no v-else specified. (#6715)
  31582. */
  31583. true
  31584. );
  31585. context.pushStringPart(`</`);
  31586. context.pushStringPart(tag.exp);
  31587. context.pushStringPart(`>`);
  31588. } else {
  31589. context.pushStringPart(`<${tag.value.content}`);
  31590. if (propsExp) {
  31591. context.pushStringPart(propsExp);
  31592. }
  31593. if (scopeId) {
  31594. context.pushStringPart(` ${scopeId}`);
  31595. }
  31596. context.pushStringPart(`>`);
  31597. processChildren(node, context, false, true, true);
  31598. context.pushStringPart(`</${tag.value.content}>`);
  31599. }
  31600. } else {
  31601. processChildren(node, context, true, true, true);
  31602. }
  31603. }
  31604. const wipMap$1 = /* @__PURE__ */ new WeakMap();
  31605. function ssrTransformTransition(node, context) {
  31606. return () => {
  31607. const appear = findProp(node, "appear", false, true);
  31608. wipMap$1.set(node, !!appear);
  31609. };
  31610. }
  31611. function ssrProcessTransition(node, context) {
  31612. node.children = node.children.filter((c) => c.type !== 3);
  31613. const appear = wipMap$1.get(node);
  31614. if (appear) {
  31615. context.pushStringPart(`<template>`);
  31616. processChildren(node, context, false, true);
  31617. context.pushStringPart(`</template>`);
  31618. } else {
  31619. processChildren(node, context, false, true);
  31620. }
  31621. }
  31622. var __defProp$8 = Object.defineProperty;
  31623. var __defProps$7 = Object.defineProperties;
  31624. var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
  31625. var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
  31626. var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
  31627. var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
  31628. var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  31629. var __spreadValues$8 = (a, b) => {
  31630. for (var prop in b || (b = {}))
  31631. if (__hasOwnProp$8.call(b, prop))
  31632. __defNormalProp$8(a, prop, b[prop]);
  31633. if (__getOwnPropSymbols$8)
  31634. for (var prop of __getOwnPropSymbols$8(b)) {
  31635. if (__propIsEnum$8.call(b, prop))
  31636. __defNormalProp$8(a, prop, b[prop]);
  31637. }
  31638. return a;
  31639. };
  31640. var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
  31641. const wipMap = /* @__PURE__ */ new WeakMap();
  31642. const WIP_SLOT = /* @__PURE__ */ Symbol();
  31643. const componentTypeMap = /* @__PURE__ */ new WeakMap();
  31644. const ssrTransformComponent = (node, context) => {
  31645. if (node.type !== 1 || node.tagType !== 1) {
  31646. return;
  31647. }
  31648. const component = resolveComponentType(
  31649. node,
  31650. context,
  31651. true
  31652. /* ssr */
  31653. );
  31654. const isDynamicComponent = isObject$2(component) && component.callee === RESOLVE_DYNAMIC_COMPONENT;
  31655. componentTypeMap.set(node, component);
  31656. if (isSymbol$1(component)) {
  31657. if (component === SUSPENSE) {
  31658. return ssrTransformSuspense(node, context);
  31659. } else if (component === TRANSITION_GROUP) {
  31660. return ssrTransformTransitionGroup(node, context);
  31661. } else if (component === TRANSITION) {
  31662. return ssrTransformTransition(node);
  31663. }
  31664. return;
  31665. }
  31666. const vnodeBranches = [];
  31667. const clonedNode = clone(node);
  31668. return function ssrPostTransformComponent() {
  31669. if (clonedNode.children.length) {
  31670. buildSlots(clonedNode, context, (props, vFor, children) => {
  31671. vnodeBranches.push(
  31672. createVNodeSlotBranch(props, vFor, children, context)
  31673. );
  31674. return createFunctionExpression(void 0);
  31675. });
  31676. }
  31677. let propsExp = `null`;
  31678. if (node.props.length) {
  31679. const { props, directives } = buildProps(
  31680. node,
  31681. context,
  31682. void 0,
  31683. true,
  31684. isDynamicComponent
  31685. );
  31686. if (props || directives.length) {
  31687. propsExp = buildSSRProps(props, directives, context);
  31688. }
  31689. }
  31690. const wipEntries = [];
  31691. wipMap.set(node, wipEntries);
  31692. const buildSSRSlotFn = (props, _vForExp, children, loc) => {
  31693. const param0 = props && stringifyExpression(props) || `_`;
  31694. const fn = createFunctionExpression(
  31695. [param0, `_push`, `_parent`, `_scopeId`],
  31696. void 0,
  31697. // no return, assign body later
  31698. true,
  31699. // newline
  31700. true,
  31701. // isSlot
  31702. loc
  31703. );
  31704. wipEntries.push({
  31705. type: WIP_SLOT,
  31706. fn,
  31707. children,
  31708. // also collect the corresponding vnode branch built earlier
  31709. vnodeBranch: vnodeBranches[wipEntries.length]
  31710. });
  31711. return fn;
  31712. };
  31713. const slots = node.children.length ? buildSlots(node, context, buildSSRSlotFn).slots : `null`;
  31714. if (typeof component !== "string") {
  31715. node.ssrCodegenNode = createCallExpression(
  31716. context.helper(SSR_RENDER_VNODE),
  31717. [
  31718. `_push`,
  31719. createCallExpression(context.helper(CREATE_VNODE), [
  31720. component,
  31721. propsExp,
  31722. slots
  31723. ]),
  31724. `_parent`
  31725. ]
  31726. );
  31727. } else {
  31728. node.ssrCodegenNode = createCallExpression(
  31729. context.helper(SSR_RENDER_COMPONENT),
  31730. [component, propsExp, slots, `_parent`]
  31731. );
  31732. }
  31733. };
  31734. };
  31735. function ssrProcessComponent(node, context, parent) {
  31736. const component = componentTypeMap.get(node);
  31737. if (!node.ssrCodegenNode) {
  31738. if (component === TELEPORT) {
  31739. return ssrProcessTeleport(node, context);
  31740. } else if (component === SUSPENSE) {
  31741. return ssrProcessSuspense(node, context);
  31742. } else if (component === TRANSITION_GROUP) {
  31743. return ssrProcessTransitionGroup(node, context);
  31744. } else {
  31745. if (parent.type === WIP_SLOT) {
  31746. context.pushStringPart(``);
  31747. }
  31748. if (component === TRANSITION) {
  31749. return ssrProcessTransition(node, context);
  31750. }
  31751. processChildren(node, context);
  31752. }
  31753. } else {
  31754. const wipEntries = wipMap.get(node) || [];
  31755. for (let i = 0; i < wipEntries.length; i++) {
  31756. const { fn, vnodeBranch } = wipEntries[i];
  31757. fn.body = createIfStatement(
  31758. createSimpleExpression(`_push`, false),
  31759. processChildrenAsStatement(
  31760. wipEntries[i],
  31761. context,
  31762. false,
  31763. true
  31764. ),
  31765. vnodeBranch
  31766. );
  31767. }
  31768. if (context.withSlotScopeId) {
  31769. node.ssrCodegenNode.arguments.push(`_scopeId`);
  31770. }
  31771. if (typeof component === "string") {
  31772. context.pushStatement(
  31773. createCallExpression(`_push`, [node.ssrCodegenNode])
  31774. );
  31775. } else {
  31776. context.pushStatement(node.ssrCodegenNode);
  31777. }
  31778. }
  31779. }
  31780. const rawOptionsMap = /* @__PURE__ */ new WeakMap();
  31781. const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
  31782. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
  31783. const vnodeDirectiveTransforms = __spreadValues$8(__spreadValues$8({}, baseDirectiveTransforms), DOMDirectiveTransforms);
  31784. function createVNodeSlotBranch(slotProps, vFor, children, parentContext) {
  31785. const rawOptions = rawOptionsMap.get(parentContext.root);
  31786. const subOptions = __spreadProps$7(__spreadValues$8({}, rawOptions), {
  31787. // overwrite with vnode-based transforms
  31788. nodeTransforms: [
  31789. ...vnodeNodeTransforms,
  31790. ...rawOptions.nodeTransforms || []
  31791. ],
  31792. directiveTransforms: __spreadValues$8(__spreadValues$8({}, vnodeDirectiveTransforms), rawOptions.directiveTransforms || {})
  31793. });
  31794. const wrapperProps = [];
  31795. if (slotProps) {
  31796. wrapperProps.push({
  31797. type: 7,
  31798. name: "slot",
  31799. exp: slotProps,
  31800. arg: void 0,
  31801. modifiers: [],
  31802. loc: locStub
  31803. });
  31804. }
  31805. if (vFor) {
  31806. wrapperProps.push(extend({}, vFor));
  31807. }
  31808. const wrapperNode = {
  31809. type: 1,
  31810. ns: 0,
  31811. tag: "template",
  31812. tagType: 3,
  31813. props: wrapperProps,
  31814. children,
  31815. loc: locStub,
  31816. codegenNode: void 0
  31817. };
  31818. subTransform(wrapperNode, subOptions, parentContext);
  31819. return createReturnStatement(children);
  31820. }
  31821. function subTransform(node, options, parentContext) {
  31822. const childRoot = createRoot([node]);
  31823. const childContext = createTransformContext(childRoot, options);
  31824. childContext.ssr = false;
  31825. childContext.scopes = __spreadValues$8({}, parentContext.scopes);
  31826. childContext.identifiers = __spreadValues$8({}, parentContext.identifiers);
  31827. childContext.imports = parentContext.imports;
  31828. traverseNode(childRoot, childContext);
  31829. ["helpers", "components", "directives"].forEach((key) => {
  31830. childContext[key].forEach((value, helperKey) => {
  31831. if (key === "helpers") {
  31832. const parentCount = parentContext.helpers.get(helperKey);
  31833. if (parentCount === void 0) {
  31834. parentContext.helpers.set(helperKey, value);
  31835. } else {
  31836. parentContext.helpers.set(helperKey, value + parentCount);
  31837. }
  31838. } else {
  31839. parentContext[key].add(value);
  31840. }
  31841. });
  31842. });
  31843. }
  31844. function clone(v) {
  31845. if (isArray$3(v)) {
  31846. return v.map(clone);
  31847. } else if (isPlainObject(v)) {
  31848. const res = {};
  31849. for (const key in v) {
  31850. res[key] = clone(v[key]);
  31851. }
  31852. return res;
  31853. } else {
  31854. return v;
  31855. }
  31856. }
  31857. function ssrCodegenTransform(ast, options) {
  31858. const context = createSSRTransformContext(ast, options);
  31859. if (options.ssrCssVars) {
  31860. const cssContext = createTransformContext(createRoot([]), options);
  31861. const varsExp = processExpression(
  31862. createSimpleExpression(options.ssrCssVars, false),
  31863. cssContext
  31864. );
  31865. context.body.push(
  31866. createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`])
  31867. );
  31868. Array.from(cssContext.helpers.keys()).forEach((helper) => {
  31869. ast.helpers.add(helper);
  31870. });
  31871. }
  31872. const isFragment = ast.children.length > 1 && ast.children.some((c) => !isText$1(c));
  31873. processChildren(ast, context, isFragment);
  31874. ast.codegenNode = createBlockStatement(context.body);
  31875. ast.ssrHelpers = Array.from(
  31876. /* @__PURE__ */ new Set([
  31877. ...Array.from(ast.helpers).filter((h) => h in ssrHelpers),
  31878. ...context.helpers
  31879. ])
  31880. );
  31881. ast.helpers = new Set(Array.from(ast.helpers).filter((h) => !(h in ssrHelpers)));
  31882. }
  31883. function createSSRTransformContext(root, options, helpers = /* @__PURE__ */ new Set(), withSlotScopeId = false) {
  31884. const body = [];
  31885. let currentString = null;
  31886. return {
  31887. root,
  31888. options,
  31889. body,
  31890. helpers,
  31891. withSlotScopeId,
  31892. onError: options.onError || ((e) => {
  31893. throw e;
  31894. }),
  31895. helper(name) {
  31896. helpers.add(name);
  31897. return name;
  31898. },
  31899. pushStringPart(part) {
  31900. if (!currentString) {
  31901. const currentCall = createCallExpression(`_push`);
  31902. body.push(currentCall);
  31903. currentString = createTemplateLiteral([]);
  31904. currentCall.arguments.push(currentString);
  31905. }
  31906. const bufferedElements = currentString.elements;
  31907. const lastItem = bufferedElements[bufferedElements.length - 1];
  31908. if (isString$1(part) && isString$1(lastItem)) {
  31909. bufferedElements[bufferedElements.length - 1] += part;
  31910. } else {
  31911. bufferedElements.push(part);
  31912. }
  31913. },
  31914. pushStatement(statement) {
  31915. currentString = null;
  31916. body.push(statement);
  31917. }
  31918. };
  31919. }
  31920. function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
  31921. return createSSRTransformContext(
  31922. parent.root,
  31923. parent.options,
  31924. parent.helpers,
  31925. withSlotScopeId
  31926. );
  31927. }
  31928. function processChildren(parent, context, asFragment = false, disableNestedFragments = false, disableComment = false) {
  31929. if (asFragment) {
  31930. context.pushStringPart(`<!--[-->`);
  31931. }
  31932. const { children } = parent;
  31933. for (let i = 0; i < children.length; i++) {
  31934. const child = children[i];
  31935. switch (child.type) {
  31936. case 1:
  31937. switch (child.tagType) {
  31938. case 0:
  31939. ssrProcessElement(child, context);
  31940. break;
  31941. case 1:
  31942. ssrProcessComponent(child, context, parent);
  31943. break;
  31944. case 2:
  31945. ssrProcessSlotOutlet(child, context);
  31946. break;
  31947. case 3:
  31948. break;
  31949. default:
  31950. context.onError(
  31951. createSSRCompilerError(
  31952. 67,
  31953. child.loc
  31954. )
  31955. );
  31956. const exhaustiveCheck2 = child;
  31957. return exhaustiveCheck2;
  31958. }
  31959. break;
  31960. case 2:
  31961. context.pushStringPart(escapeHtml(child.content));
  31962. break;
  31963. case 3:
  31964. if (!disableComment) {
  31965. context.pushStringPart(`<!--${child.content}-->`);
  31966. }
  31967. break;
  31968. case 5:
  31969. context.pushStringPart(
  31970. createCallExpression(context.helper(SSR_INTERPOLATE), [
  31971. child.content
  31972. ])
  31973. );
  31974. break;
  31975. case 9:
  31976. ssrProcessIf(child, context, disableNestedFragments, disableComment);
  31977. break;
  31978. case 11:
  31979. ssrProcessFor(child, context, disableNestedFragments);
  31980. break;
  31981. case 10:
  31982. break;
  31983. case 12:
  31984. case 8:
  31985. break;
  31986. default:
  31987. context.onError(
  31988. createSSRCompilerError(
  31989. 67,
  31990. child.loc
  31991. )
  31992. );
  31993. const exhaustiveCheck = child;
  31994. return exhaustiveCheck;
  31995. }
  31996. }
  31997. if (asFragment) {
  31998. context.pushStringPart(`<!--]-->`);
  31999. }
  32000. }
  32001. function processChildrenAsStatement(parent, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
  32002. const childContext = createChildContext(parentContext, withSlotScopeId);
  32003. processChildren(parent, childContext, asFragment);
  32004. return createBlockStatement(childContext.body);
  32005. }
  32006. const ssrTransformModel = (dir, node, context) => {
  32007. const model = dir.exp;
  32008. function checkDuplicatedValue() {
  32009. const value = findProp(node, "value");
  32010. if (value) {
  32011. context.onError(
  32012. createDOMCompilerError(
  32013. 61,
  32014. value.loc
  32015. )
  32016. );
  32017. }
  32018. }
  32019. const processSelectChildren = (children) => {
  32020. children.forEach((child) => {
  32021. if (child.type === 1) {
  32022. processOption(child);
  32023. } else if (child.type === 11) {
  32024. processSelectChildren(child.children);
  32025. } else if (child.type === 9) {
  32026. child.branches.forEach((b) => processSelectChildren(b.children));
  32027. }
  32028. });
  32029. };
  32030. function processOption(plainNode) {
  32031. if (plainNode.tag === "option") {
  32032. if (plainNode.props.findIndex((p) => p.name === "selected") === -1) {
  32033. const value = findValueBinding(plainNode);
  32034. plainNode.ssrCodegenNode.elements.push(
  32035. createConditionalExpression(
  32036. createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [
  32037. createConditionalExpression(
  32038. createCallExpression(`Array.isArray`, [model]),
  32039. createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  32040. model,
  32041. value
  32042. ]),
  32043. createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  32044. model,
  32045. value
  32046. ])
  32047. )
  32048. ]),
  32049. createSimpleExpression(" selected", true),
  32050. createSimpleExpression("", true),
  32051. false
  32052. )
  32053. );
  32054. }
  32055. } else if (plainNode.tag === "optgroup") {
  32056. processSelectChildren(plainNode.children);
  32057. }
  32058. }
  32059. if (node.tagType === 0) {
  32060. const res = { props: [] };
  32061. if (node.tag === "input") {
  32062. const defaultProps = [
  32063. // default value binding for text type inputs
  32064. createObjectProperty(`value`, model)
  32065. ];
  32066. const type = findProp(node, "type");
  32067. if (type) {
  32068. const value = findValueBinding(node);
  32069. if (type.type === 7) {
  32070. res.ssrTagParts = [
  32071. createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
  32072. type.exp,
  32073. model,
  32074. value
  32075. ])
  32076. ];
  32077. } else if (type.value) {
  32078. switch (type.value.content) {
  32079. case "radio":
  32080. res.props = [
  32081. createObjectProperty(
  32082. `checked`,
  32083. createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  32084. model,
  32085. value
  32086. ])
  32087. )
  32088. ];
  32089. break;
  32090. case "checkbox":
  32091. const trueValueBinding = findProp(node, "true-value");
  32092. if (trueValueBinding) {
  32093. const trueValue = trueValueBinding.type === 6 ? JSON.stringify(trueValueBinding.value.content) : trueValueBinding.exp;
  32094. res.props = [
  32095. createObjectProperty(
  32096. `checked`,
  32097. createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  32098. model,
  32099. trueValue
  32100. ])
  32101. )
  32102. ];
  32103. } else {
  32104. res.props = [
  32105. createObjectProperty(
  32106. `checked`,
  32107. createConditionalExpression(
  32108. createCallExpression(`Array.isArray`, [model]),
  32109. createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  32110. model,
  32111. value
  32112. ]),
  32113. model
  32114. )
  32115. )
  32116. ];
  32117. }
  32118. break;
  32119. case "file":
  32120. context.onError(
  32121. createDOMCompilerError(
  32122. 60,
  32123. dir.loc
  32124. )
  32125. );
  32126. break;
  32127. default:
  32128. checkDuplicatedValue();
  32129. res.props = defaultProps;
  32130. break;
  32131. }
  32132. }
  32133. } else if (hasDynamicKeyVBind(node)) ; else {
  32134. checkDuplicatedValue();
  32135. res.props = defaultProps;
  32136. }
  32137. } else if (node.tag === "textarea") {
  32138. checkDuplicatedValue();
  32139. node.children = [createInterpolation(model, model.loc)];
  32140. } else if (node.tag === "select") {
  32141. processSelectChildren(node.children);
  32142. } else {
  32143. context.onError(
  32144. createDOMCompilerError(
  32145. 58,
  32146. dir.loc
  32147. )
  32148. );
  32149. }
  32150. return res;
  32151. } else {
  32152. return transformModel$1(dir, node, context);
  32153. }
  32154. };
  32155. function findValueBinding(node) {
  32156. const valueBinding = findProp(node, "value");
  32157. return valueBinding ? valueBinding.type === 7 ? valueBinding.exp : createSimpleExpression(valueBinding.value.content, true) : createSimpleExpression(`null`, false);
  32158. }
  32159. const ssrTransformShow = (dir, node, context) => {
  32160. if (!dir.exp) {
  32161. context.onError(
  32162. createDOMCompilerError(62)
  32163. );
  32164. }
  32165. return {
  32166. props: [
  32167. createObjectProperty(
  32168. `style`,
  32169. createConditionalExpression(
  32170. dir.exp,
  32171. createSimpleExpression(`null`, false),
  32172. createObjectExpression([
  32173. createObjectProperty(
  32174. `display`,
  32175. createSimpleExpression(`none`, true)
  32176. )
  32177. ]),
  32178. false
  32179. )
  32180. )
  32181. ]
  32182. };
  32183. };
  32184. const filterChild = (node) => node.children.filter((n) => !isCommentOrWhitespace(n));
  32185. const hasSingleChild = (node) => filterChild(node).length === 1;
  32186. const ssrInjectFallthroughAttrs = (node, context) => {
  32187. if (node.type === 0) {
  32188. context.identifiers._attrs = 1;
  32189. }
  32190. if (node.type === 1 && node.tagType === 1 && (node.tag === "transition" || node.tag === "Transition" || node.tag === "KeepAlive" || node.tag === "keep-alive")) {
  32191. const rootChildren = filterChild(context.root);
  32192. if (rootChildren.length === 1 && rootChildren[0] === node) {
  32193. if (hasSingleChild(node)) {
  32194. injectFallthroughAttrs(node.children[0]);
  32195. }
  32196. return;
  32197. }
  32198. }
  32199. const parent = context.parent;
  32200. if (!parent || parent.type !== 0) {
  32201. return;
  32202. }
  32203. if (node.type === 10 && hasSingleChild(node)) {
  32204. let hasEncounteredIf = false;
  32205. for (const c of filterChild(parent)) {
  32206. if (c.type === 9 || c.type === 1 && findDir(c, "if")) {
  32207. if (hasEncounteredIf) return;
  32208. hasEncounteredIf = true;
  32209. } else if (
  32210. // node before v-if
  32211. !hasEncounteredIf || // non else nodes
  32212. !(c.type === 1 && findDir(c, /else/, true))
  32213. ) {
  32214. return;
  32215. }
  32216. }
  32217. injectFallthroughAttrs(node.children[0]);
  32218. } else if (hasSingleChild(parent)) {
  32219. injectFallthroughAttrs(node);
  32220. }
  32221. };
  32222. function injectFallthroughAttrs(node) {
  32223. if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) {
  32224. node.props.push({
  32225. type: 7,
  32226. name: "bind",
  32227. arg: void 0,
  32228. exp: createSimpleExpression(`_attrs`, false),
  32229. modifiers: [],
  32230. loc: locStub
  32231. });
  32232. }
  32233. }
  32234. const ssrInjectCssVars = (node, context) => {
  32235. if (!context.ssrCssVars) {
  32236. return;
  32237. }
  32238. if (node.type === 0) {
  32239. context.identifiers._cssVars = 1;
  32240. }
  32241. const parent = context.parent;
  32242. if (!parent || parent.type !== 0) {
  32243. return;
  32244. }
  32245. if (node.type === 10) {
  32246. for (const child of node.children) {
  32247. injectCssVars(child);
  32248. }
  32249. } else {
  32250. injectCssVars(node);
  32251. }
  32252. };
  32253. function injectCssVars(node) {
  32254. if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) {
  32255. if (node.tag === "suspense" || node.tag === "Suspense") {
  32256. for (const child of node.children) {
  32257. if (child.type === 1 && child.tagType === 3) {
  32258. child.children.forEach(injectCssVars);
  32259. } else {
  32260. injectCssVars(child);
  32261. }
  32262. }
  32263. } else {
  32264. node.props.push({
  32265. type: 7,
  32266. name: "bind",
  32267. arg: void 0,
  32268. exp: createSimpleExpression(`_cssVars`, false),
  32269. modifiers: [],
  32270. loc: locStub
  32271. });
  32272. }
  32273. }
  32274. }
  32275. var __defProp$7 = Object.defineProperty;
  32276. var __defProps$6 = Object.defineProperties;
  32277. var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
  32278. var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
  32279. var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
  32280. var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
  32281. var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  32282. var __spreadValues$7 = (a, b) => {
  32283. for (var prop in b || (b = {}))
  32284. if (__hasOwnProp$7.call(b, prop))
  32285. __defNormalProp$7(a, prop, b[prop]);
  32286. if (__getOwnPropSymbols$7)
  32287. for (var prop of __getOwnPropSymbols$7(b)) {
  32288. if (__propIsEnum$7.call(b, prop))
  32289. __defNormalProp$7(a, prop, b[prop]);
  32290. }
  32291. return a;
  32292. };
  32293. var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
  32294. function compile(source, options = {}) {
  32295. options = __spreadProps$6(__spreadValues$7(__spreadValues$7({}, options), parserOptions), {
  32296. ssr: true,
  32297. inSSR: true,
  32298. scopeId: options.mode === "function" ? null : options.scopeId,
  32299. // always prefix since compiler-ssr doesn't have size concern
  32300. prefixIdentifiers: true,
  32301. // disable optimizations that are unnecessary for ssr
  32302. cacheHandlers: false,
  32303. hoistStatic: false
  32304. });
  32305. const ast = typeof source === "string" ? baseParse(source, options) : source;
  32306. rawOptionsMap.set(ast, options);
  32307. transform(ast, __spreadProps$6(__spreadValues$7({}, options), {
  32308. hoistStatic: false,
  32309. nodeTransforms: [
  32310. transformVBindShorthand,
  32311. ssrTransformIf,
  32312. ssrTransformFor,
  32313. trackVForSlotScopes,
  32314. transformExpression,
  32315. ssrTransformSlotOutlet,
  32316. ssrInjectFallthroughAttrs,
  32317. ssrInjectCssVars,
  32318. ssrTransformElement,
  32319. ssrTransformComponent,
  32320. trackSlotScopes,
  32321. transformStyle,
  32322. ...options.nodeTransforms || []
  32323. // user transforms
  32324. ],
  32325. directiveTransforms: __spreadValues$7({
  32326. // reusing core v-bind
  32327. bind: transformBind,
  32328. on: transformOn$1,
  32329. // model and show have dedicated SSR handling
  32330. model: ssrTransformModel,
  32331. show: ssrTransformShow,
  32332. // the following are ignored during SSR
  32333. // on: noopDirectiveTransform,
  32334. cloak: noopDirectiveTransform,
  32335. once: noopDirectiveTransform,
  32336. memo: noopDirectiveTransform
  32337. }, options.directiveTransforms || {})
  32338. }));
  32339. ssrCodegenTransform(ast, options);
  32340. return generate(ast, options);
  32341. }
  32342. var CompilerSSR = /*#__PURE__*/Object.freeze({
  32343. __proto__: null,
  32344. compile: compile
  32345. });
  32346. var _polyfillNode_fs = {};
  32347. var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({
  32348. __proto__: null,
  32349. default: _polyfillNode_fs
  32350. });
  32351. var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1);
  32352. var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path);
  32353. var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1);
  32354. const hasWarned = {};
  32355. function warnOnce$1(msg) {
  32356. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  32357. if (!isNodeProd && true && !hasWarned[msg]) {
  32358. hasWarned[msg] = true;
  32359. warn(msg);
  32360. }
  32361. }
  32362. function warn(msg) {
  32363. console.warn(
  32364. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  32365. `
  32366. );
  32367. }
  32368. var __defProp$6 = Object.defineProperty;
  32369. var __defProps$5 = Object.defineProperties;
  32370. var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
  32371. var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
  32372. var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
  32373. var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
  32374. var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  32375. var __spreadValues$6 = (a, b) => {
  32376. for (var prop in b || (b = {}))
  32377. if (__hasOwnProp$6.call(b, prop))
  32378. __defNormalProp$6(a, prop, b[prop]);
  32379. if (__getOwnPropSymbols$6)
  32380. for (var prop of __getOwnPropSymbols$6(b)) {
  32381. if (__propIsEnum$6.call(b, prop))
  32382. __defNormalProp$6(a, prop, b[prop]);
  32383. }
  32384. return a;
  32385. };
  32386. var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
  32387. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  32388. let res = "";
  32389. let err = null;
  32390. preprocessor.render(
  32391. source,
  32392. __spreadValues$6({ filename }, preprocessOptions),
  32393. (_err, _res) => {
  32394. if (_err) err = _err;
  32395. res = _res;
  32396. }
  32397. );
  32398. if (err) throw err;
  32399. return res;
  32400. }
  32401. function compileTemplate(options) {
  32402. const { preprocessLang, preprocessCustomRequire } = options;
  32403. if (preprocessLang && !preprocessCustomRequire) {
  32404. throw new Error(
  32405. `[@vue/compiler-sfc] Template preprocessing in the browser build must provide the \`preprocessCustomRequire\` option to return the in-browser version of the preprocessor in the shape of { render(): string }.`
  32406. );
  32407. }
  32408. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : void 0 : false;
  32409. if (preprocessor) {
  32410. try {
  32411. return doCompileTemplate(__spreadProps$5(__spreadValues$6({}, options), {
  32412. source: preprocess$1(options, preprocessor),
  32413. ast: void 0
  32414. // invalidate AST if template goes through preprocessor
  32415. }));
  32416. } catch (e) {
  32417. return {
  32418. code: `export default function render() {}`,
  32419. source: options.source,
  32420. tips: [],
  32421. errors: [e]
  32422. };
  32423. }
  32424. } else if (preprocessLang) {
  32425. return {
  32426. code: `export default function render() {}`,
  32427. source: options.source,
  32428. tips: [
  32429. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  32430. ],
  32431. errors: [
  32432. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  32433. ]
  32434. };
  32435. } else {
  32436. return doCompileTemplate(options);
  32437. }
  32438. }
  32439. function doCompileTemplate({
  32440. filename,
  32441. id,
  32442. scoped,
  32443. slotted,
  32444. inMap,
  32445. source,
  32446. ast: inAST,
  32447. ssr = false,
  32448. ssrCssVars,
  32449. isProd = false,
  32450. compiler,
  32451. compilerOptions = {},
  32452. transformAssetUrls
  32453. }) {
  32454. const errors = [];
  32455. const warnings = [];
  32456. let nodeTransforms = [];
  32457. if (isObject$2(transformAssetUrls)) {
  32458. const assetOptions = normalizeOptions(transformAssetUrls);
  32459. nodeTransforms = [
  32460. createAssetUrlTransformWithOptions(assetOptions),
  32461. createSrcsetTransformWithOptions(assetOptions)
  32462. ];
  32463. } else if (transformAssetUrls !== false) {
  32464. nodeTransforms = [transformAssetUrl, transformSrcset];
  32465. }
  32466. if (ssr && !ssrCssVars) {
  32467. warnOnce$1(
  32468. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  32469. );
  32470. }
  32471. if (!id) {
  32472. warnOnce$1(`compileTemplate now requires the \`id\` option.`);
  32473. id = "";
  32474. }
  32475. const shortId = id.replace(/^data-v-/, "");
  32476. const longId = `data-v-${shortId}`;
  32477. const defaultCompiler = ssr ? CompilerSSR : CompilerDOM;
  32478. compiler = compiler || defaultCompiler;
  32479. if (compiler !== defaultCompiler) {
  32480. inAST = void 0;
  32481. }
  32482. if (inAST == null ? void 0 : inAST.transformed) {
  32483. const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, __spreadProps$5(__spreadValues$6({
  32484. prefixIdentifiers: true
  32485. }, compilerOptions), {
  32486. parseMode: "sfc",
  32487. onError: (e) => errors.push(e)
  32488. }));
  32489. const template = newAST.children.find(
  32490. (node) => node.type === 1 && node.tag === "template"
  32491. );
  32492. inAST = createRoot(template.children, inAST.source);
  32493. }
  32494. let { code, ast, preamble, map } = compiler.compile(inAST || source, __spreadProps$5(__spreadValues$6({
  32495. mode: "module",
  32496. prefixIdentifiers: true,
  32497. hoistStatic: true,
  32498. cacheHandlers: true,
  32499. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  32500. scopeId: scoped ? longId : void 0,
  32501. slotted,
  32502. sourceMap: true
  32503. }, compilerOptions), {
  32504. hmr: !isProd,
  32505. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  32506. filename,
  32507. onError: (e) => errors.push(e),
  32508. onWarn: (w) => warnings.push(w)
  32509. }));
  32510. if (inMap && !inAST) {
  32511. if (map) {
  32512. map = mapLines(inMap, map);
  32513. }
  32514. if (errors.length) {
  32515. patchErrors(errors, source, inMap);
  32516. }
  32517. }
  32518. const tips = warnings.map((w) => {
  32519. let msg = w.message;
  32520. if (w.loc) {
  32521. msg += `
  32522. ${generateCodeFrame(
  32523. (inAST == null ? void 0 : inAST.source) || source,
  32524. w.loc.start.offset,
  32525. w.loc.end.offset
  32526. )}`;
  32527. }
  32528. return msg;
  32529. });
  32530. return { code, ast, preamble, source, errors, tips, map };
  32531. }
  32532. function mapLines(oldMap, newMap) {
  32533. if (!oldMap) return newMap;
  32534. if (!newMap) return oldMap;
  32535. const oldMapConsumer = new sourceMapExports.SourceMapConsumer(oldMap);
  32536. const newMapConsumer = new sourceMapExports.SourceMapConsumer(newMap);
  32537. const mergedMapGenerator = new sourceMapExports.SourceMapGenerator();
  32538. newMapConsumer.eachMapping((m) => {
  32539. if (m.originalLine == null) {
  32540. return;
  32541. }
  32542. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  32543. line: m.originalLine,
  32544. column: m.originalColumn
  32545. });
  32546. if (origPosInOldMap.source == null) {
  32547. return;
  32548. }
  32549. mergedMapGenerator.addMapping({
  32550. generated: {
  32551. line: m.generatedLine,
  32552. column: m.generatedColumn
  32553. },
  32554. original: {
  32555. line: origPosInOldMap.line,
  32556. // map line
  32557. // use current column, since the oldMap produced by @vue/compiler-sfc
  32558. // does not
  32559. column: m.originalColumn
  32560. },
  32561. source: origPosInOldMap.source,
  32562. name: origPosInOldMap.name
  32563. });
  32564. });
  32565. const generator = mergedMapGenerator;
  32566. oldMapConsumer.sources.forEach((sourceFile) => {
  32567. generator._sources.add(sourceFile);
  32568. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  32569. if (sourceContent != null) {
  32570. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  32571. }
  32572. });
  32573. generator._sourceRoot = oldMap.sourceRoot;
  32574. generator._file = oldMap.file;
  32575. return generator.toJSON();
  32576. }
  32577. function patchErrors(errors, source, inMap) {
  32578. const originalSource = inMap.sourcesContent[0];
  32579. const offset = originalSource.indexOf(source);
  32580. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  32581. errors.forEach((err) => {
  32582. if (err.loc) {
  32583. err.loc.start.line += lineOffset;
  32584. err.loc.start.offset += offset;
  32585. if (err.loc.end !== err.loc.start) {
  32586. err.loc.end.line += lineOffset;
  32587. err.loc.end.offset += offset;
  32588. }
  32589. }
  32590. });
  32591. }
  32592. var picocolors = {exports: {}};
  32593. var hasRequiredPicocolors;
  32594. function requirePicocolors () {
  32595. if (hasRequiredPicocolors) return picocolors.exports;
  32596. hasRequiredPicocolors = 1;
  32597. let p = browser$1 || {}, argv = p.argv || [], env = p.env || {};
  32598. let isColorSupported =
  32599. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  32600. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  32601. let formatter = (open, close, replace = open) =>
  32602. input => {
  32603. let string = "" + input, index = string.indexOf(close, open.length);
  32604. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  32605. };
  32606. let replaceClose = (string, close, replace, index) => {
  32607. let result = "", cursor = 0;
  32608. do {
  32609. result += string.substring(cursor, index) + replace;
  32610. cursor = index + close.length;
  32611. index = string.indexOf(close, cursor);
  32612. } while (~index)
  32613. return result + string.substring(cursor)
  32614. };
  32615. let createColors = (enabled = isColorSupported) => {
  32616. let f = enabled ? formatter : () => String;
  32617. return {
  32618. isColorSupported: enabled,
  32619. reset: f("\x1b[0m", "\x1b[0m"),
  32620. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  32621. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  32622. italic: f("\x1b[3m", "\x1b[23m"),
  32623. underline: f("\x1b[4m", "\x1b[24m"),
  32624. inverse: f("\x1b[7m", "\x1b[27m"),
  32625. hidden: f("\x1b[8m", "\x1b[28m"),
  32626. strikethrough: f("\x1b[9m", "\x1b[29m"),
  32627. black: f("\x1b[30m", "\x1b[39m"),
  32628. red: f("\x1b[31m", "\x1b[39m"),
  32629. green: f("\x1b[32m", "\x1b[39m"),
  32630. yellow: f("\x1b[33m", "\x1b[39m"),
  32631. blue: f("\x1b[34m", "\x1b[39m"),
  32632. magenta: f("\x1b[35m", "\x1b[39m"),
  32633. cyan: f("\x1b[36m", "\x1b[39m"),
  32634. white: f("\x1b[37m", "\x1b[39m"),
  32635. gray: f("\x1b[90m", "\x1b[39m"),
  32636. bgBlack: f("\x1b[40m", "\x1b[49m"),
  32637. bgRed: f("\x1b[41m", "\x1b[49m"),
  32638. bgGreen: f("\x1b[42m", "\x1b[49m"),
  32639. bgYellow: f("\x1b[43m", "\x1b[49m"),
  32640. bgBlue: f("\x1b[44m", "\x1b[49m"),
  32641. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  32642. bgCyan: f("\x1b[46m", "\x1b[49m"),
  32643. bgWhite: f("\x1b[47m", "\x1b[49m"),
  32644. blackBright: f("\x1b[90m", "\x1b[39m"),
  32645. redBright: f("\x1b[91m", "\x1b[39m"),
  32646. greenBright: f("\x1b[92m", "\x1b[39m"),
  32647. yellowBright: f("\x1b[93m", "\x1b[39m"),
  32648. blueBright: f("\x1b[94m", "\x1b[39m"),
  32649. magentaBright: f("\x1b[95m", "\x1b[39m"),
  32650. cyanBright: f("\x1b[96m", "\x1b[39m"),
  32651. whiteBright: f("\x1b[97m", "\x1b[39m"),
  32652. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  32653. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  32654. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  32655. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  32656. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  32657. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  32658. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  32659. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  32660. }
  32661. };
  32662. picocolors.exports = createColors();
  32663. picocolors.exports.createColors = createColors;
  32664. return picocolors.exports;
  32665. }
  32666. var tokenize$1;
  32667. var hasRequiredTokenize$1;
  32668. function requireTokenize$1 () {
  32669. if (hasRequiredTokenize$1) return tokenize$1;
  32670. hasRequiredTokenize$1 = 1;
  32671. const SINGLE_QUOTE = "'".charCodeAt(0);
  32672. const DOUBLE_QUOTE = '"'.charCodeAt(0);
  32673. const BACKSLASH = '\\'.charCodeAt(0);
  32674. const SLASH = '/'.charCodeAt(0);
  32675. const NEWLINE = '\n'.charCodeAt(0);
  32676. const SPACE = ' '.charCodeAt(0);
  32677. const FEED = '\f'.charCodeAt(0);
  32678. const TAB = '\t'.charCodeAt(0);
  32679. const CR = '\r'.charCodeAt(0);
  32680. const OPEN_SQUARE = '['.charCodeAt(0);
  32681. const CLOSE_SQUARE = ']'.charCodeAt(0);
  32682. const OPEN_PARENTHESES = '('.charCodeAt(0);
  32683. const CLOSE_PARENTHESES = ')'.charCodeAt(0);
  32684. const OPEN_CURLY = '{'.charCodeAt(0);
  32685. const CLOSE_CURLY = '}'.charCodeAt(0);
  32686. const SEMICOLON = ';'.charCodeAt(0);
  32687. const ASTERISK = '*'.charCodeAt(0);
  32688. const COLON = ':'.charCodeAt(0);
  32689. const AT = '@'.charCodeAt(0);
  32690. const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
  32691. const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
  32692. const RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
  32693. const RE_HEX_ESCAPE = /[\da-f]/i;
  32694. tokenize$1 = function tokenizer(input, options = {}) {
  32695. let css = input.css.valueOf();
  32696. let ignore = options.ignoreErrors;
  32697. let code, content, escape, next, quote;
  32698. let currentToken, escaped, escapePos, n, prev;
  32699. let length = css.length;
  32700. let pos = 0;
  32701. let buffer = [];
  32702. let returned = [];
  32703. let lastBadParen = -1;
  32704. function position() {
  32705. return pos
  32706. }
  32707. function unclosed(what) {
  32708. throw input.error('Unclosed ' + what, pos)
  32709. }
  32710. function endOfFile() {
  32711. return returned.length === 0 && pos >= length
  32712. }
  32713. function nextToken(opts) {
  32714. if (returned.length) return returned.pop()
  32715. if (pos >= length) return
  32716. let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
  32717. code = css.charCodeAt(pos);
  32718. switch (code) {
  32719. case NEWLINE:
  32720. case SPACE:
  32721. case TAB:
  32722. case CR:
  32723. case FEED: {
  32724. next = pos;
  32725. do {
  32726. next += 1;
  32727. code = css.charCodeAt(next);
  32728. } while (
  32729. code === SPACE ||
  32730. code === NEWLINE ||
  32731. code === TAB ||
  32732. code === CR ||
  32733. code === FEED
  32734. )
  32735. currentToken = ['space', css.slice(pos, next)];
  32736. pos = next - 1;
  32737. break
  32738. }
  32739. case OPEN_SQUARE:
  32740. case CLOSE_SQUARE:
  32741. case OPEN_CURLY:
  32742. case CLOSE_CURLY:
  32743. case COLON:
  32744. case SEMICOLON:
  32745. case CLOSE_PARENTHESES: {
  32746. let controlChar = String.fromCharCode(code);
  32747. currentToken = [controlChar, controlChar, pos];
  32748. break
  32749. }
  32750. case OPEN_PARENTHESES: {
  32751. prev = buffer.length ? buffer.pop()[1] : '';
  32752. n = css.charCodeAt(pos + 1);
  32753. if (
  32754. prev === 'url' &&
  32755. n !== SINGLE_QUOTE &&
  32756. n !== DOUBLE_QUOTE &&
  32757. n !== SPACE &&
  32758. n !== NEWLINE &&
  32759. n !== TAB &&
  32760. n !== FEED &&
  32761. n !== CR
  32762. ) {
  32763. next = pos;
  32764. do {
  32765. escaped = false;
  32766. next = css.indexOf(')', next + 1);
  32767. if (next === -1) {
  32768. if (ignore || ignoreUnclosed) {
  32769. next = pos;
  32770. break
  32771. } else {
  32772. unclosed('bracket');
  32773. }
  32774. }
  32775. escapePos = next;
  32776. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  32777. escapePos -= 1;
  32778. escaped = !escaped;
  32779. }
  32780. } while (escaped)
  32781. currentToken = ['brackets', css.slice(pos, next + 1), pos, next];
  32782. pos = next;
  32783. } else if (pos <= lastBadParen) {
  32784. currentToken = ['(', '(', pos];
  32785. } else {
  32786. next = css.indexOf(')', pos + 1);
  32787. content = css.slice(pos, next + 1);
  32788. if (next === -1 || RE_BAD_BRACKET.test(content)) {
  32789. lastBadParen = next === -1 ? length : next;
  32790. currentToken = ['(', '(', pos];
  32791. } else {
  32792. currentToken = ['brackets', content, pos, next];
  32793. pos = next;
  32794. }
  32795. }
  32796. break
  32797. }
  32798. case SINGLE_QUOTE:
  32799. case DOUBLE_QUOTE: {
  32800. quote = code === SINGLE_QUOTE ? "'" : '"';
  32801. next = pos;
  32802. do {
  32803. escaped = false;
  32804. next = css.indexOf(quote, next + 1);
  32805. if (next === -1) {
  32806. if (ignore || ignoreUnclosed) {
  32807. next = pos + 1;
  32808. break
  32809. } else {
  32810. unclosed('string');
  32811. }
  32812. }
  32813. escapePos = next;
  32814. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  32815. escapePos -= 1;
  32816. escaped = !escaped;
  32817. }
  32818. } while (escaped)
  32819. currentToken = ['string', css.slice(pos, next + 1), pos, next];
  32820. pos = next;
  32821. break
  32822. }
  32823. case AT: {
  32824. RE_AT_END.lastIndex = pos + 1;
  32825. RE_AT_END.test(css);
  32826. if (RE_AT_END.lastIndex === 0) {
  32827. next = css.length - 1;
  32828. } else {
  32829. next = RE_AT_END.lastIndex - 2;
  32830. }
  32831. currentToken = ['at-word', css.slice(pos, next + 1), pos, next];
  32832. pos = next;
  32833. break
  32834. }
  32835. case BACKSLASH: {
  32836. next = pos;
  32837. escape = true;
  32838. while (css.charCodeAt(next + 1) === BACKSLASH) {
  32839. next += 1;
  32840. escape = !escape;
  32841. }
  32842. code = css.charCodeAt(next + 1);
  32843. if (
  32844. escape &&
  32845. code !== SLASH &&
  32846. code !== SPACE &&
  32847. code !== NEWLINE &&
  32848. code !== TAB &&
  32849. code !== CR &&
  32850. code !== FEED
  32851. ) {
  32852. next += 1;
  32853. if (RE_HEX_ESCAPE.test(css.charAt(next))) {
  32854. while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
  32855. next += 1;
  32856. }
  32857. if (css.charCodeAt(next + 1) === SPACE) {
  32858. next += 1;
  32859. }
  32860. }
  32861. }
  32862. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  32863. pos = next;
  32864. break
  32865. }
  32866. default: {
  32867. if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
  32868. next = css.indexOf('*/', pos + 2) + 1;
  32869. if (next === 0) {
  32870. if (ignore || ignoreUnclosed) {
  32871. next = css.length;
  32872. } else {
  32873. unclosed('comment');
  32874. }
  32875. }
  32876. currentToken = ['comment', css.slice(pos, next + 1), pos, next];
  32877. pos = next;
  32878. } else {
  32879. RE_WORD_END.lastIndex = pos + 1;
  32880. RE_WORD_END.test(css);
  32881. if (RE_WORD_END.lastIndex === 0) {
  32882. next = css.length - 1;
  32883. } else {
  32884. next = RE_WORD_END.lastIndex - 2;
  32885. }
  32886. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  32887. buffer.push(currentToken);
  32888. pos = next;
  32889. }
  32890. break
  32891. }
  32892. }
  32893. pos++;
  32894. return currentToken
  32895. }
  32896. function back(token) {
  32897. returned.push(token);
  32898. }
  32899. return {
  32900. back,
  32901. endOfFile,
  32902. nextToken,
  32903. position
  32904. }
  32905. };
  32906. return tokenize$1;
  32907. }
  32908. var terminalHighlight_1;
  32909. var hasRequiredTerminalHighlight;
  32910. function requireTerminalHighlight () {
  32911. if (hasRequiredTerminalHighlight) return terminalHighlight_1;
  32912. hasRequiredTerminalHighlight = 1;
  32913. let pico = /*@__PURE__*/ requirePicocolors();
  32914. let tokenizer = /*@__PURE__*/ requireTokenize$1();
  32915. let Input;
  32916. function registerInput(dependant) {
  32917. Input = dependant;
  32918. }
  32919. const HIGHLIGHT_THEME = {
  32920. ';': pico.yellow,
  32921. ':': pico.yellow,
  32922. '(': pico.cyan,
  32923. ')': pico.cyan,
  32924. '[': pico.yellow,
  32925. ']': pico.yellow,
  32926. '{': pico.yellow,
  32927. '}': pico.yellow,
  32928. 'at-word': pico.cyan,
  32929. 'brackets': pico.cyan,
  32930. 'call': pico.cyan,
  32931. 'class': pico.yellow,
  32932. 'comment': pico.gray,
  32933. 'hash': pico.magenta,
  32934. 'string': pico.green
  32935. };
  32936. function getTokenType([type, value], processor) {
  32937. if (type === 'word') {
  32938. if (value[0] === '.') {
  32939. return 'class'
  32940. }
  32941. if (value[0] === '#') {
  32942. return 'hash'
  32943. }
  32944. }
  32945. if (!processor.endOfFile()) {
  32946. let next = processor.nextToken();
  32947. processor.back(next);
  32948. if (next[0] === 'brackets' || next[0] === '(') return 'call'
  32949. }
  32950. return type
  32951. }
  32952. function terminalHighlight(css) {
  32953. let processor = tokenizer(new Input(css), { ignoreErrors: true });
  32954. let result = '';
  32955. while (!processor.endOfFile()) {
  32956. let token = processor.nextToken();
  32957. let color = HIGHLIGHT_THEME[getTokenType(token, processor)];
  32958. if (color) {
  32959. result += token[1]
  32960. .split(/\r?\n/)
  32961. .map(i => color(i))
  32962. .join('\n');
  32963. } else {
  32964. result += token[1];
  32965. }
  32966. }
  32967. return result
  32968. }
  32969. terminalHighlight.registerInput = registerInput;
  32970. terminalHighlight_1 = terminalHighlight;
  32971. return terminalHighlight_1;
  32972. }
  32973. var cssSyntaxError;
  32974. var hasRequiredCssSyntaxError;
  32975. function requireCssSyntaxError () {
  32976. if (hasRequiredCssSyntaxError) return cssSyntaxError;
  32977. hasRequiredCssSyntaxError = 1;
  32978. let pico = /*@__PURE__*/ requirePicocolors();
  32979. let terminalHighlight = /*@__PURE__*/ requireTerminalHighlight();
  32980. class CssSyntaxError extends Error {
  32981. constructor(message, line, column, source, file, plugin) {
  32982. super(message);
  32983. this.name = 'CssSyntaxError';
  32984. this.reason = message;
  32985. if (file) {
  32986. this.file = file;
  32987. }
  32988. if (source) {
  32989. this.source = source;
  32990. }
  32991. if (plugin) {
  32992. this.plugin = plugin;
  32993. }
  32994. if (typeof line !== 'undefined' && typeof column !== 'undefined') {
  32995. if (typeof line === 'number') {
  32996. this.line = line;
  32997. this.column = column;
  32998. } else {
  32999. this.line = line.line;
  33000. this.column = line.column;
  33001. this.endLine = column.line;
  33002. this.endColumn = column.column;
  33003. }
  33004. }
  33005. this.setMessage();
  33006. if (Error.captureStackTrace) {
  33007. Error.captureStackTrace(this, CssSyntaxError);
  33008. }
  33009. }
  33010. setMessage() {
  33011. this.message = this.plugin ? this.plugin + ': ' : '';
  33012. this.message += this.file ? this.file : '<css input>';
  33013. if (typeof this.line !== 'undefined') {
  33014. this.message += ':' + this.line + ':' + this.column;
  33015. }
  33016. this.message += ': ' + this.reason;
  33017. }
  33018. showSourceCode(color) {
  33019. if (!this.source) return ''
  33020. let css = this.source;
  33021. if (color == null) color = pico.isColorSupported;
  33022. let aside = text => text;
  33023. let mark = text => text;
  33024. let highlight = text => text;
  33025. if (color) {
  33026. let { bold, gray, red } = pico.createColors(true);
  33027. mark = text => bold(red(text));
  33028. aside = text => gray(text);
  33029. if (terminalHighlight) {
  33030. highlight = text => terminalHighlight(text);
  33031. }
  33032. }
  33033. let lines = css.split(/\r?\n/);
  33034. let start = Math.max(this.line - 3, 0);
  33035. let end = Math.min(this.line + 2, lines.length);
  33036. let maxWidth = String(end).length;
  33037. return lines
  33038. .slice(start, end)
  33039. .map((line, index) => {
  33040. let number = start + 1 + index;
  33041. let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
  33042. if (number === this.line) {
  33043. if (line.length > 160) {
  33044. let padding = 20;
  33045. let subLineStart = Math.max(0, this.column - padding);
  33046. let subLineEnd = Math.max(
  33047. this.column + padding,
  33048. this.endColumn + padding
  33049. );
  33050. let subLine = line.slice(subLineStart, subLineEnd);
  33051. let spacing =
  33052. aside(gutter.replace(/\d/g, ' ')) +
  33053. line
  33054. .slice(0, Math.min(this.column - 1, padding - 1))
  33055. .replace(/[^\t]/g, ' ');
  33056. return (
  33057. mark('>') +
  33058. aside(gutter) +
  33059. highlight(subLine) +
  33060. '\n ' +
  33061. spacing +
  33062. mark('^')
  33063. )
  33064. }
  33065. let spacing =
  33066. aside(gutter.replace(/\d/g, ' ')) +
  33067. line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
  33068. return (
  33069. mark('>') +
  33070. aside(gutter) +
  33071. highlight(line) +
  33072. '\n ' +
  33073. spacing +
  33074. mark('^')
  33075. )
  33076. }
  33077. return ' ' + aside(gutter) + highlight(line)
  33078. })
  33079. .join('\n')
  33080. }
  33081. toString() {
  33082. let code = this.showSourceCode();
  33083. if (code) {
  33084. code = '\n\n' + code + '\n';
  33085. }
  33086. return this.name + ': ' + this.message + code
  33087. }
  33088. }
  33089. cssSyntaxError = CssSyntaxError;
  33090. CssSyntaxError.default = CssSyntaxError;
  33091. return cssSyntaxError;
  33092. }
  33093. var stringifier;
  33094. var hasRequiredStringifier;
  33095. function requireStringifier () {
  33096. if (hasRequiredStringifier) return stringifier;
  33097. hasRequiredStringifier = 1;
  33098. // Escapes sequences that could break out of an HTML <style> context.
  33099. // Uses CSS unicode escaping (\3c = '<') which is valid CSS and parsed
  33100. // correctly by all compliant CSS consumers.
  33101. const STYLE_TAG = /(<)(\/?style\b)/gi;
  33102. const COMMENT_OPEN = /(<)(!--)/g;
  33103. function escapeHTMLInCSS(str) {
  33104. if (typeof str !== 'string') return str
  33105. if (!str.includes('<')) return str
  33106. return str.replace(STYLE_TAG, '\\3c $2').replace(COMMENT_OPEN, '\\3c $2')
  33107. }
  33108. const DEFAULT_RAW = {
  33109. after: '\n',
  33110. beforeClose: '\n',
  33111. beforeComment: '\n',
  33112. beforeDecl: '\n',
  33113. beforeOpen: ' ',
  33114. beforeRule: '\n',
  33115. colon: ': ',
  33116. commentLeft: ' ',
  33117. commentRight: ' ',
  33118. emptyBody: '',
  33119. indent: ' ',
  33120. semicolon: false
  33121. };
  33122. function capitalize(str) {
  33123. return str[0].toUpperCase() + str.slice(1)
  33124. }
  33125. class Stringifier {
  33126. constructor(builder) {
  33127. this.builder = builder;
  33128. }
  33129. atrule(node, semicolon) {
  33130. let raws = node.raws;
  33131. let name = '@' + node.name;
  33132. let params = node.params ? this.rawValue(node, 'params') : '';
  33133. if (typeof raws.afterName !== 'undefined') {
  33134. name += raws.afterName;
  33135. } else if (params) {
  33136. name += ' ';
  33137. }
  33138. if (node.nodes) {
  33139. this.block(node, name + params);
  33140. } else {
  33141. let end = (raws.between || '') + (semicolon ? ';' : '');
  33142. this.builder(escapeHTMLInCSS(name + params + end), node);
  33143. }
  33144. }
  33145. beforeAfter(node, detect) {
  33146. let value;
  33147. if (node.type === 'decl') {
  33148. value = this.raw(node, null, 'beforeDecl');
  33149. } else if (node.type === 'comment') {
  33150. value = this.raw(node, null, 'beforeComment');
  33151. } else if (detect === 'before') {
  33152. value = this.raw(node, null, 'beforeRule');
  33153. } else {
  33154. value = this.raw(node, null, 'beforeClose');
  33155. }
  33156. let buf = node.parent;
  33157. let depth = 0;
  33158. while (buf && buf.type !== 'root') {
  33159. depth += 1;
  33160. buf = buf.parent;
  33161. }
  33162. if (value.includes('\n')) {
  33163. let indent = this.raw(node, null, 'indent');
  33164. if (indent.length) {
  33165. for (let step = 0; step < depth; step++) value += indent;
  33166. }
  33167. }
  33168. return value
  33169. }
  33170. block(node, start) {
  33171. let between = this.raw(node, 'between', 'beforeOpen');
  33172. this.builder(escapeHTMLInCSS(start + between) + '{', node, 'start');
  33173. let after;
  33174. if (node.nodes && node.nodes.length) {
  33175. this.body(node);
  33176. after = this.raw(node, 'after');
  33177. } else {
  33178. after = this.raw(node, 'after', 'emptyBody');
  33179. }
  33180. if (after) this.builder(escapeHTMLInCSS(after));
  33181. this.builder('}', node, 'end');
  33182. }
  33183. body(node) {
  33184. let nodes = node.nodes;
  33185. let last = nodes.length - 1;
  33186. while (last > 0) {
  33187. if (nodes[last].type !== 'comment') break
  33188. last -= 1;
  33189. }
  33190. let semicolon = this.raw(node, 'semicolon');
  33191. let isDocument = node.type === 'document';
  33192. for (let i = 0; i < nodes.length; i++) {
  33193. let child = nodes[i];
  33194. let before = this.raw(child, 'before');
  33195. if (before) this.builder(isDocument ? before : escapeHTMLInCSS(before));
  33196. this.stringify(child, last !== i || semicolon);
  33197. }
  33198. }
  33199. comment(node) {
  33200. let left = this.raw(node, 'left', 'commentLeft');
  33201. let right = this.raw(node, 'right', 'commentRight');
  33202. this.builder(escapeHTMLInCSS('/*' + left + node.text + right + '*/'), node);
  33203. }
  33204. decl(node, semicolon) {
  33205. let raws = node.raws;
  33206. let between = this.raw(node, 'between', 'colon');
  33207. let string = node.prop + between + this.rawValue(node, 'value');
  33208. if (node.important) {
  33209. string += raws.important || ' !important';
  33210. }
  33211. if (semicolon) string += ';';
  33212. this.builder(escapeHTMLInCSS(string), node);
  33213. }
  33214. document(node) {
  33215. this.body(node);
  33216. }
  33217. raw(node, own, detect) {
  33218. let value;
  33219. if (!detect) detect = own;
  33220. // Already had
  33221. if (own) {
  33222. value = node.raws[own];
  33223. if (typeof value !== 'undefined') return value
  33224. }
  33225. let parent = node.parent;
  33226. if (detect === 'before') {
  33227. // Hack for first rule in CSS
  33228. if (!parent || (parent.type === 'root' && parent.first === node)) {
  33229. return ''
  33230. }
  33231. // `root` nodes in `document` should use only their own raws
  33232. if (parent && parent.type === 'document') {
  33233. return ''
  33234. }
  33235. }
  33236. // Floating child without parent
  33237. if (!parent) return DEFAULT_RAW[detect]
  33238. // Detect style by other nodes
  33239. let root = node.root();
  33240. let cache = root.rawCache || (root.rawCache = {});
  33241. if (typeof cache[detect] !== 'undefined') {
  33242. return cache[detect]
  33243. }
  33244. if (detect === 'before' || detect === 'after') {
  33245. return this.beforeAfter(node, detect)
  33246. } else {
  33247. let method = 'raw' + capitalize(detect);
  33248. if (this[method]) {
  33249. value = this[method](root, node);
  33250. } else {
  33251. root.walk(i => {
  33252. value = i.raws[own];
  33253. if (typeof value !== 'undefined') return false
  33254. });
  33255. }
  33256. }
  33257. if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
  33258. cache[detect] = value;
  33259. return value
  33260. }
  33261. rawBeforeClose(root) {
  33262. let value;
  33263. root.walk(i => {
  33264. if (i.nodes && i.nodes.length > 0) {
  33265. if (typeof i.raws.after !== 'undefined') {
  33266. value = i.raws.after;
  33267. if (value.includes('\n')) {
  33268. value = value.replace(/[^\n]+$/, '');
  33269. }
  33270. return false
  33271. }
  33272. }
  33273. });
  33274. if (value) value = value.replace(/\S/g, '');
  33275. return value
  33276. }
  33277. rawBeforeComment(root, node) {
  33278. let value;
  33279. root.walkComments(i => {
  33280. if (typeof i.raws.before !== 'undefined') {
  33281. value = i.raws.before;
  33282. if (value.includes('\n')) {
  33283. value = value.replace(/[^\n]+$/, '');
  33284. }
  33285. return false
  33286. }
  33287. });
  33288. if (typeof value === 'undefined') {
  33289. value = this.raw(node, null, 'beforeDecl');
  33290. } else if (value) {
  33291. value = value.replace(/\S/g, '');
  33292. }
  33293. return value
  33294. }
  33295. rawBeforeDecl(root, node) {
  33296. let value;
  33297. root.walkDecls(i => {
  33298. if (typeof i.raws.before !== 'undefined') {
  33299. value = i.raws.before;
  33300. if (value.includes('\n')) {
  33301. value = value.replace(/[^\n]+$/, '');
  33302. }
  33303. return false
  33304. }
  33305. });
  33306. if (typeof value === 'undefined') {
  33307. value = this.raw(node, null, 'beforeRule');
  33308. } else if (value) {
  33309. value = value.replace(/\S/g, '');
  33310. }
  33311. return value
  33312. }
  33313. rawBeforeOpen(root) {
  33314. let value;
  33315. root.walk(i => {
  33316. if (i.type !== 'decl') {
  33317. value = i.raws.between;
  33318. if (typeof value !== 'undefined') return false
  33319. }
  33320. });
  33321. return value
  33322. }
  33323. rawBeforeRule(root) {
  33324. let value;
  33325. root.walk(i => {
  33326. if (i.nodes && (i.parent !== root || root.first !== i)) {
  33327. if (typeof i.raws.before !== 'undefined') {
  33328. value = i.raws.before;
  33329. if (value.includes('\n')) {
  33330. value = value.replace(/[^\n]+$/, '');
  33331. }
  33332. return false
  33333. }
  33334. }
  33335. });
  33336. if (value) value = value.replace(/\S/g, '');
  33337. return value
  33338. }
  33339. rawColon(root) {
  33340. let value;
  33341. root.walkDecls(i => {
  33342. if (typeof i.raws.between !== 'undefined') {
  33343. value = i.raws.between.replace(/[^\s:]/g, '');
  33344. return false
  33345. }
  33346. });
  33347. return value
  33348. }
  33349. rawEmptyBody(root) {
  33350. let value;
  33351. root.walk(i => {
  33352. if (i.nodes && i.nodes.length === 0) {
  33353. value = i.raws.after;
  33354. if (typeof value !== 'undefined') return false
  33355. }
  33356. });
  33357. return value
  33358. }
  33359. rawIndent(root) {
  33360. if (root.raws.indent) return root.raws.indent
  33361. let value;
  33362. root.walk(i => {
  33363. let p = i.parent;
  33364. if (p && p !== root && p.parent && p.parent === root) {
  33365. if (typeof i.raws.before !== 'undefined') {
  33366. let parts = i.raws.before.split('\n');
  33367. value = parts[parts.length - 1];
  33368. value = value.replace(/\S/g, '');
  33369. return false
  33370. }
  33371. }
  33372. });
  33373. return value
  33374. }
  33375. rawSemicolon(root) {
  33376. let value;
  33377. root.walk(i => {
  33378. if (i.nodes && i.nodes.length && i.last.type === 'decl') {
  33379. value = i.raws.semicolon;
  33380. if (typeof value !== 'undefined') return false
  33381. }
  33382. });
  33383. return value
  33384. }
  33385. rawValue(node, prop) {
  33386. let value = node[prop];
  33387. let raw = node.raws[prop];
  33388. if (raw && raw.value === value) {
  33389. return raw.raw
  33390. }
  33391. return value
  33392. }
  33393. root(node) {
  33394. this.body(node);
  33395. if (node.raws.after) {
  33396. let after = node.raws.after;
  33397. let isDocument = node.parent && node.parent.type === 'document';
  33398. this.builder(isDocument ? after : escapeHTMLInCSS(after));
  33399. }
  33400. }
  33401. rule(node) {
  33402. this.block(node, this.rawValue(node, 'selector'));
  33403. if (node.raws.ownSemicolon) {
  33404. this.builder(escapeHTMLInCSS(node.raws.ownSemicolon), node, 'end');
  33405. }
  33406. }
  33407. stringify(node, semicolon) {
  33408. /* c8 ignore start */
  33409. if (!this[node.type]) {
  33410. throw new Error(
  33411. 'Unknown AST node type ' +
  33412. node.type +
  33413. '. ' +
  33414. 'Maybe you need to change PostCSS stringifier.'
  33415. )
  33416. }
  33417. /* c8 ignore stop */
  33418. this[node.type](node, semicolon);
  33419. }
  33420. }
  33421. stringifier = Stringifier;
  33422. Stringifier.default = Stringifier;
  33423. return stringifier;
  33424. }
  33425. var stringify_1;
  33426. var hasRequiredStringify;
  33427. function requireStringify () {
  33428. if (hasRequiredStringify) return stringify_1;
  33429. hasRequiredStringify = 1;
  33430. let Stringifier = /*@__PURE__*/ requireStringifier();
  33431. function stringify(node, builder) {
  33432. let str = new Stringifier(builder);
  33433. str.stringify(node);
  33434. }
  33435. stringify_1 = stringify;
  33436. stringify.default = stringify;
  33437. return stringify_1;
  33438. }
  33439. var symbols = {};
  33440. var hasRequiredSymbols;
  33441. function requireSymbols () {
  33442. if (hasRequiredSymbols) return symbols;
  33443. hasRequiredSymbols = 1;
  33444. symbols.isClean = Symbol('isClean');
  33445. symbols.my = Symbol('my');
  33446. return symbols;
  33447. }
  33448. var node$2;
  33449. var hasRequiredNode$2;
  33450. function requireNode$2 () {
  33451. if (hasRequiredNode$2) return node$2;
  33452. hasRequiredNode$2 = 1;
  33453. let CssSyntaxError = /*@__PURE__*/ requireCssSyntaxError();
  33454. let Stringifier = /*@__PURE__*/ requireStringifier();
  33455. let stringify = /*@__PURE__*/ requireStringify();
  33456. let { isClean, my } = /*@__PURE__*/ requireSymbols();
  33457. function cloneNode(obj, parent) {
  33458. let cloned = new obj.constructor();
  33459. for (let i in obj) {
  33460. if (!Object.prototype.hasOwnProperty.call(obj, i)) {
  33461. /* c8 ignore next 2 */
  33462. continue
  33463. }
  33464. if (i === 'proxyCache') continue
  33465. let value = obj[i];
  33466. let type = typeof value;
  33467. if (i === 'parent' && type === 'object') {
  33468. if (parent) cloned[i] = parent;
  33469. } else if (i === 'source') {
  33470. cloned[i] = value;
  33471. } else if (Array.isArray(value)) {
  33472. cloned[i] = value.map(j => cloneNode(j, cloned));
  33473. } else {
  33474. if (type === 'object' && value !== null) value = cloneNode(value);
  33475. cloned[i] = value;
  33476. }
  33477. }
  33478. return cloned
  33479. }
  33480. function sourceOffset(inputCSS, position) {
  33481. // Not all custom syntaxes support `offset` in `source.start` and `source.end`
  33482. if (position && typeof position.offset !== 'undefined') {
  33483. return position.offset
  33484. }
  33485. let column = 1;
  33486. let line = 1;
  33487. let offset = 0;
  33488. for (let i = 0; i < inputCSS.length; i++) {
  33489. if (line === position.line && column === position.column) {
  33490. offset = i;
  33491. break
  33492. }
  33493. if (inputCSS[i] === '\n') {
  33494. column = 1;
  33495. line += 1;
  33496. } else {
  33497. column += 1;
  33498. }
  33499. }
  33500. return offset
  33501. }
  33502. class Node {
  33503. get proxyOf() {
  33504. return this
  33505. }
  33506. constructor(defaults = {}) {
  33507. this.raws = {};
  33508. this[isClean] = false;
  33509. this[my] = true;
  33510. for (let name in defaults) {
  33511. if (name === 'nodes') {
  33512. this.nodes = [];
  33513. for (let node of defaults[name]) {
  33514. if (typeof node.clone === 'function') {
  33515. this.append(node.clone());
  33516. } else {
  33517. this.append(node);
  33518. }
  33519. }
  33520. } else {
  33521. this[name] = defaults[name];
  33522. }
  33523. }
  33524. }
  33525. addToError(error) {
  33526. error.postcssNode = this;
  33527. if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
  33528. let s = this.source;
  33529. error.stack = error.stack.replace(
  33530. /\n\s{4}at /,
  33531. `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
  33532. );
  33533. }
  33534. return error
  33535. }
  33536. after(add) {
  33537. this.parent.insertAfter(this, add);
  33538. return this
  33539. }
  33540. assign(overrides = {}) {
  33541. for (let name in overrides) {
  33542. this[name] = overrides[name];
  33543. }
  33544. return this
  33545. }
  33546. before(add) {
  33547. this.parent.insertBefore(this, add);
  33548. return this
  33549. }
  33550. cleanRaws(keepBetween) {
  33551. delete this.raws.before;
  33552. delete this.raws.after;
  33553. if (!keepBetween) delete this.raws.between;
  33554. }
  33555. clone(overrides = {}) {
  33556. let cloned = cloneNode(this);
  33557. for (let name in overrides) {
  33558. cloned[name] = overrides[name];
  33559. }
  33560. return cloned
  33561. }
  33562. cloneAfter(overrides = {}) {
  33563. let cloned = this.clone(overrides);
  33564. this.parent.insertAfter(this, cloned);
  33565. return cloned
  33566. }
  33567. cloneBefore(overrides = {}) {
  33568. let cloned = this.clone(overrides);
  33569. this.parent.insertBefore(this, cloned);
  33570. return cloned
  33571. }
  33572. error(message, opts = {}) {
  33573. if (this.source) {
  33574. let { end, start } = this.rangeBy(opts);
  33575. return this.source.input.error(
  33576. message,
  33577. { column: start.column, line: start.line },
  33578. { column: end.column, line: end.line },
  33579. opts
  33580. )
  33581. }
  33582. return new CssSyntaxError(message)
  33583. }
  33584. getProxyProcessor() {
  33585. return {
  33586. get(node, prop) {
  33587. if (prop === 'proxyOf') {
  33588. return node
  33589. } else if (prop === 'root') {
  33590. return () => node.root().toProxy()
  33591. } else {
  33592. return node[prop]
  33593. }
  33594. },
  33595. set(node, prop, value) {
  33596. if (node[prop] === value) return true
  33597. node[prop] = value;
  33598. if (
  33599. prop === 'prop' ||
  33600. prop === 'value' ||
  33601. prop === 'name' ||
  33602. prop === 'params' ||
  33603. prop === 'important' ||
  33604. /* c8 ignore next */
  33605. prop === 'text'
  33606. ) {
  33607. node.markDirty();
  33608. }
  33609. return true
  33610. }
  33611. }
  33612. }
  33613. /* c8 ignore next 3 */
  33614. markClean() {
  33615. this[isClean] = true;
  33616. }
  33617. markDirty() {
  33618. if (this[isClean]) {
  33619. this[isClean] = false;
  33620. let next = this;
  33621. while ((next = next.parent)) {
  33622. next[isClean] = false;
  33623. }
  33624. }
  33625. }
  33626. next() {
  33627. if (!this.parent) return undefined
  33628. let index = this.parent.index(this);
  33629. return this.parent.nodes[index + 1]
  33630. }
  33631. positionBy(opts = {}) {
  33632. let pos = this.source.start;
  33633. if (opts.index) {
  33634. pos = this.positionInside(opts.index);
  33635. } else if (opts.word) {
  33636. let inputString =
  33637. 'document' in this.source.input
  33638. ? this.source.input.document
  33639. : this.source.input.css;
  33640. let stringRepresentation = inputString.slice(
  33641. sourceOffset(inputString, this.source.start),
  33642. sourceOffset(inputString, this.source.end)
  33643. );
  33644. let index = stringRepresentation.indexOf(opts.word);
  33645. if (index !== -1) pos = this.positionInside(index);
  33646. }
  33647. return pos
  33648. }
  33649. positionInside(index) {
  33650. let column = this.source.start.column;
  33651. let line = this.source.start.line;
  33652. let inputString =
  33653. 'document' in this.source.input
  33654. ? this.source.input.document
  33655. : this.source.input.css;
  33656. let offset = sourceOffset(inputString, this.source.start);
  33657. let end = offset + index;
  33658. for (let i = offset; i < end; i++) {
  33659. if (inputString[i] === '\n') {
  33660. column = 1;
  33661. line += 1;
  33662. } else {
  33663. column += 1;
  33664. }
  33665. }
  33666. return { column, line, offset: end }
  33667. }
  33668. prev() {
  33669. if (!this.parent) return undefined
  33670. let index = this.parent.index(this);
  33671. return this.parent.nodes[index - 1]
  33672. }
  33673. rangeBy(opts = {}) {
  33674. let inputString =
  33675. 'document' in this.source.input
  33676. ? this.source.input.document
  33677. : this.source.input.css;
  33678. let start = {
  33679. column: this.source.start.column,
  33680. line: this.source.start.line,
  33681. offset: sourceOffset(inputString, this.source.start)
  33682. };
  33683. let end = this.source.end
  33684. ? {
  33685. column: this.source.end.column + 1,
  33686. line: this.source.end.line,
  33687. offset:
  33688. typeof this.source.end.offset === 'number'
  33689. ? // `source.end.offset` is exclusive, so we don't need to add 1
  33690. this.source.end.offset
  33691. : // Since line/column in this.source.end is inclusive,
  33692. // the `sourceOffset(... , this.source.end)` returns an inclusive offset.
  33693. // So, we add 1 to convert it to exclusive.
  33694. sourceOffset(inputString, this.source.end) + 1
  33695. }
  33696. : {
  33697. column: start.column + 1,
  33698. line: start.line,
  33699. offset: start.offset + 1
  33700. };
  33701. if (opts.word) {
  33702. let stringRepresentation = inputString.slice(
  33703. sourceOffset(inputString, this.source.start),
  33704. sourceOffset(inputString, this.source.end)
  33705. );
  33706. let index = stringRepresentation.indexOf(opts.word);
  33707. if (index !== -1) {
  33708. start = this.positionInside(index);
  33709. end = this.positionInside(index + opts.word.length);
  33710. }
  33711. } else {
  33712. if (opts.start) {
  33713. start = {
  33714. column: opts.start.column,
  33715. line: opts.start.line,
  33716. offset: sourceOffset(inputString, opts.start)
  33717. };
  33718. } else if (opts.index) {
  33719. start = this.positionInside(opts.index);
  33720. }
  33721. if (opts.end) {
  33722. end = {
  33723. column: opts.end.column,
  33724. line: opts.end.line,
  33725. offset: sourceOffset(inputString, opts.end)
  33726. };
  33727. } else if (typeof opts.endIndex === 'number') {
  33728. end = this.positionInside(opts.endIndex);
  33729. } else if (opts.index) {
  33730. end = this.positionInside(opts.index + 1);
  33731. }
  33732. }
  33733. if (
  33734. end.line < start.line ||
  33735. (end.line === start.line && end.column <= start.column)
  33736. ) {
  33737. end = {
  33738. column: start.column + 1,
  33739. line: start.line,
  33740. offset: start.offset + 1
  33741. };
  33742. }
  33743. return { end, start }
  33744. }
  33745. raw(prop, defaultType) {
  33746. let str = new Stringifier();
  33747. return str.raw(this, prop, defaultType)
  33748. }
  33749. remove() {
  33750. if (this.parent) {
  33751. this.parent.removeChild(this);
  33752. }
  33753. this.parent = undefined;
  33754. return this
  33755. }
  33756. replaceWith(...nodes) {
  33757. if (this.parent) {
  33758. let bookmark = this;
  33759. let foundSelf = false;
  33760. for (let node of nodes) {
  33761. if (node === this) {
  33762. foundSelf = true;
  33763. } else if (foundSelf) {
  33764. this.parent.insertAfter(bookmark, node);
  33765. bookmark = node;
  33766. } else {
  33767. this.parent.insertBefore(bookmark, node);
  33768. }
  33769. }
  33770. if (!foundSelf) {
  33771. this.remove();
  33772. }
  33773. }
  33774. return this
  33775. }
  33776. root() {
  33777. let result = this;
  33778. while (result.parent && result.parent.type !== 'document') {
  33779. result = result.parent;
  33780. }
  33781. return result
  33782. }
  33783. toJSON(_, inputs) {
  33784. let fixed = {};
  33785. let emitInputs = inputs == null;
  33786. inputs = inputs || new Map();
  33787. let inputsNextIndex = 0;
  33788. for (let name in this) {
  33789. if (!Object.prototype.hasOwnProperty.call(this, name)) {
  33790. /* c8 ignore next 2 */
  33791. continue
  33792. }
  33793. if (name === 'parent' || name === 'proxyCache') continue
  33794. let value = this[name];
  33795. if (Array.isArray(value)) {
  33796. fixed[name] = value.map(i => {
  33797. if (typeof i === 'object' && i.toJSON) {
  33798. return i.toJSON(null, inputs)
  33799. } else {
  33800. return i
  33801. }
  33802. });
  33803. } else if (typeof value === 'object' && value.toJSON) {
  33804. fixed[name] = value.toJSON(null, inputs);
  33805. } else if (name === 'source') {
  33806. if (value == null) continue
  33807. let inputId = inputs.get(value.input);
  33808. if (inputId == null) {
  33809. inputId = inputsNextIndex;
  33810. inputs.set(value.input, inputsNextIndex);
  33811. inputsNextIndex++;
  33812. }
  33813. fixed[name] = {
  33814. end: value.end,
  33815. inputId,
  33816. start: value.start
  33817. };
  33818. } else {
  33819. fixed[name] = value;
  33820. }
  33821. }
  33822. if (emitInputs) {
  33823. fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
  33824. }
  33825. return fixed
  33826. }
  33827. toProxy() {
  33828. if (!this.proxyCache) {
  33829. this.proxyCache = new Proxy(this, this.getProxyProcessor());
  33830. }
  33831. return this.proxyCache
  33832. }
  33833. toString(stringifier = stringify) {
  33834. if (stringifier.stringify) stringifier = stringifier.stringify;
  33835. let result = '';
  33836. stringifier(this, i => {
  33837. result += i;
  33838. });
  33839. return result
  33840. }
  33841. warn(result, text, opts = {}) {
  33842. let data = { node: this };
  33843. for (let i in opts) data[i] = opts[i];
  33844. return result.warn(text, data)
  33845. }
  33846. }
  33847. node$2 = Node;
  33848. Node.default = Node;
  33849. return node$2;
  33850. }
  33851. var comment$1;
  33852. var hasRequiredComment$1;
  33853. function requireComment$1 () {
  33854. if (hasRequiredComment$1) return comment$1;
  33855. hasRequiredComment$1 = 1;
  33856. let Node = /*@__PURE__*/ requireNode$2();
  33857. class Comment extends Node {
  33858. constructor(defaults) {
  33859. super(defaults);
  33860. this.type = 'comment';
  33861. }
  33862. }
  33863. comment$1 = Comment;
  33864. Comment.default = Comment;
  33865. return comment$1;
  33866. }
  33867. var declaration;
  33868. var hasRequiredDeclaration;
  33869. function requireDeclaration () {
  33870. if (hasRequiredDeclaration) return declaration;
  33871. hasRequiredDeclaration = 1;
  33872. let Node = /*@__PURE__*/ requireNode$2();
  33873. class Declaration extends Node {
  33874. get variable() {
  33875. return this.prop.startsWith('--') || this.prop[0] === '$'
  33876. }
  33877. constructor(defaults) {
  33878. if (
  33879. defaults &&
  33880. typeof defaults.value !== 'undefined' &&
  33881. typeof defaults.value !== 'string'
  33882. ) {
  33883. defaults = { ...defaults, value: String(defaults.value) };
  33884. }
  33885. super(defaults);
  33886. this.type = 'decl';
  33887. }
  33888. }
  33889. declaration = Declaration;
  33890. Declaration.default = Declaration;
  33891. return declaration;
  33892. }
  33893. var container$1;
  33894. var hasRequiredContainer$1;
  33895. function requireContainer$1 () {
  33896. if (hasRequiredContainer$1) return container$1;
  33897. hasRequiredContainer$1 = 1;
  33898. let Comment = /*@__PURE__*/ requireComment$1();
  33899. let Declaration = /*@__PURE__*/ requireDeclaration();
  33900. let Node = /*@__PURE__*/ requireNode$2();
  33901. let { isClean, my } = /*@__PURE__*/ requireSymbols();
  33902. let AtRule, parse, Root, Rule;
  33903. function cleanSource(nodes) {
  33904. return nodes.map(i => {
  33905. if (i.nodes) i.nodes = cleanSource(i.nodes);
  33906. delete i.source;
  33907. return i
  33908. })
  33909. }
  33910. function markTreeDirty(node) {
  33911. node[isClean] = false;
  33912. if (node.proxyOf.nodes) {
  33913. for (let i of node.proxyOf.nodes) {
  33914. markTreeDirty(i);
  33915. }
  33916. }
  33917. }
  33918. class Container extends Node {
  33919. get first() {
  33920. if (!this.proxyOf.nodes) return undefined
  33921. return this.proxyOf.nodes[0]
  33922. }
  33923. get last() {
  33924. if (!this.proxyOf.nodes) return undefined
  33925. return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
  33926. }
  33927. append(...children) {
  33928. for (let child of children) {
  33929. let nodes = this.normalize(child, this.last);
  33930. for (let node of nodes) this.proxyOf.nodes.push(node);
  33931. }
  33932. this.markDirty();
  33933. return this
  33934. }
  33935. cleanRaws(keepBetween) {
  33936. super.cleanRaws(keepBetween);
  33937. if (this.nodes) {
  33938. for (let node of this.nodes) node.cleanRaws(keepBetween);
  33939. }
  33940. }
  33941. each(callback) {
  33942. if (!this.proxyOf.nodes) return undefined
  33943. let iterator = this.getIterator();
  33944. let index, result;
  33945. while (this.indexes[iterator] < this.proxyOf.nodes.length) {
  33946. index = this.indexes[iterator];
  33947. result = callback(this.proxyOf.nodes[index], index);
  33948. if (result === false) break
  33949. this.indexes[iterator] += 1;
  33950. }
  33951. delete this.indexes[iterator];
  33952. return result
  33953. }
  33954. every(condition) {
  33955. return this.nodes.every(condition)
  33956. }
  33957. getIterator() {
  33958. if (!this.lastEach) this.lastEach = 0;
  33959. if (!this.indexes) this.indexes = {};
  33960. this.lastEach += 1;
  33961. let iterator = this.lastEach;
  33962. this.indexes[iterator] = 0;
  33963. return iterator
  33964. }
  33965. getProxyProcessor() {
  33966. return {
  33967. get(node, prop) {
  33968. if (prop === 'proxyOf') {
  33969. return node
  33970. } else if (!node[prop]) {
  33971. return node[prop]
  33972. } else if (
  33973. prop === 'each' ||
  33974. (typeof prop === 'string' && prop.startsWith('walk'))
  33975. ) {
  33976. return (...args) => {
  33977. return node[prop](
  33978. ...args.map(i => {
  33979. if (typeof i === 'function') {
  33980. return (child, index) => i(child.toProxy(), index)
  33981. } else {
  33982. return i
  33983. }
  33984. })
  33985. )
  33986. }
  33987. } else if (prop === 'every' || prop === 'some') {
  33988. return cb => {
  33989. return node[prop]((child, ...other) =>
  33990. cb(child.toProxy(), ...other)
  33991. )
  33992. }
  33993. } else if (prop === 'root') {
  33994. return () => node.root().toProxy()
  33995. } else if (prop === 'nodes') {
  33996. return node.nodes.map(i => i.toProxy())
  33997. } else if (prop === 'first' || prop === 'last') {
  33998. return node[prop].toProxy()
  33999. } else {
  34000. return node[prop]
  34001. }
  34002. },
  34003. set(node, prop, value) {
  34004. if (node[prop] === value) return true
  34005. node[prop] = value;
  34006. if (prop === 'name' || prop === 'params' || prop === 'selector') {
  34007. node.markDirty();
  34008. }
  34009. return true
  34010. }
  34011. }
  34012. }
  34013. index(child) {
  34014. if (typeof child === 'number') return child
  34015. if (child.proxyOf) child = child.proxyOf;
  34016. return this.proxyOf.nodes.indexOf(child)
  34017. }
  34018. insertAfter(exist, add) {
  34019. let existIndex = this.index(exist);
  34020. let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
  34021. existIndex = this.index(exist);
  34022. for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node);
  34023. let index;
  34024. for (let id in this.indexes) {
  34025. index = this.indexes[id];
  34026. if (existIndex < index) {
  34027. this.indexes[id] = index + nodes.length;
  34028. }
  34029. }
  34030. this.markDirty();
  34031. return this
  34032. }
  34033. insertBefore(exist, add) {
  34034. let existIndex = this.index(exist);
  34035. let type = existIndex === 0 ? 'prepend' : false;
  34036. let nodes = this.normalize(
  34037. add,
  34038. this.proxyOf.nodes[existIndex],
  34039. type
  34040. ).reverse();
  34041. existIndex = this.index(exist);
  34042. for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node);
  34043. let index;
  34044. for (let id in this.indexes) {
  34045. index = this.indexes[id];
  34046. if (existIndex <= index) {
  34047. this.indexes[id] = index + nodes.length;
  34048. }
  34049. }
  34050. this.markDirty();
  34051. return this
  34052. }
  34053. normalize(nodes, sample) {
  34054. if (typeof nodes === 'string') {
  34055. nodes = cleanSource(parse(nodes).nodes);
  34056. } else if (typeof nodes === 'undefined') {
  34057. nodes = [];
  34058. } else if (Array.isArray(nodes)) {
  34059. nodes = nodes.slice(0);
  34060. for (let i of nodes) {
  34061. if (i.parent) i.parent.removeChild(i, 'ignore');
  34062. }
  34063. } else if (nodes.type === 'root' && this.type !== 'document') {
  34064. nodes = nodes.nodes.slice(0);
  34065. for (let i of nodes) {
  34066. if (i.parent) i.parent.removeChild(i, 'ignore');
  34067. }
  34068. } else if (nodes.type) {
  34069. nodes = [nodes];
  34070. } else if (nodes.prop) {
  34071. if (typeof nodes.value === 'undefined') {
  34072. throw new Error('Value field is missed in node creation')
  34073. } else if (typeof nodes.value !== 'string') {
  34074. nodes.value = String(nodes.value);
  34075. }
  34076. nodes = [new Declaration(nodes)];
  34077. } else if (nodes.selector || nodes.selectors) {
  34078. nodes = [new Rule(nodes)];
  34079. } else if (nodes.name) {
  34080. nodes = [new AtRule(nodes)];
  34081. } else if (nodes.text) {
  34082. nodes = [new Comment(nodes)];
  34083. } else {
  34084. throw new Error('Unknown node type in node creation')
  34085. }
  34086. let processed = nodes.map(i => {
  34087. /* c8 ignore next */
  34088. if (!i[my]) Container.rebuild(i);
  34089. i = i.proxyOf;
  34090. if (i.parent) i.parent.removeChild(i);
  34091. if (i[isClean]) markTreeDirty(i);
  34092. if (!i.raws) i.raws = {};
  34093. if (typeof i.raws.before === 'undefined') {
  34094. if (sample && typeof sample.raws.before !== 'undefined') {
  34095. i.raws.before = sample.raws.before.replace(/\S/g, '');
  34096. }
  34097. }
  34098. i.parent = this.proxyOf;
  34099. return i
  34100. });
  34101. return processed
  34102. }
  34103. prepend(...children) {
  34104. children = children.reverse();
  34105. for (let child of children) {
  34106. let nodes = this.normalize(child, this.first, 'prepend').reverse();
  34107. for (let node of nodes) this.proxyOf.nodes.unshift(node);
  34108. for (let id in this.indexes) {
  34109. this.indexes[id] = this.indexes[id] + nodes.length;
  34110. }
  34111. }
  34112. this.markDirty();
  34113. return this
  34114. }
  34115. push(child) {
  34116. child.parent = this;
  34117. this.proxyOf.nodes.push(child);
  34118. return this
  34119. }
  34120. removeAll() {
  34121. for (let node of this.proxyOf.nodes) node.parent = undefined;
  34122. this.proxyOf.nodes = [];
  34123. this.markDirty();
  34124. return this
  34125. }
  34126. removeChild(child) {
  34127. child = this.index(child);
  34128. this.proxyOf.nodes[child].parent = undefined;
  34129. this.proxyOf.nodes.splice(child, 1);
  34130. let index;
  34131. for (let id in this.indexes) {
  34132. index = this.indexes[id];
  34133. if (index >= child) {
  34134. this.indexes[id] = index - 1;
  34135. }
  34136. }
  34137. this.markDirty();
  34138. return this
  34139. }
  34140. replaceValues(pattern, opts, callback) {
  34141. if (!callback) {
  34142. callback = opts;
  34143. opts = {};
  34144. }
  34145. this.walkDecls(decl => {
  34146. if (opts.props && !opts.props.includes(decl.prop)) return
  34147. if (opts.fast && !decl.value.includes(opts.fast)) return
  34148. decl.value = decl.value.replace(pattern, callback);
  34149. });
  34150. this.markDirty();
  34151. return this
  34152. }
  34153. some(condition) {
  34154. return this.nodes.some(condition)
  34155. }
  34156. walk(callback) {
  34157. return this.each((child, i) => {
  34158. let result;
  34159. try {
  34160. result = callback(child, i);
  34161. } catch (e) {
  34162. throw child.addToError(e)
  34163. }
  34164. if (result !== false && child.walk) {
  34165. result = child.walk(callback);
  34166. }
  34167. return result
  34168. })
  34169. }
  34170. walkAtRules(name, callback) {
  34171. if (!callback) {
  34172. callback = name;
  34173. return this.walk((child, i) => {
  34174. if (child.type === 'atrule') {
  34175. return callback(child, i)
  34176. }
  34177. })
  34178. }
  34179. if (name instanceof RegExp) {
  34180. return this.walk((child, i) => {
  34181. if (child.type === 'atrule' && name.test(child.name)) {
  34182. return callback(child, i)
  34183. }
  34184. })
  34185. }
  34186. return this.walk((child, i) => {
  34187. if (child.type === 'atrule' && child.name === name) {
  34188. return callback(child, i)
  34189. }
  34190. })
  34191. }
  34192. walkComments(callback) {
  34193. return this.walk((child, i) => {
  34194. if (child.type === 'comment') {
  34195. return callback(child, i)
  34196. }
  34197. })
  34198. }
  34199. walkDecls(prop, callback) {
  34200. if (!callback) {
  34201. callback = prop;
  34202. return this.walk((child, i) => {
  34203. if (child.type === 'decl') {
  34204. return callback(child, i)
  34205. }
  34206. })
  34207. }
  34208. if (prop instanceof RegExp) {
  34209. return this.walk((child, i) => {
  34210. if (child.type === 'decl' && prop.test(child.prop)) {
  34211. return callback(child, i)
  34212. }
  34213. })
  34214. }
  34215. return this.walk((child, i) => {
  34216. if (child.type === 'decl' && child.prop === prop) {
  34217. return callback(child, i)
  34218. }
  34219. })
  34220. }
  34221. walkRules(selector, callback) {
  34222. if (!callback) {
  34223. callback = selector;
  34224. return this.walk((child, i) => {
  34225. if (child.type === 'rule') {
  34226. return callback(child, i)
  34227. }
  34228. })
  34229. }
  34230. if (selector instanceof RegExp) {
  34231. return this.walk((child, i) => {
  34232. if (child.type === 'rule' && selector.test(child.selector)) {
  34233. return callback(child, i)
  34234. }
  34235. })
  34236. }
  34237. return this.walk((child, i) => {
  34238. if (child.type === 'rule' && child.selector === selector) {
  34239. return callback(child, i)
  34240. }
  34241. })
  34242. }
  34243. }
  34244. Container.registerParse = dependant => {
  34245. parse = dependant;
  34246. };
  34247. Container.registerRule = dependant => {
  34248. Rule = dependant;
  34249. };
  34250. Container.registerAtRule = dependant => {
  34251. AtRule = dependant;
  34252. };
  34253. Container.registerRoot = dependant => {
  34254. Root = dependant;
  34255. };
  34256. container$1 = Container;
  34257. Container.default = Container;
  34258. /* c8 ignore start */
  34259. Container.rebuild = node => {
  34260. if (node.type === 'atrule') {
  34261. Object.setPrototypeOf(node, AtRule.prototype);
  34262. } else if (node.type === 'rule') {
  34263. Object.setPrototypeOf(node, Rule.prototype);
  34264. } else if (node.type === 'decl') {
  34265. Object.setPrototypeOf(node, Declaration.prototype);
  34266. } else if (node.type === 'comment') {
  34267. Object.setPrototypeOf(node, Comment.prototype);
  34268. } else if (node.type === 'root') {
  34269. Object.setPrototypeOf(node, Root.prototype);
  34270. }
  34271. node[my] = true;
  34272. if (node.nodes) {
  34273. node.nodes.forEach(child => {
  34274. Container.rebuild(child);
  34275. });
  34276. }
  34277. };
  34278. /* c8 ignore stop */
  34279. return container$1;
  34280. }
  34281. var atRule;
  34282. var hasRequiredAtRule;
  34283. function requireAtRule () {
  34284. if (hasRequiredAtRule) return atRule;
  34285. hasRequiredAtRule = 1;
  34286. let Container = /*@__PURE__*/ requireContainer$1();
  34287. class AtRule extends Container {
  34288. constructor(defaults) {
  34289. super(defaults);
  34290. this.type = 'atrule';
  34291. }
  34292. append(...children) {
  34293. if (!this.proxyOf.nodes) this.nodes = [];
  34294. return super.append(...children)
  34295. }
  34296. prepend(...children) {
  34297. if (!this.proxyOf.nodes) this.nodes = [];
  34298. return super.prepend(...children)
  34299. }
  34300. }
  34301. atRule = AtRule;
  34302. AtRule.default = AtRule;
  34303. Container.registerAtRule(AtRule);
  34304. return atRule;
  34305. }
  34306. var document;
  34307. var hasRequiredDocument;
  34308. function requireDocument () {
  34309. if (hasRequiredDocument) return document;
  34310. hasRequiredDocument = 1;
  34311. let Container = /*@__PURE__*/ requireContainer$1();
  34312. let LazyResult, Processor;
  34313. class Document extends Container {
  34314. constructor(defaults) {
  34315. // type needs to be passed to super, otherwise child roots won't be normalized correctly
  34316. super({ type: 'document', ...defaults });
  34317. if (!this.nodes) {
  34318. this.nodes = [];
  34319. }
  34320. }
  34321. toResult(opts = {}) {
  34322. let lazy = new LazyResult(new Processor(), this, opts);
  34323. return lazy.stringify()
  34324. }
  34325. }
  34326. Document.registerLazyResult = dependant => {
  34327. LazyResult = dependant;
  34328. };
  34329. Document.registerProcessor = dependant => {
  34330. Processor = dependant;
  34331. };
  34332. document = Document;
  34333. Document.default = Document;
  34334. return document;
  34335. }
  34336. var nonSecure;
  34337. var hasRequiredNonSecure;
  34338. function requireNonSecure () {
  34339. if (hasRequiredNonSecure) return nonSecure;
  34340. hasRequiredNonSecure = 1;
  34341. // This alphabet uses `A-Za-z0-9_-` symbols.
  34342. // The order of characters is optimized for better gzip and brotli compression.
  34343. // References to the same file (works both for gzip and brotli):
  34344. // `'use`, `andom`, and `rict'`
  34345. // References to the brotli default dictionary:
  34346. // `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf`
  34347. let urlAlphabet =
  34348. 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
  34349. let customAlphabet = (alphabet, defaultSize = 21) => {
  34350. return (size = defaultSize) => {
  34351. let id = '';
  34352. // A compact alternative for `for (var i = 0; i < step; i++)`.
  34353. let i = size | 0;
  34354. while (i--) {
  34355. // `| 0` is more compact and faster than `Math.floor()`.
  34356. id += alphabet[(Math.random() * alphabet.length) | 0];
  34357. }
  34358. return id
  34359. }
  34360. };
  34361. let nanoid = (size = 21) => {
  34362. let id = '';
  34363. // A compact alternative for `for (var i = 0; i < step; i++)`.
  34364. let i = size | 0;
  34365. while (i--) {
  34366. // `| 0` is more compact and faster than `Math.floor()`.
  34367. id += urlAlphabet[(Math.random() * 64) | 0];
  34368. }
  34369. return id
  34370. };
  34371. nonSecure = { nanoid, customAlphabet };
  34372. return nonSecure;
  34373. }
  34374. var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1);
  34375. var previousMap;
  34376. var hasRequiredPreviousMap;
  34377. function requirePreviousMap () {
  34378. if (hasRequiredPreviousMap) return previousMap;
  34379. hasRequiredPreviousMap = 1;
  34380. let { existsSync, readFileSync } = require$$0$1;
  34381. let { dirname, join } = require$$1;
  34382. let { SourceMapConsumer, SourceMapGenerator } = /*@__PURE__*/ requireSourceMap$1();
  34383. function fromBase64(str) {
  34384. if (Buffer$1) {
  34385. return Buffer$1.from(str, 'base64').toString()
  34386. } else {
  34387. /* c8 ignore next 2 */
  34388. return window.atob(str)
  34389. }
  34390. }
  34391. class PreviousMap {
  34392. constructor(css, opts) {
  34393. if (opts.map === false) return
  34394. if (opts.unsafeMap) this.unsafeMap = true;
  34395. this.loadAnnotation(css);
  34396. this.inline = this.startWith(this.annotation, 'data:');
  34397. let prev = opts.map ? opts.map.prev : undefined;
  34398. let text = this.loadMap(opts.from, prev);
  34399. if (!this.mapFile && opts.from) {
  34400. this.mapFile = opts.from;
  34401. }
  34402. if (this.mapFile) this.root = dirname(this.mapFile);
  34403. if (text) this.text = text;
  34404. }
  34405. consumer() {
  34406. if (!this.consumerCache) {
  34407. this.consumerCache = new SourceMapConsumer(this.json || this.text);
  34408. }
  34409. return this.consumerCache
  34410. }
  34411. decodeInline(text) {
  34412. let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
  34413. let baseUri = /^data:application\/json;base64,/;
  34414. let charsetUri = /^data:application\/json;charset=utf-?8,/;
  34415. let uri = /^data:application\/json,/;
  34416. let uriMatch = text.match(charsetUri) || text.match(uri);
  34417. if (uriMatch) {
  34418. return decodeURIComponent(text.substr(uriMatch[0].length))
  34419. }
  34420. let baseUriMatch = text.match(baseCharsetUri) || text.match(baseUri);
  34421. if (baseUriMatch) {
  34422. return fromBase64(text.substr(baseUriMatch[0].length))
  34423. }
  34424. let encoding = text.slice('data:application/json;'.length);
  34425. encoding = encoding.slice(0, encoding.indexOf(','));
  34426. throw new Error('Unsupported source map encoding ' + encoding)
  34427. }
  34428. getAnnotationURL(sourceMapString) {
  34429. return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim()
  34430. }
  34431. isMap(map) {
  34432. if (typeof map !== 'object') return false
  34433. return (
  34434. typeof map.mappings === 'string' ||
  34435. typeof map._mappings === 'string' ||
  34436. Array.isArray(map.sections)
  34437. )
  34438. }
  34439. loadAnnotation(css) {
  34440. let comments = css.match(/\/\*\s*# sourceMappingURL=/g);
  34441. if (!comments) return
  34442. // sourceMappingURLs from comments, strings, etc.
  34443. let start = css.lastIndexOf(comments.pop());
  34444. let end = css.indexOf('*/', start);
  34445. if (start > -1 && end > -1) {
  34446. // Locate the last sourceMappingURL to avoid pickin
  34447. this.annotation = this.getAnnotationURL(css.substring(start, end));
  34448. }
  34449. }
  34450. loadFile(path, cssFile, trusted) {
  34451. /* c8 ignore next 5 */
  34452. if (!trusted && !this.unsafeMap) {
  34453. if (!/\.map$/i.test(path)) {
  34454. return undefined
  34455. }
  34456. }
  34457. this.root = dirname(path);
  34458. if (existsSync(path)) {
  34459. this.mapFile = path;
  34460. return readFileSync(path, 'utf-8').toString().trim()
  34461. }
  34462. }
  34463. loadMap(file, prev) {
  34464. if (prev === false) return false
  34465. if (prev) {
  34466. if (typeof prev === 'string') {
  34467. return prev
  34468. } else if (typeof prev === 'function') {
  34469. let prevPath = prev(file);
  34470. if (prevPath) {
  34471. let map = this.loadFile(prevPath, file, true);
  34472. if (!map) {
  34473. throw new Error(
  34474. 'Unable to load previous source map: ' + prevPath.toString()
  34475. )
  34476. }
  34477. return map
  34478. }
  34479. } else if (prev instanceof SourceMapConsumer) {
  34480. return SourceMapGenerator.fromSourceMap(prev).toString()
  34481. } else if (prev instanceof SourceMapGenerator) {
  34482. return prev.toString()
  34483. } else if (this.isMap(prev)) {
  34484. return JSON.stringify(prev)
  34485. } else {
  34486. throw new Error(
  34487. 'Unsupported previous source map format: ' + prev.toString()
  34488. )
  34489. }
  34490. } else if (this.inline) {
  34491. return this.decodeInline(this.annotation)
  34492. } else if (this.annotation) {
  34493. let map = this.annotation;
  34494. if (file) map = join(dirname(file), map);
  34495. let unknown = this.loadFile(map, file, false);
  34496. if (unknown) {
  34497. try {
  34498. /* c8 ignore next 4 */
  34499. this.json = JSON.parse(unknown.replace(/^\)]}'[^\n]*\n/, ''));
  34500. } catch {
  34501. return undefined
  34502. }
  34503. }
  34504. return unknown
  34505. }
  34506. }
  34507. startWith(string, start) {
  34508. if (!string) return false
  34509. return string.substr(0, start.length) === start
  34510. }
  34511. withContent() {
  34512. return !!(
  34513. this.consumer().sourcesContent &&
  34514. this.consumer().sourcesContent.length > 0
  34515. )
  34516. }
  34517. }
  34518. previousMap = PreviousMap;
  34519. PreviousMap.default = PreviousMap;
  34520. return previousMap;
  34521. }
  34522. var input;
  34523. var hasRequiredInput;
  34524. function requireInput () {
  34525. if (hasRequiredInput) return input;
  34526. hasRequiredInput = 1;
  34527. let { nanoid } = /*@__PURE__*/ requireNonSecure();
  34528. let { isAbsolute, resolve } = require$$1;
  34529. let { SourceMapConsumer, SourceMapGenerator } = /*@__PURE__*/ requireSourceMap$1();
  34530. let { fileURLToPath, pathToFileURL } = require$$2;
  34531. let CssSyntaxError = /*@__PURE__*/ requireCssSyntaxError();
  34532. let PreviousMap = /*@__PURE__*/ requirePreviousMap();
  34533. let terminalHighlight = /*@__PURE__*/ requireTerminalHighlight();
  34534. let lineToIndexCache = Symbol('lineToIndexCache');
  34535. let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
  34536. let pathAvailable = Boolean(resolve && isAbsolute);
  34537. function getLineToIndex(input) {
  34538. if (input[lineToIndexCache]) return input[lineToIndexCache]
  34539. let lines = input.css.split('\n');
  34540. let lineToIndex = new Array(lines.length);
  34541. let prevIndex = 0;
  34542. for (let i = 0, l = lines.length; i < l; i++) {
  34543. lineToIndex[i] = prevIndex;
  34544. prevIndex += lines[i].length + 1;
  34545. }
  34546. input[lineToIndexCache] = lineToIndex;
  34547. return lineToIndex
  34548. }
  34549. class Input {
  34550. get from() {
  34551. return this.file || this.id
  34552. }
  34553. constructor(css, opts = {}) {
  34554. if (
  34555. css === null ||
  34556. typeof css === 'undefined' ||
  34557. (typeof css === 'object' && !css.toString)
  34558. ) {
  34559. throw new Error(`PostCSS received ${css} instead of CSS string`)
  34560. }
  34561. this.css = css.toString();
  34562. if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
  34563. this.hasBOM = true;
  34564. this.css = this.css.slice(1);
  34565. } else {
  34566. this.hasBOM = false;
  34567. }
  34568. this.document = this.css;
  34569. if (opts.document) this.document = opts.document.toString();
  34570. if (opts.from) {
  34571. if (
  34572. !pathAvailable ||
  34573. /^\w+:\/\//.test(opts.from) ||
  34574. isAbsolute(opts.from)
  34575. ) {
  34576. this.file = opts.from;
  34577. } else {
  34578. this.file = resolve(opts.from);
  34579. }
  34580. }
  34581. if (pathAvailable && sourceMapAvailable) {
  34582. let map = new PreviousMap(this.css, opts);
  34583. if (map.text) {
  34584. this.map = map;
  34585. let file = map.consumer().file;
  34586. if (!this.file && file) this.file = this.mapResolve(file);
  34587. }
  34588. }
  34589. if (!this.file) {
  34590. this.id = '<input css ' + nanoid(6) + '>';
  34591. }
  34592. if (this.map) this.map.file = this.from;
  34593. }
  34594. error(message, line, column, opts = {}) {
  34595. let endColumn, endLine, endOffset, offset, result;
  34596. if (line && typeof line === 'object') {
  34597. let start = line;
  34598. let end = column;
  34599. if (typeof start.offset === 'number') {
  34600. offset = start.offset;
  34601. let pos = this.fromOffset(offset);
  34602. line = pos.line;
  34603. column = pos.col;
  34604. } else {
  34605. line = start.line;
  34606. column = start.column;
  34607. offset = this.fromLineAndColumn(line, column);
  34608. }
  34609. if (typeof end.offset === 'number') {
  34610. endOffset = end.offset;
  34611. let pos = this.fromOffset(endOffset);
  34612. endLine = pos.line;
  34613. endColumn = pos.col;
  34614. } else {
  34615. endLine = end.line;
  34616. endColumn = end.column;
  34617. endOffset = this.fromLineAndColumn(end.line, end.column);
  34618. }
  34619. } else if (!column) {
  34620. offset = line;
  34621. let pos = this.fromOffset(offset);
  34622. line = pos.line;
  34623. column = pos.col;
  34624. } else {
  34625. offset = this.fromLineAndColumn(line, column);
  34626. }
  34627. let origin = this.origin(line, column, endLine, endColumn);
  34628. if (origin) {
  34629. result = new CssSyntaxError(
  34630. message,
  34631. origin.endLine === undefined
  34632. ? origin.line
  34633. : { column: origin.column, line: origin.line },
  34634. origin.endLine === undefined
  34635. ? origin.column
  34636. : { column: origin.endColumn, line: origin.endLine },
  34637. origin.source,
  34638. origin.file,
  34639. opts.plugin
  34640. );
  34641. } else {
  34642. result = new CssSyntaxError(
  34643. message,
  34644. endLine === undefined ? line : { column, line },
  34645. endLine === undefined ? column : { column: endColumn, line: endLine },
  34646. this.css,
  34647. this.file,
  34648. opts.plugin
  34649. );
  34650. }
  34651. result.input = {
  34652. column,
  34653. endColumn,
  34654. endLine,
  34655. endOffset,
  34656. line,
  34657. offset,
  34658. source: this.css
  34659. };
  34660. if (this.file) {
  34661. if (pathToFileURL) {
  34662. result.input.url = pathToFileURL(this.file).toString();
  34663. }
  34664. result.input.file = this.file;
  34665. }
  34666. return result
  34667. }
  34668. fromLineAndColumn(line, column) {
  34669. let lineToIndex = getLineToIndex(this);
  34670. let index = lineToIndex[line - 1];
  34671. return index + column - 1
  34672. }
  34673. fromOffset(offset) {
  34674. let lineToIndex = getLineToIndex(this);
  34675. let lastLine = lineToIndex[lineToIndex.length - 1];
  34676. let min = 0;
  34677. if (offset >= lastLine) {
  34678. min = lineToIndex.length - 1;
  34679. } else {
  34680. let max = lineToIndex.length - 2;
  34681. let mid;
  34682. while (min < max) {
  34683. mid = min + ((max - min) >> 1);
  34684. if (offset < lineToIndex[mid]) {
  34685. max = mid - 1;
  34686. } else if (offset >= lineToIndex[mid + 1]) {
  34687. min = mid + 1;
  34688. } else {
  34689. min = mid;
  34690. break
  34691. }
  34692. }
  34693. }
  34694. return {
  34695. col: offset - lineToIndex[min] + 1,
  34696. line: min + 1
  34697. }
  34698. }
  34699. mapResolve(file) {
  34700. if (/^\w+:\/\//.test(file)) {
  34701. return file
  34702. }
  34703. return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
  34704. }
  34705. origin(line, column, endLine, endColumn) {
  34706. if (!this.map) return false
  34707. let consumer = this.map.consumer();
  34708. let from = consumer.originalPositionFor({ column, line });
  34709. if (!from.source) return false
  34710. let to;
  34711. if (typeof endLine === 'number') {
  34712. to = consumer.originalPositionFor({ column: endColumn, line: endLine });
  34713. }
  34714. let fromUrl;
  34715. if (isAbsolute(from.source)) {
  34716. fromUrl = pathToFileURL(from.source);
  34717. } else {
  34718. fromUrl = new URL(
  34719. from.source,
  34720. this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
  34721. );
  34722. }
  34723. let result = {
  34724. column: from.column,
  34725. endColumn: to && to.column,
  34726. endLine: to && to.line,
  34727. line: from.line,
  34728. url: fromUrl.toString()
  34729. };
  34730. if (fromUrl.protocol === 'file:') {
  34731. if (fileURLToPath) {
  34732. result.file = fileURLToPath(fromUrl);
  34733. } else {
  34734. /* c8 ignore next 2 */
  34735. throw new Error(`file: protocol is not available in this PostCSS build`)
  34736. }
  34737. }
  34738. let source = consumer.sourceContentFor(from.source);
  34739. if (source) result.source = source;
  34740. return result
  34741. }
  34742. toJSON() {
  34743. let json = {};
  34744. for (let name of ['hasBOM', 'css', 'file', 'id']) {
  34745. if (this[name] != null) {
  34746. json[name] = this[name];
  34747. }
  34748. }
  34749. if (this.map) {
  34750. json.map = { ...this.map };
  34751. if (json.map.consumerCache) {
  34752. json.map.consumerCache = undefined;
  34753. }
  34754. }
  34755. return json
  34756. }
  34757. }
  34758. input = Input;
  34759. Input.default = Input;
  34760. if (terminalHighlight && terminalHighlight.registerInput) {
  34761. terminalHighlight.registerInput(Input);
  34762. }
  34763. return input;
  34764. }
  34765. var root$1;
  34766. var hasRequiredRoot$1;
  34767. function requireRoot$1 () {
  34768. if (hasRequiredRoot$1) return root$1;
  34769. hasRequiredRoot$1 = 1;
  34770. let Container = /*@__PURE__*/ requireContainer$1();
  34771. let LazyResult, Processor;
  34772. class Root extends Container {
  34773. constructor(defaults) {
  34774. super(defaults);
  34775. this.type = 'root';
  34776. if (!this.nodes) this.nodes = [];
  34777. }
  34778. normalize(child, sample, type) {
  34779. let nodes = super.normalize(child);
  34780. if (sample) {
  34781. if (type === 'prepend') {
  34782. if (this.nodes.length > 1) {
  34783. sample.raws.before = this.nodes[1].raws.before;
  34784. } else {
  34785. delete sample.raws.before;
  34786. }
  34787. } else if (this.first !== sample) {
  34788. for (let node of nodes) {
  34789. node.raws.before = sample.raws.before;
  34790. }
  34791. }
  34792. }
  34793. return nodes
  34794. }
  34795. removeChild(child, ignore) {
  34796. let index = this.index(child);
  34797. if (!ignore && index === 0 && this.nodes.length > 1) {
  34798. this.nodes[1].raws.before = this.nodes[index].raws.before;
  34799. }
  34800. return super.removeChild(child)
  34801. }
  34802. toResult(opts = {}) {
  34803. let lazy = new LazyResult(new Processor(), this, opts);
  34804. return lazy.stringify()
  34805. }
  34806. }
  34807. Root.registerLazyResult = dependant => {
  34808. LazyResult = dependant;
  34809. };
  34810. Root.registerProcessor = dependant => {
  34811. Processor = dependant;
  34812. };
  34813. root$1 = Root;
  34814. Root.default = Root;
  34815. Container.registerRoot(Root);
  34816. return root$1;
  34817. }
  34818. var list_1;
  34819. var hasRequiredList;
  34820. function requireList () {
  34821. if (hasRequiredList) return list_1;
  34822. hasRequiredList = 1;
  34823. let list = {
  34824. comma(string) {
  34825. return list.split(string, [','], true)
  34826. },
  34827. space(string) {
  34828. let spaces = [' ', '\n', '\t'];
  34829. return list.split(string, spaces)
  34830. },
  34831. split(string, separators, last) {
  34832. let array = [];
  34833. let current = '';
  34834. let split = false;
  34835. let func = 0;
  34836. let inQuote = false;
  34837. let prevQuote = '';
  34838. let escape = false;
  34839. for (let letter of string) {
  34840. if (escape) {
  34841. escape = false;
  34842. } else if (letter === '\\') {
  34843. escape = true;
  34844. } else if (inQuote) {
  34845. if (letter === prevQuote) {
  34846. inQuote = false;
  34847. }
  34848. } else if (letter === '"' || letter === "'") {
  34849. inQuote = true;
  34850. prevQuote = letter;
  34851. } else if (letter === '(') {
  34852. func += 1;
  34853. } else if (letter === ')') {
  34854. if (func > 0) func -= 1;
  34855. } else if (func === 0) {
  34856. if (separators.includes(letter)) split = true;
  34857. }
  34858. if (split) {
  34859. if (current !== '') array.push(current.trim());
  34860. current = '';
  34861. split = false;
  34862. } else {
  34863. current += letter;
  34864. }
  34865. }
  34866. if (last || current !== '') array.push(current.trim());
  34867. return array
  34868. }
  34869. };
  34870. list_1 = list;
  34871. list.default = list;
  34872. return list_1;
  34873. }
  34874. var rule;
  34875. var hasRequiredRule;
  34876. function requireRule () {
  34877. if (hasRequiredRule) return rule;
  34878. hasRequiredRule = 1;
  34879. let Container = /*@__PURE__*/ requireContainer$1();
  34880. let list = /*@__PURE__*/ requireList();
  34881. class Rule extends Container {
  34882. get selectors() {
  34883. return list.comma(this.selector)
  34884. }
  34885. set selectors(values) {
  34886. let match = this.selector ? this.selector.match(/,\s*/) : null;
  34887. let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
  34888. this.selector = values.join(sep);
  34889. }
  34890. constructor(defaults) {
  34891. super(defaults);
  34892. this.type = 'rule';
  34893. if (!this.nodes) this.nodes = [];
  34894. }
  34895. }
  34896. rule = Rule;
  34897. Rule.default = Rule;
  34898. Container.registerRule(Rule);
  34899. return rule;
  34900. }
  34901. var fromJSON_1;
  34902. var hasRequiredFromJSON;
  34903. function requireFromJSON () {
  34904. if (hasRequiredFromJSON) return fromJSON_1;
  34905. hasRequiredFromJSON = 1;
  34906. let AtRule = /*@__PURE__*/ requireAtRule();
  34907. let Comment = /*@__PURE__*/ requireComment$1();
  34908. let Declaration = /*@__PURE__*/ requireDeclaration();
  34909. let Input = /*@__PURE__*/ requireInput();
  34910. let PreviousMap = /*@__PURE__*/ requirePreviousMap();
  34911. let Root = /*@__PURE__*/ requireRoot$1();
  34912. let Rule = /*@__PURE__*/ requireRule();
  34913. function fromJSON(json, inputs) {
  34914. if (Array.isArray(json)) return json.map(n => fromJSON(n))
  34915. let { inputs: ownInputs, ...defaults } = json;
  34916. if (ownInputs) {
  34917. inputs = [];
  34918. for (let input of ownInputs) {
  34919. let inputHydrated = { ...input, __proto__: Input.prototype };
  34920. if (inputHydrated.map) {
  34921. inputHydrated.map = {
  34922. ...inputHydrated.map,
  34923. __proto__: PreviousMap.prototype
  34924. };
  34925. }
  34926. inputs.push(inputHydrated);
  34927. }
  34928. }
  34929. if (defaults.nodes) {
  34930. defaults.nodes = json.nodes.map(n => fromJSON(n, inputs));
  34931. }
  34932. if (defaults.source) {
  34933. let { inputId, ...source } = defaults.source;
  34934. defaults.source = source;
  34935. if (inputId != null) {
  34936. defaults.source.input = inputs[inputId];
  34937. }
  34938. }
  34939. if (defaults.type === 'root') {
  34940. return new Root(defaults)
  34941. } else if (defaults.type === 'decl') {
  34942. return new Declaration(defaults)
  34943. } else if (defaults.type === 'rule') {
  34944. return new Rule(defaults)
  34945. } else if (defaults.type === 'comment') {
  34946. return new Comment(defaults)
  34947. } else if (defaults.type === 'atrule') {
  34948. return new AtRule(defaults)
  34949. } else {
  34950. throw new Error('Unknown node type: ' + json.type)
  34951. }
  34952. }
  34953. fromJSON_1 = fromJSON;
  34954. fromJSON.default = fromJSON;
  34955. return fromJSON_1;
  34956. }
  34957. var mapGenerator;
  34958. var hasRequiredMapGenerator;
  34959. function requireMapGenerator () {
  34960. if (hasRequiredMapGenerator) return mapGenerator;
  34961. hasRequiredMapGenerator = 1;
  34962. let { dirname, relative, resolve, sep } = require$$1;
  34963. let { SourceMapConsumer, SourceMapGenerator } = /*@__PURE__*/ requireSourceMap$1();
  34964. let { pathToFileURL } = require$$2;
  34965. let Input = /*@__PURE__*/ requireInput();
  34966. let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
  34967. let pathAvailable = Boolean(dirname && resolve && relative && sep);
  34968. class MapGenerator {
  34969. constructor(stringify, root, opts, cssString) {
  34970. this.stringify = stringify;
  34971. this.mapOpts = opts.map || {};
  34972. this.root = root;
  34973. this.opts = opts;
  34974. this.css = cssString;
  34975. this.originalCSS = cssString;
  34976. this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
  34977. this.memoizedFileURLs = new Map();
  34978. this.memoizedPaths = new Map();
  34979. this.memoizedURLs = new Map();
  34980. }
  34981. addAnnotation() {
  34982. let content;
  34983. if (this.isInline()) {
  34984. content =
  34985. 'data:application/json;base64,' + this.toBase64(this.map.toString());
  34986. } else if (typeof this.mapOpts.annotation === 'string') {
  34987. content = this.mapOpts.annotation;
  34988. } else if (typeof this.mapOpts.annotation === 'function') {
  34989. content = this.mapOpts.annotation(this.opts.to, this.root);
  34990. } else {
  34991. content = this.outputFile() + '.map';
  34992. }
  34993. let eol = '\n';
  34994. if (this.css.includes('\r\n')) eol = '\r\n';
  34995. this.css += eol + '/*# sourceMappingURL=' + content + ' */';
  34996. }
  34997. applyPrevMaps() {
  34998. for (let prev of this.previous()) {
  34999. let from = this.toUrl(this.path(prev.file));
  35000. let root = prev.root || dirname(prev.file);
  35001. let map;
  35002. if (this.mapOpts.sourcesContent === false) {
  35003. map = new SourceMapConsumer(prev.text);
  35004. if (map.sourcesContent) {
  35005. map.sourcesContent = null;
  35006. }
  35007. } else {
  35008. map = prev.consumer();
  35009. }
  35010. this.map.applySourceMap(map, from, this.toUrl(this.path(root)));
  35011. }
  35012. }
  35013. clearAnnotation() {
  35014. if (this.mapOpts.annotation === false) return
  35015. if (this.root) {
  35016. let node;
  35017. for (let i = this.root.nodes.length - 1; i >= 0; i--) {
  35018. node = this.root.nodes[i];
  35019. if (node.type !== 'comment') continue
  35020. if (node.text.startsWith('# sourceMappingURL=')) {
  35021. this.root.removeChild(i);
  35022. }
  35023. }
  35024. } else if (this.css) {
  35025. let startIndex;
  35026. while ((startIndex = this.css.lastIndexOf('/*#')) !== -1) {
  35027. let endIndex = this.css.indexOf('*/', startIndex + 3);
  35028. if (endIndex === -1) break
  35029. while (startIndex > 0 && this.css[startIndex - 1] === '\n') {
  35030. startIndex--;
  35031. }
  35032. this.css = this.css.slice(0, startIndex) + this.css.slice(endIndex + 2);
  35033. }
  35034. }
  35035. }
  35036. generate() {
  35037. this.clearAnnotation();
  35038. if (pathAvailable && sourceMapAvailable && this.isMap()) {
  35039. return this.generateMap()
  35040. } else {
  35041. let result = '';
  35042. this.stringify(this.root, i => {
  35043. result += i;
  35044. });
  35045. return [result]
  35046. }
  35047. }
  35048. generateMap() {
  35049. if (this.root) {
  35050. this.generateString();
  35051. } else if (this.previous().length === 1) {
  35052. let prev = this.previous()[0].consumer();
  35053. prev.file = this.outputFile();
  35054. this.map = SourceMapGenerator.fromSourceMap(prev, {
  35055. ignoreInvalidMapping: true
  35056. });
  35057. } else {
  35058. this.map = new SourceMapGenerator({
  35059. file: this.outputFile(),
  35060. ignoreInvalidMapping: true
  35061. });
  35062. this.map.addMapping({
  35063. generated: { column: 0, line: 1 },
  35064. original: { column: 0, line: 1 },
  35065. source: this.opts.from
  35066. ? this.toUrl(this.path(this.opts.from))
  35067. : '<no source>'
  35068. });
  35069. }
  35070. if (this.isSourcesContent()) this.setSourcesContent();
  35071. if (this.root && this.previous().length > 0) this.applyPrevMaps();
  35072. if (this.isAnnotation()) this.addAnnotation();
  35073. if (this.isInline()) {
  35074. return [this.css]
  35075. } else {
  35076. return [this.css, this.map]
  35077. }
  35078. }
  35079. generateString() {
  35080. this.css = '';
  35081. this.map = new SourceMapGenerator({
  35082. file: this.outputFile(),
  35083. ignoreInvalidMapping: true
  35084. });
  35085. let line = 1;
  35086. let column = 1;
  35087. let noSource = '<no source>';
  35088. let mapping = {
  35089. generated: { column: 0, line: 0 },
  35090. original: { column: 0, line: 0 },
  35091. source: ''
  35092. };
  35093. let last, lines;
  35094. this.stringify(this.root, (str, node, type) => {
  35095. this.css += str;
  35096. if (node && type !== 'end') {
  35097. mapping.generated.line = line;
  35098. mapping.generated.column = column - 1;
  35099. if (node.source && node.source.start) {
  35100. mapping.source = this.sourcePath(node);
  35101. mapping.original.line = node.source.start.line;
  35102. mapping.original.column = node.source.start.column - 1;
  35103. this.map.addMapping(mapping);
  35104. } else {
  35105. mapping.source = noSource;
  35106. mapping.original.line = 1;
  35107. mapping.original.column = 0;
  35108. this.map.addMapping(mapping);
  35109. }
  35110. }
  35111. lines = str.match(/\n/g);
  35112. if (lines) {
  35113. line += lines.length;
  35114. last = str.lastIndexOf('\n');
  35115. column = str.length - last;
  35116. } else {
  35117. column += str.length;
  35118. }
  35119. if (node && type !== 'start') {
  35120. let p = node.parent || { raws: {} };
  35121. let childless =
  35122. node.type === 'decl' || (node.type === 'atrule' && !node.nodes);
  35123. if (!childless || node !== p.last || p.raws.semicolon) {
  35124. if (node.source && node.source.end) {
  35125. mapping.source = this.sourcePath(node);
  35126. mapping.original.line = node.source.end.line;
  35127. mapping.original.column = node.source.end.column - 1;
  35128. mapping.generated.line = line;
  35129. mapping.generated.column = column - 2;
  35130. this.map.addMapping(mapping);
  35131. } else {
  35132. mapping.source = noSource;
  35133. mapping.original.line = 1;
  35134. mapping.original.column = 0;
  35135. mapping.generated.line = line;
  35136. mapping.generated.column = column - 1;
  35137. this.map.addMapping(mapping);
  35138. }
  35139. }
  35140. }
  35141. });
  35142. }
  35143. isAnnotation() {
  35144. if (this.isInline()) {
  35145. return true
  35146. }
  35147. if (typeof this.mapOpts.annotation !== 'undefined') {
  35148. return this.mapOpts.annotation
  35149. }
  35150. if (this.previous().length) {
  35151. return this.previous().some(i => i.annotation)
  35152. }
  35153. return true
  35154. }
  35155. isInline() {
  35156. if (typeof this.mapOpts.inline !== 'undefined') {
  35157. return this.mapOpts.inline
  35158. }
  35159. let annotation = this.mapOpts.annotation;
  35160. if (typeof annotation !== 'undefined' && annotation !== true) {
  35161. return false
  35162. }
  35163. if (this.previous().length) {
  35164. return this.previous().some(i => i.inline)
  35165. }
  35166. return true
  35167. }
  35168. isMap() {
  35169. if (typeof this.opts.map !== 'undefined') {
  35170. return !!this.opts.map
  35171. }
  35172. return this.previous().length > 0
  35173. }
  35174. isSourcesContent() {
  35175. if (typeof this.mapOpts.sourcesContent !== 'undefined') {
  35176. return this.mapOpts.sourcesContent
  35177. }
  35178. if (this.previous().length) {
  35179. return this.previous().some(i => i.withContent())
  35180. }
  35181. return true
  35182. }
  35183. outputFile() {
  35184. if (this.opts.to) {
  35185. return this.path(this.opts.to)
  35186. } else if (this.opts.from) {
  35187. return this.path(this.opts.from)
  35188. } else {
  35189. return 'to.css'
  35190. }
  35191. }
  35192. path(file) {
  35193. if (this.mapOpts.absolute) return file
  35194. if (file.charCodeAt(0) === 60 /* `<` */) return file
  35195. if (/^\w+:\/\//.test(file)) return file
  35196. let cached = this.memoizedPaths.get(file);
  35197. if (cached) return cached
  35198. let from = this.opts.to ? dirname(this.opts.to) : '.';
  35199. if (typeof this.mapOpts.annotation === 'string') {
  35200. from = dirname(resolve(from, this.mapOpts.annotation));
  35201. }
  35202. let path = relative(from, file);
  35203. this.memoizedPaths.set(file, path);
  35204. return path
  35205. }
  35206. previous() {
  35207. if (!this.previousMaps) {
  35208. this.previousMaps = [];
  35209. if (this.root) {
  35210. this.root.walk(node => {
  35211. if (node.source && node.source.input.map) {
  35212. let map = node.source.input.map;
  35213. if (!this.previousMaps.includes(map)) {
  35214. this.previousMaps.push(map);
  35215. }
  35216. }
  35217. });
  35218. } else {
  35219. let input = new Input(this.originalCSS, this.opts);
  35220. if (input.map) this.previousMaps.push(input.map);
  35221. }
  35222. }
  35223. return this.previousMaps
  35224. }
  35225. setSourcesContent() {
  35226. let already = {};
  35227. if (this.root) {
  35228. this.root.walk(node => {
  35229. if (node.source) {
  35230. let from = node.source.input.from;
  35231. if (from && !already[from]) {
  35232. already[from] = true;
  35233. let fromUrl = this.usesFileUrls
  35234. ? this.toFileUrl(from)
  35235. : this.toUrl(this.path(from));
  35236. this.map.setSourceContent(fromUrl, node.source.input.css);
  35237. }
  35238. }
  35239. });
  35240. } else if (this.css) {
  35241. let from = this.opts.from
  35242. ? this.toUrl(this.path(this.opts.from))
  35243. : '<no source>';
  35244. this.map.setSourceContent(from, this.css);
  35245. }
  35246. }
  35247. sourcePath(node) {
  35248. if (this.mapOpts.from) {
  35249. return this.toUrl(this.mapOpts.from)
  35250. } else if (this.usesFileUrls) {
  35251. return this.toFileUrl(node.source.input.from)
  35252. } else {
  35253. return this.toUrl(this.path(node.source.input.from))
  35254. }
  35255. }
  35256. toBase64(str) {
  35257. if (Buffer$1) {
  35258. return Buffer$1.from(str).toString('base64')
  35259. } else {
  35260. return window.btoa(unescape(encodeURIComponent(str)))
  35261. }
  35262. }
  35263. toFileUrl(path) {
  35264. let cached = this.memoizedFileURLs.get(path);
  35265. if (cached) return cached
  35266. if (pathToFileURL) {
  35267. let fileURL = pathToFileURL(path).toString();
  35268. this.memoizedFileURLs.set(path, fileURL);
  35269. return fileURL
  35270. } else {
  35271. throw new Error(
  35272. '`map.absolute` option is not available in this PostCSS build'
  35273. )
  35274. }
  35275. }
  35276. toUrl(path) {
  35277. let cached = this.memoizedURLs.get(path);
  35278. if (cached) return cached
  35279. if (sep === '\\') {
  35280. path = path.replace(/\\/g, '/');
  35281. }
  35282. let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
  35283. this.memoizedURLs.set(path, url);
  35284. return url
  35285. }
  35286. }
  35287. mapGenerator = MapGenerator;
  35288. return mapGenerator;
  35289. }
  35290. var parser$1;
  35291. var hasRequiredParser$1;
  35292. function requireParser$1 () {
  35293. if (hasRequiredParser$1) return parser$1;
  35294. hasRequiredParser$1 = 1;
  35295. let AtRule = /*@__PURE__*/ requireAtRule();
  35296. let Comment = /*@__PURE__*/ requireComment$1();
  35297. let Declaration = /*@__PURE__*/ requireDeclaration();
  35298. let Root = /*@__PURE__*/ requireRoot$1();
  35299. let Rule = /*@__PURE__*/ requireRule();
  35300. let tokenizer = /*@__PURE__*/ requireTokenize$1();
  35301. const SAFE_COMMENT_NEIGHBOR = {
  35302. empty: true,
  35303. space: true
  35304. };
  35305. function findLastWithPosition(tokens) {
  35306. for (let i = tokens.length - 1; i >= 0; i--) {
  35307. let token = tokens[i];
  35308. let pos = token[3] || token[2];
  35309. if (pos) return pos
  35310. }
  35311. }
  35312. function tokensToString(tokens, from, to) {
  35313. let result = '';
  35314. for (let i = from; i < to; i++) result += tokens[i][1];
  35315. return result
  35316. }
  35317. class Parser {
  35318. constructor(input) {
  35319. this.input = input;
  35320. this.root = new Root();
  35321. this.current = this.root;
  35322. this.spaces = '';
  35323. this.semicolon = false;
  35324. this.createTokenizer();
  35325. this.root.source = { input, start: { column: 1, line: 1, offset: 0 } };
  35326. }
  35327. atrule(token) {
  35328. let node = new AtRule();
  35329. node.name = token[1].slice(1);
  35330. if (node.name === '') {
  35331. this.unnamedAtrule(node, token);
  35332. }
  35333. this.init(node, token[2]);
  35334. let type;
  35335. let prev;
  35336. let shift;
  35337. let last = false;
  35338. let open = false;
  35339. let params = [];
  35340. let brackets = [];
  35341. while (!this.tokenizer.endOfFile()) {
  35342. token = this.tokenizer.nextToken();
  35343. type = token[0];
  35344. if (type === '(' || type === '[') {
  35345. brackets.push(type === '(' ? ')' : ']');
  35346. } else if (type === '{' && brackets.length > 0) {
  35347. brackets.push('}');
  35348. } else if (type === brackets[brackets.length - 1]) {
  35349. brackets.pop();
  35350. }
  35351. if (brackets.length === 0) {
  35352. if (type === ';') {
  35353. node.source.end = this.getPosition(token[2]);
  35354. node.source.end.offset++;
  35355. this.semicolon = true;
  35356. break
  35357. } else if (type === '{') {
  35358. open = true;
  35359. break
  35360. } else if (type === '}') {
  35361. if (params.length > 0) {
  35362. shift = params.length - 1;
  35363. prev = params[shift];
  35364. while (prev && prev[0] === 'space') {
  35365. prev = params[--shift];
  35366. }
  35367. if (prev) {
  35368. node.source.end = this.getPosition(prev[3] || prev[2]);
  35369. node.source.end.offset++;
  35370. }
  35371. }
  35372. this.end(token);
  35373. break
  35374. } else {
  35375. params.push(token);
  35376. }
  35377. } else {
  35378. params.push(token);
  35379. }
  35380. if (this.tokenizer.endOfFile()) {
  35381. last = true;
  35382. break
  35383. }
  35384. }
  35385. node.raws.between = this.spacesAndCommentsFromEnd(params);
  35386. if (params.length) {
  35387. node.raws.afterName = this.spacesAndCommentsFromStart(params);
  35388. this.raw(node, 'params', params);
  35389. if (last) {
  35390. token = params[params.length - 1];
  35391. node.source.end = this.getPosition(token[3] || token[2]);
  35392. node.source.end.offset++;
  35393. this.spaces = node.raws.between;
  35394. node.raws.between = '';
  35395. }
  35396. } else {
  35397. node.raws.afterName = '';
  35398. node.params = '';
  35399. }
  35400. if (open) {
  35401. node.nodes = [];
  35402. this.current = node;
  35403. }
  35404. }
  35405. checkMissedSemicolon(tokens) {
  35406. let colon = this.colon(tokens);
  35407. if (colon === false) return
  35408. let founded = 0;
  35409. let token;
  35410. for (let j = colon - 1; j >= 0; j--) {
  35411. token = tokens[j];
  35412. if (token[0] !== 'space') {
  35413. founded += 1;
  35414. if (founded === 2) break
  35415. }
  35416. }
  35417. // If the token is a word, e.g. `!important`, `red` or any other valid
  35418. // property's value. Then we need to return the colon after that word
  35419. // token. [3] is the "end" colon of that word. And because we need it
  35420. // after that one we do +1 to get the next one.
  35421. throw this.input.error(
  35422. 'Missed semicolon',
  35423. token[0] === 'word' ? token[3] + 1 : token[2]
  35424. )
  35425. }
  35426. colon(tokens) {
  35427. let brackets = 0;
  35428. let prev, token, type;
  35429. for (let [i, element] of tokens.entries()) {
  35430. token = element;
  35431. type = token[0];
  35432. if (type === '(') {
  35433. brackets += 1;
  35434. }
  35435. if (type === ')') {
  35436. brackets -= 1;
  35437. }
  35438. if (brackets === 0 && type === ':') {
  35439. if (!prev) {
  35440. this.doubleColon(token);
  35441. } else if (prev[0] === 'word' && prev[1] === 'progid') {
  35442. continue
  35443. } else {
  35444. return i
  35445. }
  35446. }
  35447. prev = token;
  35448. }
  35449. return false
  35450. }
  35451. comment(token) {
  35452. let node = new Comment();
  35453. this.init(node, token[2]);
  35454. node.source.end = this.getPosition(token[3] || token[2]);
  35455. node.source.end.offset++;
  35456. let text = token[1].slice(2, -2);
  35457. if (!text.trim()) {
  35458. node.text = '';
  35459. node.raws.left = text;
  35460. node.raws.right = '';
  35461. } else {
  35462. let match = text.match(/^(\s*)([^]*\S)(\s*)$/);
  35463. node.text = match[2];
  35464. node.raws.left = match[1];
  35465. node.raws.right = match[3];
  35466. }
  35467. }
  35468. createTokenizer() {
  35469. this.tokenizer = tokenizer(this.input);
  35470. }
  35471. decl(tokens, customProperty) {
  35472. let node = new Declaration();
  35473. this.init(node, tokens[0][2]);
  35474. let last = tokens[tokens.length - 1];
  35475. if (last[0] === ';') {
  35476. this.semicolon = true;
  35477. tokens.pop();
  35478. }
  35479. node.source.end = this.getPosition(
  35480. last[3] || last[2] || findLastWithPosition(tokens)
  35481. );
  35482. node.source.end.offset++;
  35483. let start = 0;
  35484. while (tokens[start][0] !== 'word') {
  35485. if (start === tokens.length - 1) this.unknownWord([tokens[start]]);
  35486. start++;
  35487. }
  35488. node.raws.before += tokensToString(tokens, 0, start);
  35489. node.source.start = this.getPosition(tokens[start][2]);
  35490. let propStart = start;
  35491. while (start < tokens.length) {
  35492. let type = tokens[start][0];
  35493. if (type === ':' || type === 'space' || type === 'comment') {
  35494. break
  35495. }
  35496. start++;
  35497. }
  35498. node.prop = tokensToString(tokens, propStart, start);
  35499. let betweenStart = start;
  35500. let token;
  35501. while (start < tokens.length) {
  35502. token = tokens[start];
  35503. start++;
  35504. if (token[0] === ':') break
  35505. if (token[0] === 'word' && /\w/.test(token[1])) {
  35506. this.unknownWord([token]);
  35507. }
  35508. }
  35509. node.raws.between = tokensToString(tokens, betweenStart, start);
  35510. if (node.prop[0] === '_' || node.prop[0] === '*') {
  35511. node.raws.before += node.prop[0];
  35512. node.prop = node.prop.slice(1);
  35513. }
  35514. let firstSpacesStart = start;
  35515. while (start < tokens.length) {
  35516. let next = tokens[start][0];
  35517. if (next !== 'space' && next !== 'comment') break
  35518. start++;
  35519. }
  35520. let firstSpaces = tokens.slice(firstSpacesStart, start);
  35521. tokens = tokens.slice(start);
  35522. this.precheckMissedSemicolon(tokens);
  35523. for (let i = tokens.length - 1; i >= 0; i--) {
  35524. token = tokens[i];
  35525. if (token[1].toLowerCase() === '!important') {
  35526. node.important = true;
  35527. let string = this.stringFrom(tokens, i);
  35528. string = this.spacesFromEnd(tokens) + string;
  35529. if (string !== ' !important') node.raws.important = string;
  35530. break
  35531. } else if (token[1].toLowerCase() === 'important') {
  35532. let cache = tokens.slice(0);
  35533. let str = '';
  35534. for (let j = i; j > 0; j--) {
  35535. let type = cache[j][0];
  35536. if (str.trim().startsWith('!') && type !== 'space') {
  35537. break
  35538. }
  35539. str = cache.pop()[1] + str;
  35540. }
  35541. if (str.trim().startsWith('!')) {
  35542. node.important = true;
  35543. node.raws.important = str;
  35544. tokens = cache;
  35545. }
  35546. }
  35547. if (token[0] !== 'space' && token[0] !== 'comment') {
  35548. break
  35549. }
  35550. }
  35551. let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment');
  35552. if (hasWord) {
  35553. node.raws.between += firstSpaces.map(i => i[1]).join('');
  35554. firstSpaces = [];
  35555. }
  35556. this.raw(node, 'value', firstSpaces.concat(tokens), customProperty);
  35557. if (node.value.includes(':') && !customProperty) {
  35558. this.checkMissedSemicolon(tokens);
  35559. }
  35560. }
  35561. doubleColon(token) {
  35562. throw this.input.error(
  35563. 'Double colon',
  35564. { offset: token[2] },
  35565. { offset: token[2] + token[1].length }
  35566. )
  35567. }
  35568. emptyRule(token) {
  35569. let node = new Rule();
  35570. this.init(node, token[2]);
  35571. node.selector = '';
  35572. node.raws.between = '';
  35573. this.current = node;
  35574. }
  35575. end(token) {
  35576. if (this.current.nodes && this.current.nodes.length) {
  35577. this.current.raws.semicolon = this.semicolon;
  35578. }
  35579. this.semicolon = false;
  35580. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  35581. this.spaces = '';
  35582. if (this.current.parent) {
  35583. this.current.source.end = this.getPosition(token[2]);
  35584. this.current.source.end.offset++;
  35585. this.current = this.current.parent;
  35586. } else {
  35587. this.unexpectedClose(token);
  35588. }
  35589. }
  35590. endFile() {
  35591. if (this.current.parent) this.unclosedBlock();
  35592. if (this.current.nodes && this.current.nodes.length) {
  35593. this.current.raws.semicolon = this.semicolon;
  35594. }
  35595. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  35596. this.root.source.end = this.getPosition(this.tokenizer.position());
  35597. }
  35598. freeSemicolon(token) {
  35599. this.spaces += token[1];
  35600. if (this.current.nodes) {
  35601. let prev = this.current.nodes[this.current.nodes.length - 1];
  35602. if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
  35603. prev.raws.ownSemicolon = this.spaces;
  35604. this.spaces = '';
  35605. prev.source.end = this.getPosition(token[2]);
  35606. prev.source.end.offset += prev.raws.ownSemicolon.length;
  35607. }
  35608. }
  35609. }
  35610. // Helpers
  35611. getPosition(offset) {
  35612. let pos = this.input.fromOffset(offset);
  35613. return {
  35614. column: pos.col,
  35615. line: pos.line,
  35616. offset
  35617. }
  35618. }
  35619. init(node, offset) {
  35620. this.current.push(node);
  35621. node.source = {
  35622. input: this.input,
  35623. start: this.getPosition(offset)
  35624. };
  35625. node.raws.before = this.spaces;
  35626. this.spaces = '';
  35627. if (node.type !== 'comment') this.semicolon = false;
  35628. }
  35629. other(start) {
  35630. let end = false;
  35631. let type = null;
  35632. let colon = false;
  35633. let bracket = null;
  35634. let brackets = [];
  35635. let customProperty = start[1].startsWith('--');
  35636. let tokens = [];
  35637. let token = start;
  35638. while (token) {
  35639. type = token[0];
  35640. tokens.push(token);
  35641. if (type === '(' || type === '[') {
  35642. if (!bracket) bracket = token;
  35643. brackets.push(type === '(' ? ')' : ']');
  35644. } else if (customProperty && colon && type === '{') {
  35645. if (!bracket) bracket = token;
  35646. brackets.push('}');
  35647. } else if (brackets.length === 0) {
  35648. if (type === ';') {
  35649. if (colon) {
  35650. this.decl(tokens, customProperty);
  35651. return
  35652. } else {
  35653. break
  35654. }
  35655. } else if (type === '{') {
  35656. this.rule(tokens);
  35657. return
  35658. } else if (type === '}') {
  35659. this.tokenizer.back(tokens.pop());
  35660. end = true;
  35661. break
  35662. } else if (type === ':') {
  35663. colon = true;
  35664. }
  35665. } else if (type === brackets[brackets.length - 1]) {
  35666. brackets.pop();
  35667. if (brackets.length === 0) bracket = null;
  35668. }
  35669. token = this.tokenizer.nextToken();
  35670. }
  35671. if (this.tokenizer.endOfFile()) end = true;
  35672. if (brackets.length > 0) this.unclosedBracket(bracket);
  35673. if (end && colon) {
  35674. if (!customProperty) {
  35675. while (tokens.length) {
  35676. token = tokens[tokens.length - 1][0];
  35677. if (token !== 'space' && token !== 'comment') break
  35678. this.tokenizer.back(tokens.pop());
  35679. }
  35680. }
  35681. this.decl(tokens, customProperty);
  35682. } else {
  35683. this.unknownWord(tokens);
  35684. }
  35685. }
  35686. parse() {
  35687. let token;
  35688. while (!this.tokenizer.endOfFile()) {
  35689. token = this.tokenizer.nextToken();
  35690. switch (token[0]) {
  35691. case 'space':
  35692. this.spaces += token[1];
  35693. break
  35694. case ';':
  35695. this.freeSemicolon(token);
  35696. break
  35697. case '}':
  35698. this.end(token);
  35699. break
  35700. case 'comment':
  35701. this.comment(token);
  35702. break
  35703. case 'at-word':
  35704. this.atrule(token);
  35705. break
  35706. case '{':
  35707. this.emptyRule(token);
  35708. break
  35709. default:
  35710. this.other(token);
  35711. break
  35712. }
  35713. }
  35714. this.endFile();
  35715. }
  35716. precheckMissedSemicolon(/* tokens */) {
  35717. // Hook for Safe Parser
  35718. }
  35719. raw(node, prop, tokens, customProperty) {
  35720. let token, type;
  35721. let length = tokens.length;
  35722. let value = '';
  35723. let clean = true;
  35724. let next, prev;
  35725. for (let i = 0; i < length; i += 1) {
  35726. token = tokens[i];
  35727. type = token[0];
  35728. if (type === 'space' && i === length - 1 && !customProperty) {
  35729. clean = false;
  35730. } else if (type === 'comment') {
  35731. prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty';
  35732. next = tokens[i + 1] ? tokens[i + 1][0] : 'empty';
  35733. if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
  35734. if (value.slice(-1) === ',') {
  35735. clean = false;
  35736. } else {
  35737. value += token[1];
  35738. }
  35739. } else {
  35740. clean = false;
  35741. }
  35742. } else {
  35743. value += token[1];
  35744. }
  35745. }
  35746. if (!clean) {
  35747. let raw = tokens.reduce((all, i) => all + i[1], '');
  35748. node.raws[prop] = { raw, value };
  35749. }
  35750. node[prop] = value;
  35751. }
  35752. rule(tokens) {
  35753. tokens.pop();
  35754. let node = new Rule();
  35755. this.init(node, tokens[0][2]);
  35756. node.raws.between = this.spacesAndCommentsFromEnd(tokens);
  35757. this.raw(node, 'selector', tokens);
  35758. this.current = node;
  35759. }
  35760. spacesAndCommentsFromEnd(tokens) {
  35761. let lastTokenType;
  35762. let spaces = '';
  35763. while (tokens.length) {
  35764. lastTokenType = tokens[tokens.length - 1][0];
  35765. if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
  35766. spaces = tokens.pop()[1] + spaces;
  35767. }
  35768. return spaces
  35769. }
  35770. // Errors
  35771. spacesAndCommentsFromStart(tokens) {
  35772. let next;
  35773. let spaces = '';
  35774. while (tokens.length) {
  35775. next = tokens[0][0];
  35776. if (next !== 'space' && next !== 'comment') break
  35777. spaces += tokens.shift()[1];
  35778. }
  35779. return spaces
  35780. }
  35781. spacesFromEnd(tokens) {
  35782. let lastTokenType;
  35783. let spaces = '';
  35784. while (tokens.length) {
  35785. lastTokenType = tokens[tokens.length - 1][0];
  35786. if (lastTokenType !== 'space') break
  35787. spaces = tokens.pop()[1] + spaces;
  35788. }
  35789. return spaces
  35790. }
  35791. stringFrom(tokens, from) {
  35792. let result = '';
  35793. for (let i = from; i < tokens.length; i++) {
  35794. result += tokens[i][1];
  35795. }
  35796. tokens.splice(from, tokens.length - from);
  35797. return result
  35798. }
  35799. unclosedBlock() {
  35800. let pos = this.current.source.start;
  35801. throw this.input.error('Unclosed block', pos.line, pos.column)
  35802. }
  35803. unclosedBracket(bracket) {
  35804. throw this.input.error(
  35805. 'Unclosed bracket',
  35806. { offset: bracket[2] },
  35807. { offset: bracket[2] + 1 }
  35808. )
  35809. }
  35810. unexpectedClose(token) {
  35811. throw this.input.error(
  35812. 'Unexpected }',
  35813. { offset: token[2] },
  35814. { offset: token[2] + 1 }
  35815. )
  35816. }
  35817. unknownWord(tokens) {
  35818. throw this.input.error(
  35819. 'Unknown word ' + tokens[0][1],
  35820. { offset: tokens[0][2] },
  35821. { offset: tokens[0][2] + tokens[0][1].length }
  35822. )
  35823. }
  35824. unnamedAtrule(node, token) {
  35825. throw this.input.error(
  35826. 'At-rule without name',
  35827. { offset: token[2] },
  35828. { offset: token[2] + token[1].length }
  35829. )
  35830. }
  35831. }
  35832. parser$1 = Parser;
  35833. return parser$1;
  35834. }
  35835. var parse_1;
  35836. var hasRequiredParse;
  35837. function requireParse () {
  35838. if (hasRequiredParse) return parse_1;
  35839. hasRequiredParse = 1;
  35840. let Container = /*@__PURE__*/ requireContainer$1();
  35841. let Input = /*@__PURE__*/ requireInput();
  35842. let Parser = /*@__PURE__*/ requireParser$1();
  35843. function parse(css, opts) {
  35844. let input = new Input(css, opts);
  35845. let parser = new Parser(input);
  35846. try {
  35847. parser.parse();
  35848. } catch (e) {
  35849. if (browser$1.env.NODE_ENV !== 'production') {
  35850. if (e.name === 'CssSyntaxError' && opts && opts.from) {
  35851. if (/\.scss$/i.test(opts.from)) {
  35852. e.message +=
  35853. '\nYou tried to parse SCSS with ' +
  35854. 'the standard CSS parser; ' +
  35855. 'try again with the postcss-scss parser';
  35856. } else if (/\.sass/i.test(opts.from)) {
  35857. e.message +=
  35858. '\nYou tried to parse Sass with ' +
  35859. 'the standard CSS parser; ' +
  35860. 'try again with the postcss-sass parser';
  35861. } else if (/\.less$/i.test(opts.from)) {
  35862. e.message +=
  35863. '\nYou tried to parse Less with ' +
  35864. 'the standard CSS parser; ' +
  35865. 'try again with the postcss-less parser';
  35866. }
  35867. }
  35868. }
  35869. throw e
  35870. }
  35871. return parser.root
  35872. }
  35873. parse_1 = parse;
  35874. parse.default = parse;
  35875. Container.registerParse(parse);
  35876. return parse_1;
  35877. }
  35878. var warning;
  35879. var hasRequiredWarning;
  35880. function requireWarning () {
  35881. if (hasRequiredWarning) return warning;
  35882. hasRequiredWarning = 1;
  35883. class Warning {
  35884. constructor(text, opts = {}) {
  35885. this.type = 'warning';
  35886. this.text = text;
  35887. if (opts.node && opts.node.source) {
  35888. let range = opts.node.rangeBy(opts);
  35889. this.line = range.start.line;
  35890. this.column = range.start.column;
  35891. this.endLine = range.end.line;
  35892. this.endColumn = range.end.column;
  35893. }
  35894. for (let opt in opts) this[opt] = opts[opt];
  35895. }
  35896. toString() {
  35897. if (this.node) {
  35898. return this.node.error(this.text, {
  35899. index: this.index,
  35900. plugin: this.plugin,
  35901. word: this.word
  35902. }).message
  35903. }
  35904. if (this.plugin) {
  35905. return this.plugin + ': ' + this.text
  35906. }
  35907. return this.text
  35908. }
  35909. }
  35910. warning = Warning;
  35911. Warning.default = Warning;
  35912. return warning;
  35913. }
  35914. var result;
  35915. var hasRequiredResult;
  35916. function requireResult () {
  35917. if (hasRequiredResult) return result;
  35918. hasRequiredResult = 1;
  35919. let Warning = /*@__PURE__*/ requireWarning();
  35920. class Result {
  35921. get content() {
  35922. return this.css
  35923. }
  35924. constructor(processor, root, opts) {
  35925. this.processor = processor;
  35926. this.messages = [];
  35927. this.root = root;
  35928. this.opts = opts;
  35929. this.css = '';
  35930. this.map = undefined;
  35931. }
  35932. toString() {
  35933. return this.css
  35934. }
  35935. warn(text, opts = {}) {
  35936. if (!opts.plugin) {
  35937. if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
  35938. opts.plugin = this.lastPlugin.postcssPlugin;
  35939. }
  35940. }
  35941. let warning = new Warning(text, opts);
  35942. this.messages.push(warning);
  35943. return warning
  35944. }
  35945. warnings() {
  35946. return this.messages.filter(i => i.type === 'warning')
  35947. }
  35948. }
  35949. result = Result;
  35950. Result.default = Result;
  35951. return result;
  35952. }
  35953. /* eslint-disable no-console */
  35954. var warnOnce;
  35955. var hasRequiredWarnOnce;
  35956. function requireWarnOnce () {
  35957. if (hasRequiredWarnOnce) return warnOnce;
  35958. hasRequiredWarnOnce = 1;
  35959. let printed = {};
  35960. warnOnce = function warnOnce(message) {
  35961. if (printed[message]) return
  35962. printed[message] = true;
  35963. if (typeof console !== 'undefined' && console.warn) {
  35964. console.warn(message);
  35965. }
  35966. };
  35967. return warnOnce;
  35968. }
  35969. var lazyResult;
  35970. var hasRequiredLazyResult;
  35971. function requireLazyResult () {
  35972. if (hasRequiredLazyResult) return lazyResult;
  35973. hasRequiredLazyResult = 1;
  35974. let Container = /*@__PURE__*/ requireContainer$1();
  35975. let Document = /*@__PURE__*/ requireDocument();
  35976. let MapGenerator = /*@__PURE__*/ requireMapGenerator();
  35977. let parse = /*@__PURE__*/ requireParse();
  35978. let Result = /*@__PURE__*/ requireResult();
  35979. let Root = /*@__PURE__*/ requireRoot$1();
  35980. let stringify = /*@__PURE__*/ requireStringify();
  35981. let { isClean, my } = /*@__PURE__*/ requireSymbols();
  35982. let warnOnce = /*@__PURE__*/ requireWarnOnce();
  35983. const TYPE_TO_CLASS_NAME = {
  35984. atrule: 'AtRule',
  35985. comment: 'Comment',
  35986. decl: 'Declaration',
  35987. document: 'Document',
  35988. root: 'Root',
  35989. rule: 'Rule'
  35990. };
  35991. const PLUGIN_PROPS = {
  35992. AtRule: true,
  35993. AtRuleExit: true,
  35994. Comment: true,
  35995. CommentExit: true,
  35996. Declaration: true,
  35997. DeclarationExit: true,
  35998. Document: true,
  35999. DocumentExit: true,
  36000. Once: true,
  36001. OnceExit: true,
  36002. postcssPlugin: true,
  36003. prepare: true,
  36004. Root: true,
  36005. RootExit: true,
  36006. Rule: true,
  36007. RuleExit: true
  36008. };
  36009. const NOT_VISITORS = {
  36010. Once: true,
  36011. postcssPlugin: true,
  36012. prepare: true
  36013. };
  36014. const CHILDREN = 0;
  36015. function isPromise(obj) {
  36016. return typeof obj === 'object' && typeof obj.then === 'function'
  36017. }
  36018. function getEvents(node) {
  36019. let key = false;
  36020. let type = TYPE_TO_CLASS_NAME[node.type];
  36021. if (node.type === 'decl') {
  36022. key = node.prop.toLowerCase();
  36023. } else if (node.type === 'atrule') {
  36024. key = node.name.toLowerCase();
  36025. }
  36026. if (key && node.append) {
  36027. return [
  36028. type,
  36029. type + '-' + key,
  36030. CHILDREN,
  36031. type + 'Exit',
  36032. type + 'Exit-' + key
  36033. ]
  36034. } else if (key) {
  36035. return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
  36036. } else if (node.append) {
  36037. return [type, CHILDREN, type + 'Exit']
  36038. } else {
  36039. return [type, type + 'Exit']
  36040. }
  36041. }
  36042. function toStack(node) {
  36043. let events;
  36044. if (node.type === 'document') {
  36045. events = ['Document', CHILDREN, 'DocumentExit'];
  36046. } else if (node.type === 'root') {
  36047. events = ['Root', CHILDREN, 'RootExit'];
  36048. } else {
  36049. events = getEvents(node);
  36050. }
  36051. return {
  36052. eventIndex: 0,
  36053. events,
  36054. iterator: 0,
  36055. node,
  36056. visitorIndex: 0,
  36057. visitors: []
  36058. }
  36059. }
  36060. function cleanMarks(node) {
  36061. node[isClean] = false;
  36062. if (node.nodes) node.nodes.forEach(i => cleanMarks(i));
  36063. return node
  36064. }
  36065. let postcss = {};
  36066. class LazyResult {
  36067. get content() {
  36068. return this.stringify().content
  36069. }
  36070. get css() {
  36071. return this.stringify().css
  36072. }
  36073. get map() {
  36074. return this.stringify().map
  36075. }
  36076. get messages() {
  36077. return this.sync().messages
  36078. }
  36079. get opts() {
  36080. return this.result.opts
  36081. }
  36082. get processor() {
  36083. return this.result.processor
  36084. }
  36085. get root() {
  36086. return this.sync().root
  36087. }
  36088. get [Symbol.toStringTag]() {
  36089. return 'LazyResult'
  36090. }
  36091. constructor(processor, css, opts) {
  36092. this.stringified = false;
  36093. this.processed = false;
  36094. let root;
  36095. if (
  36096. typeof css === 'object' &&
  36097. css !== null &&
  36098. (css.type === 'root' || css.type === 'document')
  36099. ) {
  36100. root = cleanMarks(css);
  36101. } else if (css instanceof LazyResult || css instanceof Result) {
  36102. root = cleanMarks(css.root);
  36103. if (css.map) {
  36104. if (typeof opts.map === 'undefined') opts.map = {};
  36105. if (!opts.map.inline) opts.map.inline = false;
  36106. opts.map.prev = css.map;
  36107. }
  36108. } else {
  36109. let parser = parse;
  36110. if (opts.syntax) parser = opts.syntax.parse;
  36111. if (opts.parser) parser = opts.parser;
  36112. if (parser.parse) parser = parser.parse;
  36113. try {
  36114. root = parser(css, opts);
  36115. } catch (error) {
  36116. this.processed = true;
  36117. this.error = error;
  36118. }
  36119. if (root && !root[my]) {
  36120. /* c8 ignore next 2 */
  36121. Container.rebuild(root);
  36122. }
  36123. }
  36124. this.result = new Result(processor, root, opts);
  36125. this.helpers = { ...postcss, postcss, result: this.result };
  36126. this.plugins = this.processor.plugins.map(plugin => {
  36127. if (typeof plugin === 'object' && plugin.prepare) {
  36128. return { ...plugin, ...plugin.prepare(this.result) }
  36129. } else {
  36130. return plugin
  36131. }
  36132. });
  36133. }
  36134. async() {
  36135. if (this.error) return Promise.reject(this.error)
  36136. if (this.processed) return Promise.resolve(this.result)
  36137. if (!this.processing) {
  36138. this.processing = this.runAsync();
  36139. }
  36140. return this.processing
  36141. }
  36142. catch(onRejected) {
  36143. return this.async().catch(onRejected)
  36144. }
  36145. finally(onFinally) {
  36146. return this.async().then(onFinally, onFinally)
  36147. }
  36148. getAsyncError() {
  36149. throw new Error('Use process(css).then(cb) to work with async plugins')
  36150. }
  36151. handleError(error, node) {
  36152. let plugin = this.result.lastPlugin;
  36153. try {
  36154. if (node) node.addToError(error);
  36155. this.error = error;
  36156. if (error.name === 'CssSyntaxError' && !error.plugin) {
  36157. error.plugin = plugin.postcssPlugin;
  36158. error.setMessage();
  36159. } else if (plugin.postcssVersion) {
  36160. if (browser$1.env.NODE_ENV !== 'production') {
  36161. let pluginName = plugin.postcssPlugin;
  36162. let pluginVer = plugin.postcssVersion;
  36163. let runtimeVer = this.result.processor.version;
  36164. let a = pluginVer.split('.');
  36165. let b = runtimeVer.split('.');
  36166. if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
  36167. // eslint-disable-next-line no-console
  36168. console.error(
  36169. 'Unknown error from PostCSS plugin. Your current PostCSS ' +
  36170. 'version is ' +
  36171. runtimeVer +
  36172. ', but ' +
  36173. pluginName +
  36174. ' uses ' +
  36175. pluginVer +
  36176. '. Perhaps this is the source of the error below.'
  36177. );
  36178. }
  36179. }
  36180. }
  36181. } catch (err) {
  36182. /* c8 ignore next 3 */
  36183. // eslint-disable-next-line no-console
  36184. if (console && console.error) console.error(err);
  36185. }
  36186. return error
  36187. }
  36188. prepareVisitors() {
  36189. this.listeners = {};
  36190. let add = (plugin, type, cb) => {
  36191. if (!this.listeners[type]) this.listeners[type] = [];
  36192. this.listeners[type].push([plugin, cb]);
  36193. };
  36194. for (let plugin of this.plugins) {
  36195. if (typeof plugin === 'object') {
  36196. for (let event in plugin) {
  36197. if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
  36198. throw new Error(
  36199. `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
  36200. `Try to update PostCSS (${this.processor.version} now).`
  36201. )
  36202. }
  36203. if (!NOT_VISITORS[event]) {
  36204. if (typeof plugin[event] === 'object') {
  36205. for (let filter in plugin[event]) {
  36206. if (filter === '*') {
  36207. add(plugin, event, plugin[event][filter]);
  36208. } else {
  36209. add(
  36210. plugin,
  36211. event + '-' + filter.toLowerCase(),
  36212. plugin[event][filter]
  36213. );
  36214. }
  36215. }
  36216. } else if (typeof plugin[event] === 'function') {
  36217. add(plugin, event, plugin[event]);
  36218. }
  36219. }
  36220. }
  36221. }
  36222. }
  36223. this.hasListener = Object.keys(this.listeners).length > 0;
  36224. }
  36225. async runAsync() {
  36226. this.plugin = 0;
  36227. for (let i = 0; i < this.plugins.length; i++) {
  36228. let plugin = this.plugins[i];
  36229. let promise = this.runOnRoot(plugin);
  36230. if (isPromise(promise)) {
  36231. try {
  36232. await promise;
  36233. } catch (error) {
  36234. throw this.handleError(error)
  36235. }
  36236. }
  36237. }
  36238. this.prepareVisitors();
  36239. if (this.hasListener) {
  36240. let root = this.result.root;
  36241. while (!root[isClean]) {
  36242. root[isClean] = true;
  36243. let stack = [toStack(root)];
  36244. while (stack.length > 0) {
  36245. let promise = this.visitTick(stack);
  36246. if (isPromise(promise)) {
  36247. try {
  36248. await promise;
  36249. } catch (e) {
  36250. let node = stack[stack.length - 1].node;
  36251. throw this.handleError(e, node)
  36252. }
  36253. }
  36254. }
  36255. }
  36256. if (this.listeners.OnceExit) {
  36257. for (let [plugin, visitor] of this.listeners.OnceExit) {
  36258. this.result.lastPlugin = plugin;
  36259. try {
  36260. if (root.type === 'document') {
  36261. let roots = root.nodes.map(subRoot =>
  36262. visitor(subRoot, this.helpers)
  36263. );
  36264. await Promise.all(roots);
  36265. } else {
  36266. await visitor(root, this.helpers);
  36267. }
  36268. } catch (e) {
  36269. throw this.handleError(e)
  36270. }
  36271. }
  36272. }
  36273. }
  36274. this.processed = true;
  36275. return this.stringify()
  36276. }
  36277. runOnRoot(plugin) {
  36278. this.result.lastPlugin = plugin;
  36279. try {
  36280. if (typeof plugin === 'object' && plugin.Once) {
  36281. if (this.result.root.type === 'document') {
  36282. let roots = this.result.root.nodes.map(root =>
  36283. plugin.Once(root, this.helpers)
  36284. );
  36285. if (isPromise(roots[0])) {
  36286. return Promise.all(roots)
  36287. }
  36288. return roots
  36289. }
  36290. return plugin.Once(this.result.root, this.helpers)
  36291. } else if (typeof plugin === 'function') {
  36292. return plugin(this.result.root, this.result)
  36293. }
  36294. } catch (error) {
  36295. throw this.handleError(error)
  36296. }
  36297. }
  36298. stringify() {
  36299. if (this.error) throw this.error
  36300. if (this.stringified) return this.result
  36301. this.stringified = true;
  36302. this.sync();
  36303. let opts = this.result.opts;
  36304. let str = stringify;
  36305. if (opts.syntax) str = opts.syntax.stringify;
  36306. if (opts.stringifier) str = opts.stringifier;
  36307. if (str.stringify) str = str.stringify;
  36308. let rootSource = this.result.root.source;
  36309. if (
  36310. opts.map === undefined &&
  36311. !(rootSource && rootSource.input && rootSource.input.map)
  36312. ) {
  36313. let result = '';
  36314. str(this.result.root, i => {
  36315. result += i;
  36316. });
  36317. this.result.css = result;
  36318. return this.result
  36319. }
  36320. let map = new MapGenerator(str, this.result.root, this.result.opts);
  36321. let data = map.generate();
  36322. this.result.css = data[0];
  36323. this.result.map = data[1];
  36324. return this.result
  36325. }
  36326. sync() {
  36327. if (this.error) throw this.error
  36328. if (this.processed) return this.result
  36329. this.processed = true;
  36330. if (this.processing) {
  36331. throw this.getAsyncError()
  36332. }
  36333. for (let plugin of this.plugins) {
  36334. let promise = this.runOnRoot(plugin);
  36335. if (isPromise(promise)) {
  36336. throw this.getAsyncError()
  36337. }
  36338. }
  36339. this.prepareVisitors();
  36340. if (this.hasListener) {
  36341. let root = this.result.root;
  36342. while (!root[isClean]) {
  36343. root[isClean] = true;
  36344. this.walkSync(root);
  36345. }
  36346. if (this.listeners.OnceExit) {
  36347. if (root.type === 'document') {
  36348. for (let subRoot of root.nodes) {
  36349. this.visitSync(this.listeners.OnceExit, subRoot);
  36350. }
  36351. } else {
  36352. this.visitSync(this.listeners.OnceExit, root);
  36353. }
  36354. }
  36355. }
  36356. return this.result
  36357. }
  36358. then(onFulfilled, onRejected) {
  36359. if (browser$1.env.NODE_ENV !== 'production') {
  36360. if (!('from' in this.opts)) {
  36361. warnOnce(
  36362. 'Without `from` option PostCSS could generate wrong source map ' +
  36363. 'and will not find Browserslist config. Set it to CSS file path ' +
  36364. 'or to `undefined` to prevent this warning.'
  36365. );
  36366. }
  36367. }
  36368. return this.async().then(onFulfilled, onRejected)
  36369. }
  36370. toString() {
  36371. return this.css
  36372. }
  36373. visitSync(visitors, node) {
  36374. for (let [plugin, visitor] of visitors) {
  36375. this.result.lastPlugin = plugin;
  36376. let promise;
  36377. try {
  36378. promise = visitor(node, this.helpers);
  36379. } catch (e) {
  36380. throw this.handleError(e, node.proxyOf)
  36381. }
  36382. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  36383. return true
  36384. }
  36385. if (isPromise(promise)) {
  36386. throw this.getAsyncError()
  36387. }
  36388. }
  36389. }
  36390. visitTick(stack) {
  36391. let visit = stack[stack.length - 1];
  36392. let { node, visitors } = visit;
  36393. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  36394. stack.pop();
  36395. return
  36396. }
  36397. if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
  36398. let [plugin, visitor] = visitors[visit.visitorIndex];
  36399. visit.visitorIndex += 1;
  36400. if (visit.visitorIndex === visitors.length) {
  36401. visit.visitors = [];
  36402. visit.visitorIndex = 0;
  36403. }
  36404. this.result.lastPlugin = plugin;
  36405. try {
  36406. return visitor(node.toProxy(), this.helpers)
  36407. } catch (e) {
  36408. throw this.handleError(e, node)
  36409. }
  36410. }
  36411. if (visit.iterator !== 0) {
  36412. let iterator = visit.iterator;
  36413. let child;
  36414. while ((child = node.nodes[node.indexes[iterator]])) {
  36415. node.indexes[iterator] += 1;
  36416. if (!child[isClean]) {
  36417. child[isClean] = true;
  36418. stack.push(toStack(child));
  36419. return
  36420. }
  36421. }
  36422. visit.iterator = 0;
  36423. delete node.indexes[iterator];
  36424. }
  36425. let events = visit.events;
  36426. while (visit.eventIndex < events.length) {
  36427. let event = events[visit.eventIndex];
  36428. visit.eventIndex += 1;
  36429. if (event === CHILDREN) {
  36430. if (node.nodes && node.nodes.length) {
  36431. node[isClean] = true;
  36432. visit.iterator = node.getIterator();
  36433. }
  36434. return
  36435. } else if (this.listeners[event]) {
  36436. visit.visitors = this.listeners[event];
  36437. return
  36438. }
  36439. }
  36440. stack.pop();
  36441. }
  36442. walkSync(node) {
  36443. node[isClean] = true;
  36444. let events = getEvents(node);
  36445. for (let event of events) {
  36446. if (event === CHILDREN) {
  36447. if (node.nodes) {
  36448. node.each(child => {
  36449. if (!child[isClean]) this.walkSync(child);
  36450. });
  36451. }
  36452. } else {
  36453. let visitors = this.listeners[event];
  36454. if (visitors) {
  36455. if (this.visitSync(visitors, node.toProxy())) return
  36456. }
  36457. }
  36458. }
  36459. }
  36460. warnings() {
  36461. return this.sync().warnings()
  36462. }
  36463. }
  36464. LazyResult.registerPostcss = dependant => {
  36465. postcss = dependant;
  36466. };
  36467. lazyResult = LazyResult;
  36468. LazyResult.default = LazyResult;
  36469. Root.registerLazyResult(LazyResult);
  36470. Document.registerLazyResult(LazyResult);
  36471. return lazyResult;
  36472. }
  36473. var noWorkResult;
  36474. var hasRequiredNoWorkResult;
  36475. function requireNoWorkResult () {
  36476. if (hasRequiredNoWorkResult) return noWorkResult;
  36477. hasRequiredNoWorkResult = 1;
  36478. let MapGenerator = /*@__PURE__*/ requireMapGenerator();
  36479. let parse = /*@__PURE__*/ requireParse();
  36480. let Result = /*@__PURE__*/ requireResult();
  36481. let stringify = /*@__PURE__*/ requireStringify();
  36482. let warnOnce = /*@__PURE__*/ requireWarnOnce();
  36483. class NoWorkResult {
  36484. get content() {
  36485. return this.result.css
  36486. }
  36487. get css() {
  36488. return this.result.css
  36489. }
  36490. get map() {
  36491. return this.result.map
  36492. }
  36493. get messages() {
  36494. return []
  36495. }
  36496. get opts() {
  36497. return this.result.opts
  36498. }
  36499. get processor() {
  36500. return this.result.processor
  36501. }
  36502. get root() {
  36503. if (this._root) {
  36504. return this._root
  36505. }
  36506. let root;
  36507. let parser = parse;
  36508. try {
  36509. root = parser(this._css, this._opts);
  36510. } catch (error) {
  36511. this.error = error;
  36512. }
  36513. if (this.error) {
  36514. throw this.error
  36515. } else {
  36516. this._root = root;
  36517. return root
  36518. }
  36519. }
  36520. get [Symbol.toStringTag]() {
  36521. return 'NoWorkResult'
  36522. }
  36523. constructor(processor, css, opts) {
  36524. css = css.toString();
  36525. this.stringified = false;
  36526. this._processor = processor;
  36527. this._css = css;
  36528. this._opts = opts;
  36529. this._map = undefined;
  36530. let str = stringify;
  36531. this.result = new Result(this._processor, undefined, this._opts);
  36532. this.result.css = css;
  36533. let self = this;
  36534. Object.defineProperty(this.result, 'root', {
  36535. get() {
  36536. return self.root
  36537. }
  36538. });
  36539. let map = new MapGenerator(str, undefined, this._opts, css);
  36540. if (map.isMap()) {
  36541. let [generatedCSS, generatedMap] = map.generate();
  36542. if (generatedCSS) {
  36543. this.result.css = generatedCSS;
  36544. }
  36545. if (generatedMap) {
  36546. this.result.map = generatedMap;
  36547. }
  36548. } else {
  36549. map.clearAnnotation();
  36550. this.result.css = map.css;
  36551. }
  36552. }
  36553. async() {
  36554. if (this.error) return Promise.reject(this.error)
  36555. return Promise.resolve(this.result)
  36556. }
  36557. catch(onRejected) {
  36558. return this.async().catch(onRejected)
  36559. }
  36560. finally(onFinally) {
  36561. return this.async().then(onFinally, onFinally)
  36562. }
  36563. sync() {
  36564. if (this.error) throw this.error
  36565. return this.result
  36566. }
  36567. then(onFulfilled, onRejected) {
  36568. if (browser$1.env.NODE_ENV !== 'production') {
  36569. if (!('from' in this._opts)) {
  36570. warnOnce(
  36571. 'Without `from` option PostCSS could generate wrong source map ' +
  36572. 'and will not find Browserslist config. Set it to CSS file path ' +
  36573. 'or to `undefined` to prevent this warning.'
  36574. );
  36575. }
  36576. }
  36577. return this.async().then(onFulfilled, onRejected)
  36578. }
  36579. toString() {
  36580. return this._css
  36581. }
  36582. warnings() {
  36583. return []
  36584. }
  36585. }
  36586. noWorkResult = NoWorkResult;
  36587. NoWorkResult.default = NoWorkResult;
  36588. return noWorkResult;
  36589. }
  36590. var processor$1;
  36591. var hasRequiredProcessor$1;
  36592. function requireProcessor$1 () {
  36593. if (hasRequiredProcessor$1) return processor$1;
  36594. hasRequiredProcessor$1 = 1;
  36595. let Document = /*@__PURE__*/ requireDocument();
  36596. let LazyResult = /*@__PURE__*/ requireLazyResult();
  36597. let NoWorkResult = /*@__PURE__*/ requireNoWorkResult();
  36598. let Root = /*@__PURE__*/ requireRoot$1();
  36599. class Processor {
  36600. constructor(plugins = []) {
  36601. this.version = '8.5.15';
  36602. this.plugins = this.normalize(plugins);
  36603. }
  36604. normalize(plugins) {
  36605. let normalized = [];
  36606. for (let i of plugins) {
  36607. if (i.postcss === true) {
  36608. i = i();
  36609. } else if (i.postcss) {
  36610. i = i.postcss;
  36611. }
  36612. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  36613. normalized = normalized.concat(i.plugins);
  36614. } else if (typeof i === 'object' && i.postcssPlugin) {
  36615. normalized.push(i);
  36616. } else if (typeof i === 'function') {
  36617. normalized.push(i);
  36618. } else if (typeof i === 'object' && (i.parse || i.stringify)) {
  36619. if (browser$1.env.NODE_ENV !== 'production') {
  36620. throw new Error(
  36621. 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
  36622. 'one of the syntax/parser/stringifier options as outlined ' +
  36623. 'in your PostCSS runner documentation.'
  36624. )
  36625. }
  36626. } else {
  36627. throw new Error(i + ' is not a PostCSS plugin')
  36628. }
  36629. }
  36630. return normalized
  36631. }
  36632. process(css, opts = {}) {
  36633. if (
  36634. !this.plugins.length &&
  36635. !opts.parser &&
  36636. !opts.stringifier &&
  36637. !opts.syntax
  36638. ) {
  36639. return new NoWorkResult(this, css, opts)
  36640. } else {
  36641. return new LazyResult(this, css, opts)
  36642. }
  36643. }
  36644. use(plugin) {
  36645. this.plugins = this.plugins.concat(this.normalize([plugin]));
  36646. return this
  36647. }
  36648. }
  36649. processor$1 = Processor;
  36650. Processor.default = Processor;
  36651. Root.registerProcessor(Processor);
  36652. Document.registerProcessor(Processor);
  36653. return processor$1;
  36654. }
  36655. var postcss_1;
  36656. var hasRequiredPostcss;
  36657. function requirePostcss () {
  36658. if (hasRequiredPostcss) return postcss_1;
  36659. hasRequiredPostcss = 1;
  36660. let AtRule = /*@__PURE__*/ requireAtRule();
  36661. let Comment = /*@__PURE__*/ requireComment$1();
  36662. let Container = /*@__PURE__*/ requireContainer$1();
  36663. let CssSyntaxError = /*@__PURE__*/ requireCssSyntaxError();
  36664. let Declaration = /*@__PURE__*/ requireDeclaration();
  36665. let Document = /*@__PURE__*/ requireDocument();
  36666. let fromJSON = /*@__PURE__*/ requireFromJSON();
  36667. let Input = /*@__PURE__*/ requireInput();
  36668. let LazyResult = /*@__PURE__*/ requireLazyResult();
  36669. let list = /*@__PURE__*/ requireList();
  36670. let Node = /*@__PURE__*/ requireNode$2();
  36671. let parse = /*@__PURE__*/ requireParse();
  36672. let Processor = /*@__PURE__*/ requireProcessor$1();
  36673. let Result = /*@__PURE__*/ requireResult();
  36674. let Root = /*@__PURE__*/ requireRoot$1();
  36675. let Rule = /*@__PURE__*/ requireRule();
  36676. let stringify = /*@__PURE__*/ requireStringify();
  36677. let Warning = /*@__PURE__*/ requireWarning();
  36678. function postcss(...plugins) {
  36679. if (plugins.length === 1 && Array.isArray(plugins[0])) {
  36680. plugins = plugins[0];
  36681. }
  36682. return new Processor(plugins)
  36683. }
  36684. postcss.plugin = function plugin(name, initializer) {
  36685. let warningPrinted = false;
  36686. function creator(...args) {
  36687. // eslint-disable-next-line no-console
  36688. if (console && console.warn && !warningPrinted) {
  36689. warningPrinted = true;
  36690. // eslint-disable-next-line no-console
  36691. console.warn(
  36692. name +
  36693. ': postcss.plugin was deprecated. Migration guide:\n' +
  36694. 'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
  36695. );
  36696. if (browser$1.env.LANG && browser$1.env.LANG.startsWith('cn')) {
  36697. /* c8 ignore next 7 */
  36698. // eslint-disable-next-line no-console
  36699. console.warn(
  36700. name +
  36701. ': 里面 postcss.plugin 被弃用. 迁移指南:\n' +
  36702. 'https://www.w3ctech.com/topic/2226'
  36703. );
  36704. }
  36705. }
  36706. let transformer = initializer(...args);
  36707. transformer.postcssPlugin = name;
  36708. transformer.postcssVersion = new Processor().version;
  36709. return transformer
  36710. }
  36711. let cache;
  36712. Object.defineProperty(creator, 'postcss', {
  36713. get() {
  36714. if (!cache) cache = creator();
  36715. return cache
  36716. }
  36717. });
  36718. creator.process = function (css, processOpts, pluginOpts) {
  36719. return postcss([creator(pluginOpts)]).process(css, processOpts)
  36720. };
  36721. return creator
  36722. };
  36723. postcss.stringify = stringify;
  36724. postcss.parse = parse;
  36725. postcss.fromJSON = fromJSON;
  36726. postcss.list = list;
  36727. postcss.comment = defaults => new Comment(defaults);
  36728. postcss.atRule = defaults => new AtRule(defaults);
  36729. postcss.decl = defaults => new Declaration(defaults);
  36730. postcss.rule = defaults => new Rule(defaults);
  36731. postcss.root = defaults => new Root(defaults);
  36732. postcss.document = defaults => new Document(defaults);
  36733. postcss.CssSyntaxError = CssSyntaxError;
  36734. postcss.Declaration = Declaration;
  36735. postcss.Container = Container;
  36736. postcss.Processor = Processor;
  36737. postcss.Document = Document;
  36738. postcss.Comment = Comment;
  36739. postcss.Warning = Warning;
  36740. postcss.AtRule = AtRule;
  36741. postcss.Result = Result;
  36742. postcss.Input = Input;
  36743. postcss.Rule = Rule;
  36744. postcss.Root = Root;
  36745. postcss.Node = Node;
  36746. LazyResult.registerPostcss(postcss);
  36747. postcss_1 = postcss;
  36748. postcss.default = postcss;
  36749. return postcss_1;
  36750. }
  36751. var postcssExports = /*@__PURE__*/ requirePostcss();
  36752. var postcss = /*@__PURE__*/getDefaultExportFromCjs(postcssExports);
  36753. postcss.stringify;
  36754. postcss.fromJSON;
  36755. postcss.plugin;
  36756. postcss.parse;
  36757. postcss.list;
  36758. postcss.document;
  36759. postcss.comment;
  36760. postcss.atRule;
  36761. postcss.rule;
  36762. postcss.decl;
  36763. postcss.root;
  36764. postcss.CssSyntaxError;
  36765. postcss.Declaration;
  36766. postcss.Container;
  36767. postcss.Processor;
  36768. postcss.Document;
  36769. postcss.Comment;
  36770. postcss.Warning;
  36771. postcss.AtRule;
  36772. postcss.Result;
  36773. postcss.Input;
  36774. const Rule = postcss.Rule;
  36775. postcss.Root;
  36776. postcss.Node;
  36777. const trimPlugin = () => {
  36778. return {
  36779. postcssPlugin: "vue-sfc-trim",
  36780. Once(root) {
  36781. root.walk(({ type, raws }) => {
  36782. if (type === "rule" || type === "atrule") {
  36783. if (raws.before) raws.before = "\n";
  36784. if ("after" in raws && raws.after) raws.after = "\n";
  36785. }
  36786. });
  36787. }
  36788. };
  36789. };
  36790. trimPlugin.postcss = true;
  36791. var dist = {exports: {}};
  36792. var processor = {exports: {}};
  36793. var parser = {exports: {}};
  36794. var root = {exports: {}};
  36795. var container = {exports: {}};
  36796. var util$1 = {};
  36797. var unesc = {exports: {}};
  36798. var hasRequiredUnesc;
  36799. function requireUnesc () {
  36800. if (hasRequiredUnesc) return unesc.exports;
  36801. hasRequiredUnesc = 1;
  36802. (function (module, exports) {
  36803. exports.__esModule = true;
  36804. exports["default"] = unesc;
  36805. // Many thanks for this post which made this migration much easier.
  36806. // https://mathiasbynens.be/notes/css-escapes
  36807. /**
  36808. *
  36809. * @param {string} str
  36810. * @returns {[string, number]|undefined}
  36811. */
  36812. function gobbleHex(str) {
  36813. var lower = str.toLowerCase();
  36814. var hex = '';
  36815. var spaceTerminated = false;
  36816. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  36817. var code = lower.charCodeAt(i);
  36818. // check to see if we are dealing with a valid hex char [a-f|0-9]
  36819. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  36820. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  36821. spaceTerminated = code === 32;
  36822. if (!valid) {
  36823. break;
  36824. }
  36825. hex += lower[i];
  36826. }
  36827. if (hex.length === 0) {
  36828. return undefined;
  36829. }
  36830. var codePoint = parseInt(hex, 16);
  36831. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  36832. // Add special case for
  36833. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  36834. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  36835. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  36836. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  36837. }
  36838. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  36839. }
  36840. var CONTAINS_ESCAPE = /\\/;
  36841. function unesc(str) {
  36842. var needToProcess = CONTAINS_ESCAPE.test(str);
  36843. if (!needToProcess) {
  36844. return str;
  36845. }
  36846. var ret = "";
  36847. for (var i = 0; i < str.length; i++) {
  36848. if (str[i] === "\\") {
  36849. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  36850. if (gobbled !== undefined) {
  36851. ret += gobbled[0];
  36852. i += gobbled[1];
  36853. continue;
  36854. }
  36855. // Retain a pair of \\ if double escaped `\\\\`
  36856. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  36857. if (str[i + 1] === "\\") {
  36858. ret += "\\";
  36859. i++;
  36860. continue;
  36861. }
  36862. // if \\ is at the end of the string retain it
  36863. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  36864. if (str.length === i + 1) {
  36865. ret += str[i];
  36866. }
  36867. continue;
  36868. }
  36869. ret += str[i];
  36870. }
  36871. return ret;
  36872. }
  36873. module.exports = exports.default;
  36874. } (unesc, unesc.exports));
  36875. return unesc.exports;
  36876. }
  36877. var getProp = {exports: {}};
  36878. var hasRequiredGetProp;
  36879. function requireGetProp () {
  36880. if (hasRequiredGetProp) return getProp.exports;
  36881. hasRequiredGetProp = 1;
  36882. (function (module, exports) {
  36883. exports.__esModule = true;
  36884. exports["default"] = getProp;
  36885. function getProp(obj) {
  36886. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  36887. props[_key - 1] = arguments[_key];
  36888. }
  36889. while (props.length > 0) {
  36890. var prop = props.shift();
  36891. if (!obj[prop]) {
  36892. return undefined;
  36893. }
  36894. obj = obj[prop];
  36895. }
  36896. return obj;
  36897. }
  36898. module.exports = exports.default;
  36899. } (getProp, getProp.exports));
  36900. return getProp.exports;
  36901. }
  36902. var ensureObject = {exports: {}};
  36903. var hasRequiredEnsureObject;
  36904. function requireEnsureObject () {
  36905. if (hasRequiredEnsureObject) return ensureObject.exports;
  36906. hasRequiredEnsureObject = 1;
  36907. (function (module, exports) {
  36908. exports.__esModule = true;
  36909. exports["default"] = ensureObject;
  36910. function ensureObject(obj) {
  36911. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  36912. props[_key - 1] = arguments[_key];
  36913. }
  36914. while (props.length > 0) {
  36915. var prop = props.shift();
  36916. if (!obj[prop]) {
  36917. obj[prop] = {};
  36918. }
  36919. obj = obj[prop];
  36920. }
  36921. }
  36922. module.exports = exports.default;
  36923. } (ensureObject, ensureObject.exports));
  36924. return ensureObject.exports;
  36925. }
  36926. var stripComments = {exports: {}};
  36927. var hasRequiredStripComments;
  36928. function requireStripComments () {
  36929. if (hasRequiredStripComments) return stripComments.exports;
  36930. hasRequiredStripComments = 1;
  36931. (function (module, exports) {
  36932. exports.__esModule = true;
  36933. exports["default"] = stripComments;
  36934. function stripComments(str) {
  36935. var s = "";
  36936. var commentStart = str.indexOf("/*");
  36937. var lastEnd = 0;
  36938. while (commentStart >= 0) {
  36939. s = s + str.slice(lastEnd, commentStart);
  36940. var commentEnd = str.indexOf("*/", commentStart + 2);
  36941. if (commentEnd < 0) {
  36942. return s;
  36943. }
  36944. lastEnd = commentEnd + 2;
  36945. commentStart = str.indexOf("/*", lastEnd);
  36946. }
  36947. s = s + str.slice(lastEnd);
  36948. return s;
  36949. }
  36950. module.exports = exports.default;
  36951. } (stripComments, stripComments.exports));
  36952. return stripComments.exports;
  36953. }
  36954. var maxNestingDepth = {};
  36955. var hasRequiredMaxNestingDepth;
  36956. function requireMaxNestingDepth () {
  36957. if (hasRequiredMaxNestingDepth) return maxNestingDepth;
  36958. hasRequiredMaxNestingDepth = 1;
  36959. (function (exports) {
  36960. exports.__esModule = true;
  36961. exports.MAX_NESTING_DEPTH = void 0;
  36962. exports["default"] = resolveMaxNestingDepth;
  36963. /**
  36964. * The default maximum selector nesting depth allowed when parsing or
  36965. * serializing a selector. Going beyond this would otherwise recurse deeply
  36966. * enough to overflow the call stack (CVE-2026-9358 / CWE-674). Real-world
  36967. * selectors never get anywhere near this, so it acts purely as a safety net
  36968. * that turns an uncatchable stack overflow into a catchable error.
  36969. */
  36970. var MAX_NESTING_DEPTH = exports.MAX_NESTING_DEPTH = 256;
  36971. /**
  36972. * Coerce a user-supplied nesting-depth limit into a safe value. Anything that
  36973. * is not a non-negative safe integer (NaN, Infinity, negative numbers, or a
  36974. * non-number) would disable or break the guard, so it falls back to the
  36975. * default.
  36976. *
  36977. * @param {unknown} value the limit provided through the `maxNestingDepth` option
  36978. * @returns {number} a safe, non-negative integer limit
  36979. */
  36980. function resolveMaxNestingDepth(value) {
  36981. return Number.isSafeInteger(value) && value >= 0 ? value : MAX_NESTING_DEPTH;
  36982. }
  36983. } (maxNestingDepth));
  36984. return maxNestingDepth;
  36985. }
  36986. var hasRequiredUtil$1;
  36987. function requireUtil$1 () {
  36988. if (hasRequiredUtil$1) return util$1;
  36989. hasRequiredUtil$1 = 1;
  36990. util$1.__esModule = true;
  36991. util$1.unesc = util$1.stripComments = util$1.resolveMaxNestingDepth = util$1.getProp = util$1.ensureObject = util$1.MAX_NESTING_DEPTH = void 0;
  36992. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  36993. util$1.unesc = _unesc["default"];
  36994. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  36995. util$1.getProp = _getProp["default"];
  36996. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  36997. util$1.ensureObject = _ensureObject["default"];
  36998. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  36999. util$1.stripComments = _stripComments["default"];
  37000. var _maxNestingDepth = _interopRequireWildcard(/*@__PURE__*/ requireMaxNestingDepth());
  37001. util$1.resolveMaxNestingDepth = _maxNestingDepth["default"];
  37002. util$1.MAX_NESTING_DEPTH = _maxNestingDepth.MAX_NESTING_DEPTH;
  37003. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  37004. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37005. return util$1;
  37006. }
  37007. var node$1 = {exports: {}};
  37008. var hasRequiredNode$1;
  37009. function requireNode$1 () {
  37010. if (hasRequiredNode$1) return node$1.exports;
  37011. hasRequiredNode$1 = 1;
  37012. (function (module, exports) {
  37013. exports.__esModule = true;
  37014. exports["default"] = void 0;
  37015. var _util = /*@__PURE__*/ requireUtil$1();
  37016. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  37017. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  37018. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  37019. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  37020. var cloneNode = function cloneNode(obj, parent) {
  37021. if (typeof obj !== 'object' || obj === null) {
  37022. return obj;
  37023. }
  37024. var cloned = new obj.constructor();
  37025. for (var i in obj) {
  37026. if (!obj.hasOwnProperty(i)) {
  37027. continue;
  37028. }
  37029. var value = obj[i];
  37030. var type = typeof value;
  37031. if (i === 'parent' && type === 'object') {
  37032. if (parent) {
  37033. cloned[i] = parent;
  37034. }
  37035. } else if (value instanceof Array) {
  37036. cloned[i] = value.map(function (j) {
  37037. return cloneNode(j, cloned);
  37038. });
  37039. } else {
  37040. cloned[i] = cloneNode(value, cloned);
  37041. }
  37042. }
  37043. return cloned;
  37044. };
  37045. exports["default"] = /*#__PURE__*/function () {
  37046. function Node(opts) {
  37047. if (opts === void 0) {
  37048. opts = {};
  37049. }
  37050. Object.assign(this, opts);
  37051. this.spaces = this.spaces || {};
  37052. this.spaces.before = this.spaces.before || '';
  37053. this.spaces.after = this.spaces.after || '';
  37054. }
  37055. var _proto = Node.prototype;
  37056. _proto.remove = function remove() {
  37057. if (this.parent) {
  37058. this.parent.removeChild(this);
  37059. }
  37060. this.parent = undefined;
  37061. return this;
  37062. };
  37063. _proto.replaceWith = function replaceWith() {
  37064. if (this.parent) {
  37065. for (var index in arguments) {
  37066. this.parent.insertBefore(this, arguments[index]);
  37067. }
  37068. this.remove();
  37069. }
  37070. return this;
  37071. };
  37072. _proto.next = function next() {
  37073. return this.parent.at(this.parent.index(this) + 1);
  37074. };
  37075. _proto.prev = function prev() {
  37076. return this.parent.at(this.parent.index(this) - 1);
  37077. };
  37078. _proto.clone = function clone(overrides) {
  37079. if (overrides === void 0) {
  37080. overrides = {};
  37081. }
  37082. var cloned = cloneNode(this);
  37083. for (var name in overrides) {
  37084. cloned[name] = overrides[name];
  37085. }
  37086. return cloned;
  37087. }
  37088. /**
  37089. * Some non-standard syntax doesn't follow normal escaping rules for css.
  37090. * This allows non standard syntax to be appended to an existing property
  37091. * by specifying the escaped value. By specifying the escaped value,
  37092. * illegal characters are allowed to be directly inserted into css output.
  37093. * @param {string} name the property to set
  37094. * @param {any} value the unescaped value of the property
  37095. * @param {string} valueEscaped optional. the escaped value of the property.
  37096. */;
  37097. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  37098. if (!this.raws) {
  37099. this.raws = {};
  37100. }
  37101. var originalValue = this[name];
  37102. var originalEscaped = this.raws[name];
  37103. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  37104. if (originalEscaped || valueEscaped !== value) {
  37105. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  37106. } else {
  37107. delete this.raws[name]; // delete any escaped value that was created by the setter.
  37108. }
  37109. }
  37110. /**
  37111. * Some non-standard syntax doesn't follow normal escaping rules for css.
  37112. * This allows the escaped value to be specified directly, allowing illegal
  37113. * characters to be directly inserted into css output.
  37114. * @param {string} name the property to set
  37115. * @param {any} value the unescaped value of the property
  37116. * @param {string} valueEscaped the escaped value of the property.
  37117. */;
  37118. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  37119. if (!this.raws) {
  37120. this.raws = {};
  37121. }
  37122. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  37123. this.raws[name] = valueEscaped;
  37124. }
  37125. /**
  37126. * When you want a value to passed through to CSS directly. This method
  37127. * deletes the corresponding raw value causing the stringifier to fallback
  37128. * to the unescaped value.
  37129. * @param {string} name the property to set.
  37130. * @param {any} value The value that is both escaped and unescaped.
  37131. */;
  37132. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  37133. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  37134. if (this.raws) {
  37135. delete this.raws[name];
  37136. }
  37137. }
  37138. /**
  37139. *
  37140. * @param {number} line The number (starting with 1)
  37141. * @param {number} column The column number (starting with 1)
  37142. */;
  37143. _proto.isAtPosition = function isAtPosition(line, column) {
  37144. if (this.source && this.source.start && this.source.end) {
  37145. if (this.source.start.line > line) {
  37146. return false;
  37147. }
  37148. if (this.source.end.line < line) {
  37149. return false;
  37150. }
  37151. if (this.source.start.line === line && this.source.start.column > column) {
  37152. return false;
  37153. }
  37154. if (this.source.end.line === line && this.source.end.column < column) {
  37155. return false;
  37156. }
  37157. return true;
  37158. }
  37159. return undefined;
  37160. };
  37161. _proto.stringifyProperty = function stringifyProperty(name) {
  37162. return this.raws && this.raws[name] || this[name];
  37163. };
  37164. _proto.valueToString = function valueToString() {
  37165. return String(this.stringifyProperty("value"));
  37166. };
  37167. _proto.toString = function toString() {
  37168. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  37169. }
  37170. // Internal recursion entry point used by Container serialization. Leaf
  37171. // nodes don't recurse, so they ignore the depth/limit and stringify
  37172. // themselves. Containers override this to thread the nesting depth.
  37173. ;
  37174. _proto._stringify = function _stringify() {
  37175. return this.toString();
  37176. };
  37177. _createClass(Node, [{
  37178. key: "rawSpaceBefore",
  37179. get: function get() {
  37180. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  37181. if (rawSpace === undefined) {
  37182. rawSpace = this.spaces && this.spaces.before;
  37183. }
  37184. return rawSpace || "";
  37185. },
  37186. set: function set(raw) {
  37187. (0, _util.ensureObject)(this, "raws", "spaces");
  37188. this.raws.spaces.before = raw;
  37189. }
  37190. }, {
  37191. key: "rawSpaceAfter",
  37192. get: function get() {
  37193. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  37194. if (rawSpace === undefined) {
  37195. rawSpace = this.spaces.after;
  37196. }
  37197. return rawSpace || "";
  37198. },
  37199. set: function set(raw) {
  37200. (0, _util.ensureObject)(this, "raws", "spaces");
  37201. this.raws.spaces.after = raw;
  37202. }
  37203. }]);
  37204. return Node;
  37205. }();
  37206. module.exports = exports.default;
  37207. } (node$1, node$1.exports));
  37208. return node$1.exports;
  37209. }
  37210. var types = {};
  37211. var hasRequiredTypes;
  37212. function requireTypes () {
  37213. if (hasRequiredTypes) return types;
  37214. hasRequiredTypes = 1;
  37215. types.__esModule = true;
  37216. types.UNIVERSAL = types.TAG = types.STRING = types.SELECTOR = types.ROOT = types.PSEUDO = types.NESTING = types.ID = types.COMMENT = types.COMBINATOR = types.CLASS = types.ATTRIBUTE = void 0;
  37217. types.TAG = 'tag';
  37218. types.STRING = 'string';
  37219. types.SELECTOR = 'selector';
  37220. types.ROOT = 'root';
  37221. types.PSEUDO = 'pseudo';
  37222. types.NESTING = 'nesting';
  37223. types.ID = 'id';
  37224. types.COMMENT = 'comment';
  37225. types.COMBINATOR = 'combinator';
  37226. types.CLASS = 'class';
  37227. types.ATTRIBUTE = 'attribute';
  37228. types.UNIVERSAL = 'universal';
  37229. return types;
  37230. }
  37231. var hasRequiredContainer;
  37232. function requireContainer () {
  37233. if (hasRequiredContainer) return container.exports;
  37234. hasRequiredContainer = 1;
  37235. (function (module, exports) {
  37236. exports.__esModule = true;
  37237. exports["default"] = void 0;
  37238. var _util = /*@__PURE__*/ requireUtil$1();
  37239. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37240. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  37241. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  37242. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37243. function _createForOfIteratorHelperLoose(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (t) return (t = t.call(r)).next.bind(t); if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) { t && (r = t); var o = 0; return function () { return o >= r.length ? { done: true } : { done: false, value: r[o++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  37244. function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
  37245. function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
  37246. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  37247. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  37248. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  37249. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  37250. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  37251. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  37252. exports["default"] = /*#__PURE__*/function (_Node) {
  37253. _inheritsLoose(Container, _Node);
  37254. function Container(opts) {
  37255. var _this;
  37256. _this = _Node.call(this, opts) || this;
  37257. if (!_this.nodes) {
  37258. _this.nodes = [];
  37259. }
  37260. return _this;
  37261. }
  37262. var _proto = Container.prototype;
  37263. _proto.append = function append(selector) {
  37264. selector.parent = this;
  37265. this.nodes.push(selector);
  37266. return this;
  37267. };
  37268. _proto.prepend = function prepend(selector) {
  37269. selector.parent = this;
  37270. this.nodes.unshift(selector);
  37271. for (var id in this.indexes) {
  37272. this.indexes[id]++;
  37273. }
  37274. return this;
  37275. };
  37276. _proto.at = function at(index) {
  37277. return this.nodes[index];
  37278. };
  37279. _proto.index = function index(child) {
  37280. if (typeof child === 'number') {
  37281. return child;
  37282. }
  37283. return this.nodes.indexOf(child);
  37284. };
  37285. _proto.removeChild = function removeChild(child) {
  37286. child = this.index(child);
  37287. this.at(child).parent = undefined;
  37288. this.nodes.splice(child, 1);
  37289. var index;
  37290. for (var id in this.indexes) {
  37291. index = this.indexes[id];
  37292. if (index >= child) {
  37293. this.indexes[id] = index - 1;
  37294. }
  37295. }
  37296. return this;
  37297. };
  37298. _proto.removeAll = function removeAll() {
  37299. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  37300. var node = _step.value;
  37301. node.parent = undefined;
  37302. }
  37303. this.nodes = [];
  37304. return this;
  37305. };
  37306. _proto.empty = function empty() {
  37307. return this.removeAll();
  37308. };
  37309. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  37310. var _this$nodes;
  37311. newNode.parent = this;
  37312. var oldIndex = this.index(oldNode);
  37313. var resetNode = [];
  37314. for (var i = 2; i < arguments.length; i++) {
  37315. resetNode.push(arguments[i]);
  37316. }
  37317. (_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
  37318. newNode.parent = this;
  37319. var index;
  37320. for (var id in this.indexes) {
  37321. index = this.indexes[id];
  37322. if (oldIndex < index) {
  37323. this.indexes[id] = index + arguments.length - 1;
  37324. }
  37325. }
  37326. return this;
  37327. };
  37328. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  37329. var _this$nodes2;
  37330. newNode.parent = this;
  37331. var oldIndex = this.index(oldNode);
  37332. var resetNode = [];
  37333. for (var i = 2; i < arguments.length; i++) {
  37334. resetNode.push(arguments[i]);
  37335. }
  37336. (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
  37337. newNode.parent = this;
  37338. var index;
  37339. for (var id in this.indexes) {
  37340. index = this.indexes[id];
  37341. if (index >= oldIndex) {
  37342. this.indexes[id] = index + arguments.length - 1;
  37343. }
  37344. }
  37345. return this;
  37346. };
  37347. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  37348. var found = undefined;
  37349. this.each(function (node) {
  37350. if (node.atPosition) {
  37351. var foundChild = node.atPosition(line, col);
  37352. if (foundChild) {
  37353. found = foundChild;
  37354. return false;
  37355. }
  37356. } else if (node.isAtPosition(line, col)) {
  37357. found = node;
  37358. return false;
  37359. }
  37360. });
  37361. return found;
  37362. }
  37363. /**
  37364. * Return the most specific node at the line and column number given.
  37365. * The source location is based on the original parsed location, locations aren't
  37366. * updated as selector nodes are mutated.
  37367. *
  37368. * Note that this location is relative to the location of the first character
  37369. * of the selector, and not the location of the selector in the overall document
  37370. * when used in conjunction with postcss.
  37371. *
  37372. * If not found, returns undefined.
  37373. * @param {number} line The line number of the node to find. (1-based index)
  37374. * @param {number} col The column number of the node to find. (1-based index)
  37375. */;
  37376. _proto.atPosition = function atPosition(line, col) {
  37377. if (this.isAtPosition(line, col)) {
  37378. return this._findChildAtPosition(line, col) || this;
  37379. } else {
  37380. return undefined;
  37381. }
  37382. };
  37383. _proto._inferEndPosition = function _inferEndPosition() {
  37384. if (this.last && this.last.source && this.last.source.end) {
  37385. this.source = this.source || {};
  37386. this.source.end = this.source.end || {};
  37387. Object.assign(this.source.end, this.last.source.end);
  37388. }
  37389. };
  37390. _proto.each = function each(callback) {
  37391. if (!this.lastEach) {
  37392. this.lastEach = 0;
  37393. }
  37394. if (!this.indexes) {
  37395. this.indexes = {};
  37396. }
  37397. this.lastEach++;
  37398. var id = this.lastEach;
  37399. this.indexes[id] = 0;
  37400. if (!this.length) {
  37401. return undefined;
  37402. }
  37403. var index, result;
  37404. while (this.indexes[id] < this.length) {
  37405. index = this.indexes[id];
  37406. result = callback(this.at(index), index);
  37407. if (result === false) {
  37408. break;
  37409. }
  37410. this.indexes[id] += 1;
  37411. }
  37412. delete this.indexes[id];
  37413. if (result === false) {
  37414. return false;
  37415. }
  37416. };
  37417. _proto.walk = function walk(callback) {
  37418. return this.each(function (node, i) {
  37419. var result = callback(node, i);
  37420. if (result !== false && node.length) {
  37421. result = node.walk(callback);
  37422. }
  37423. if (result === false) {
  37424. return false;
  37425. }
  37426. });
  37427. };
  37428. _proto.walkAttributes = function walkAttributes(callback) {
  37429. var _this2 = this;
  37430. return this.walk(function (selector) {
  37431. if (selector.type === types.ATTRIBUTE) {
  37432. return callback.call(_this2, selector);
  37433. }
  37434. });
  37435. };
  37436. _proto.walkClasses = function walkClasses(callback) {
  37437. var _this3 = this;
  37438. return this.walk(function (selector) {
  37439. if (selector.type === types.CLASS) {
  37440. return callback.call(_this3, selector);
  37441. }
  37442. });
  37443. };
  37444. _proto.walkCombinators = function walkCombinators(callback) {
  37445. var _this4 = this;
  37446. return this.walk(function (selector) {
  37447. if (selector.type === types.COMBINATOR) {
  37448. return callback.call(_this4, selector);
  37449. }
  37450. });
  37451. };
  37452. _proto.walkComments = function walkComments(callback) {
  37453. var _this5 = this;
  37454. return this.walk(function (selector) {
  37455. if (selector.type === types.COMMENT) {
  37456. return callback.call(_this5, selector);
  37457. }
  37458. });
  37459. };
  37460. _proto.walkIds = function walkIds(callback) {
  37461. var _this6 = this;
  37462. return this.walk(function (selector) {
  37463. if (selector.type === types.ID) {
  37464. return callback.call(_this6, selector);
  37465. }
  37466. });
  37467. };
  37468. _proto.walkNesting = function walkNesting(callback) {
  37469. var _this7 = this;
  37470. return this.walk(function (selector) {
  37471. if (selector.type === types.NESTING) {
  37472. return callback.call(_this7, selector);
  37473. }
  37474. });
  37475. };
  37476. _proto.walkPseudos = function walkPseudos(callback) {
  37477. var _this8 = this;
  37478. return this.walk(function (selector) {
  37479. if (selector.type === types.PSEUDO) {
  37480. return callback.call(_this8, selector);
  37481. }
  37482. });
  37483. };
  37484. _proto.walkTags = function walkTags(callback) {
  37485. var _this9 = this;
  37486. return this.walk(function (selector) {
  37487. if (selector.type === types.TAG) {
  37488. return callback.call(_this9, selector);
  37489. }
  37490. });
  37491. };
  37492. _proto.walkUniversals = function walkUniversals(callback) {
  37493. var _this0 = this;
  37494. return this.walk(function (selector) {
  37495. if (selector.type === types.UNIVERSAL) {
  37496. return callback.call(_this0, selector);
  37497. }
  37498. });
  37499. };
  37500. _proto.split = function split(callback) {
  37501. var _this1 = this;
  37502. var current = [];
  37503. return this.reduce(function (memo, node, index) {
  37504. var split = callback.call(_this1, node);
  37505. current.push(node);
  37506. if (split) {
  37507. memo.push(current);
  37508. current = [];
  37509. } else if (index === _this1.length - 1) {
  37510. memo.push(current);
  37511. }
  37512. return memo;
  37513. }, []);
  37514. };
  37515. _proto.map = function map(callback) {
  37516. return this.nodes.map(callback);
  37517. };
  37518. _proto.reduce = function reduce(callback, memo) {
  37519. return this.nodes.reduce(callback, memo);
  37520. };
  37521. _proto.every = function every(callback) {
  37522. return this.nodes.every(callback);
  37523. };
  37524. _proto.some = function some(callback) {
  37525. return this.nodes.some(callback);
  37526. };
  37527. _proto.filter = function filter(callback) {
  37528. return this.nodes.filter(callback);
  37529. };
  37530. _proto.sort = function sort(callback) {
  37531. return this.nodes.sort(callback);
  37532. };
  37533. _proto.toString = function toString(options) {
  37534. if (options === void 0) {
  37535. options = {};
  37536. }
  37537. return this._stringify(options, 0, (0, _util.resolveMaxNestingDepth)(options.maxNestingDepth));
  37538. };
  37539. _proto._stringify = function _stringify(options, depth, max) {
  37540. return this.map(function (child) {
  37541. return child._stringify(options, depth, max);
  37542. }).join('');
  37543. };
  37544. _createClass(Container, [{
  37545. key: "first",
  37546. get: function get() {
  37547. return this.at(0);
  37548. }
  37549. }, {
  37550. key: "last",
  37551. get: function get() {
  37552. return this.at(this.length - 1);
  37553. }
  37554. }, {
  37555. key: "length",
  37556. get: function get() {
  37557. return this.nodes.length;
  37558. }
  37559. }]);
  37560. return Container;
  37561. }(_node["default"]);
  37562. module.exports = exports.default;
  37563. } (container, container.exports));
  37564. return container.exports;
  37565. }
  37566. var hasRequiredRoot;
  37567. function requireRoot () {
  37568. if (hasRequiredRoot) return root.exports;
  37569. hasRequiredRoot = 1;
  37570. (function (module, exports) {
  37571. exports.__esModule = true;
  37572. exports["default"] = void 0;
  37573. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  37574. var _types = /*@__PURE__*/ requireTypes();
  37575. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37576. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  37577. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  37578. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  37579. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  37580. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  37581. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  37582. exports["default"] = /*#__PURE__*/function (_Container) {
  37583. _inheritsLoose(Root, _Container);
  37584. function Root(opts) {
  37585. var _this;
  37586. _this = _Container.call(this, opts) || this;
  37587. _this.type = _types.ROOT;
  37588. return _this;
  37589. }
  37590. var _proto = Root.prototype;
  37591. _proto._stringify = function _stringify(options, depth, max) {
  37592. var str = this.reduce(function (memo, selector) {
  37593. memo.push(selector._stringify(options, depth, max));
  37594. return memo;
  37595. }, []).join(',');
  37596. return this.trailingComma ? str + ',' : str;
  37597. };
  37598. _proto.error = function error(message, options) {
  37599. if (this._error) {
  37600. return this._error(message, options);
  37601. } else {
  37602. return new Error(message);
  37603. }
  37604. };
  37605. _createClass(Root, [{
  37606. key: "errorGenerator",
  37607. set: function set(handler) {
  37608. this._error = handler;
  37609. }
  37610. }]);
  37611. return Root;
  37612. }(_container["default"]);
  37613. module.exports = exports.default;
  37614. } (root, root.exports));
  37615. return root.exports;
  37616. }
  37617. var selector = {exports: {}};
  37618. var hasRequiredSelector;
  37619. function requireSelector () {
  37620. if (hasRequiredSelector) return selector.exports;
  37621. hasRequiredSelector = 1;
  37622. (function (module, exports) {
  37623. exports.__esModule = true;
  37624. exports["default"] = void 0;
  37625. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  37626. var _types = /*@__PURE__*/ requireTypes();
  37627. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37628. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  37629. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  37630. exports["default"] = /*#__PURE__*/function (_Container) {
  37631. _inheritsLoose(Selector, _Container);
  37632. function Selector(opts) {
  37633. var _this;
  37634. _this = _Container.call(this, opts) || this;
  37635. _this.type = _types.SELECTOR;
  37636. return _this;
  37637. }
  37638. return Selector;
  37639. }(_container["default"]);
  37640. module.exports = exports.default;
  37641. } (selector, selector.exports));
  37642. return selector.exports;
  37643. }
  37644. var className = {exports: {}};
  37645. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  37646. var cssesc_1;
  37647. var hasRequiredCssesc;
  37648. function requireCssesc () {
  37649. if (hasRequiredCssesc) return cssesc_1;
  37650. hasRequiredCssesc = 1;
  37651. var object = {};
  37652. var hasOwnProperty = object.hasOwnProperty;
  37653. var merge = function merge(options, defaults) {
  37654. if (!options) {
  37655. return defaults;
  37656. }
  37657. var result = {};
  37658. for (var key in defaults) {
  37659. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  37660. // only recognized option names are used.
  37661. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  37662. }
  37663. return result;
  37664. };
  37665. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  37666. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  37667. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  37668. // https://mathiasbynens.be/notes/css-escapes#css
  37669. var cssesc = function cssesc(string, options) {
  37670. options = merge(options, cssesc.options);
  37671. if (options.quotes != 'single' && options.quotes != 'double') {
  37672. options.quotes = 'single';
  37673. }
  37674. var quote = options.quotes == 'double' ? '"' : '\'';
  37675. var isIdentifier = options.isIdentifier;
  37676. var firstChar = string.charAt(0);
  37677. var output = '';
  37678. var counter = 0;
  37679. var length = string.length;
  37680. while (counter < length) {
  37681. var character = string.charAt(counter++);
  37682. var codePoint = character.charCodeAt();
  37683. var value = void 0;
  37684. // If it’s not a printable ASCII character…
  37685. if (codePoint < 0x20 || codePoint > 0x7E) {
  37686. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  37687. // It’s a high surrogate, and there is a next character.
  37688. var extra = string.charCodeAt(counter++);
  37689. if ((extra & 0xFC00) == 0xDC00) {
  37690. // next character is low surrogate
  37691. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  37692. } else {
  37693. // It’s an unmatched surrogate; only append this code unit, in case
  37694. // the next code unit is the high surrogate of a surrogate pair.
  37695. counter--;
  37696. }
  37697. }
  37698. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  37699. } else {
  37700. if (options.escapeEverything) {
  37701. if (regexAnySingleEscape.test(character)) {
  37702. value = '\\' + character;
  37703. } else {
  37704. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  37705. }
  37706. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  37707. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  37708. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  37709. value = '\\' + character;
  37710. } else {
  37711. value = character;
  37712. }
  37713. }
  37714. output += value;
  37715. }
  37716. if (isIdentifier) {
  37717. if (/^-[-\d]/.test(output)) {
  37718. output = '\\-' + output.slice(1);
  37719. } else if (/\d/.test(firstChar)) {
  37720. output = '\\3' + firstChar + ' ' + output.slice(1);
  37721. }
  37722. }
  37723. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  37724. // since they’re redundant. Note that this is only possible if the escape
  37725. // sequence isn’t preceded by an odd number of backslashes.
  37726. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  37727. if ($1 && $1.length % 2) {
  37728. // It’s not safe to remove the space, so don’t.
  37729. return $0;
  37730. }
  37731. // Strip the space.
  37732. return ($1 || '') + $2;
  37733. });
  37734. if (!isIdentifier && options.wrap) {
  37735. return quote + output + quote;
  37736. }
  37737. return output;
  37738. };
  37739. // Expose default options (so they can be overridden globally).
  37740. cssesc.options = {
  37741. 'escapeEverything': false,
  37742. 'isIdentifier': false,
  37743. 'quotes': 'single',
  37744. 'wrap': false
  37745. };
  37746. cssesc.version = '3.0.0';
  37747. cssesc_1 = cssesc;
  37748. return cssesc_1;
  37749. }
  37750. var hasRequiredClassName;
  37751. function requireClassName () {
  37752. if (hasRequiredClassName) return className.exports;
  37753. hasRequiredClassName = 1;
  37754. (function (module, exports) {
  37755. exports.__esModule = true;
  37756. exports["default"] = void 0;
  37757. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  37758. var _util = /*@__PURE__*/ requireUtil$1();
  37759. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37760. var _types = /*@__PURE__*/ requireTypes();
  37761. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37762. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  37763. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  37764. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  37765. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  37766. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  37767. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  37768. exports["default"] = /*#__PURE__*/function (_Node) {
  37769. _inheritsLoose(ClassName, _Node);
  37770. function ClassName(opts) {
  37771. var _this;
  37772. _this = _Node.call(this, opts) || this;
  37773. _this.type = _types.CLASS;
  37774. _this._constructed = true;
  37775. return _this;
  37776. }
  37777. var _proto = ClassName.prototype;
  37778. _proto.valueToString = function valueToString() {
  37779. return '.' + _Node.prototype.valueToString.call(this);
  37780. };
  37781. _createClass(ClassName, [{
  37782. key: "value",
  37783. get: function get() {
  37784. return this._value;
  37785. },
  37786. set: function set(v) {
  37787. if (this._constructed) {
  37788. var escaped = (0, _cssesc["default"])(v, {
  37789. isIdentifier: true
  37790. });
  37791. if (escaped !== v) {
  37792. (0, _util.ensureObject)(this, "raws");
  37793. this.raws.value = escaped;
  37794. } else if (this.raws) {
  37795. delete this.raws.value;
  37796. }
  37797. }
  37798. this._value = v;
  37799. }
  37800. }]);
  37801. return ClassName;
  37802. }(_node["default"]);
  37803. module.exports = exports.default;
  37804. } (className, className.exports));
  37805. return className.exports;
  37806. }
  37807. var comment = {exports: {}};
  37808. var hasRequiredComment;
  37809. function requireComment () {
  37810. if (hasRequiredComment) return comment.exports;
  37811. hasRequiredComment = 1;
  37812. (function (module, exports) {
  37813. exports.__esModule = true;
  37814. exports["default"] = void 0;
  37815. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37816. var _types = /*@__PURE__*/ requireTypes();
  37817. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37818. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  37819. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  37820. exports["default"] = /*#__PURE__*/function (_Node) {
  37821. _inheritsLoose(Comment, _Node);
  37822. function Comment(opts) {
  37823. var _this;
  37824. _this = _Node.call(this, opts) || this;
  37825. _this.type = _types.COMMENT;
  37826. return _this;
  37827. }
  37828. return Comment;
  37829. }(_node["default"]);
  37830. module.exports = exports.default;
  37831. } (comment, comment.exports));
  37832. return comment.exports;
  37833. }
  37834. var id = {exports: {}};
  37835. var hasRequiredId;
  37836. function requireId () {
  37837. if (hasRequiredId) return id.exports;
  37838. hasRequiredId = 1;
  37839. (function (module, exports) {
  37840. exports.__esModule = true;
  37841. exports["default"] = void 0;
  37842. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37843. var _types = /*@__PURE__*/ requireTypes();
  37844. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37845. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  37846. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  37847. exports["default"] = /*#__PURE__*/function (_Node) {
  37848. _inheritsLoose(ID, _Node);
  37849. function ID(opts) {
  37850. var _this;
  37851. _this = _Node.call(this, opts) || this;
  37852. _this.type = _types.ID;
  37853. return _this;
  37854. }
  37855. var _proto = ID.prototype;
  37856. _proto.valueToString = function valueToString() {
  37857. return '#' + _Node.prototype.valueToString.call(this);
  37858. };
  37859. return ID;
  37860. }(_node["default"]);
  37861. module.exports = exports.default;
  37862. } (id, id.exports));
  37863. return id.exports;
  37864. }
  37865. var tag = {exports: {}};
  37866. var namespace = {exports: {}};
  37867. var hasRequiredNamespace;
  37868. function requireNamespace () {
  37869. if (hasRequiredNamespace) return namespace.exports;
  37870. hasRequiredNamespace = 1;
  37871. (function (module, exports) {
  37872. exports.__esModule = true;
  37873. exports["default"] = void 0;
  37874. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  37875. var _util = /*@__PURE__*/ requireUtil$1();
  37876. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37877. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37878. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  37879. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  37880. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  37881. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  37882. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  37883. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  37884. exports["default"] = /*#__PURE__*/function (_Node) {
  37885. _inheritsLoose(Namespace, _Node);
  37886. function Namespace() {
  37887. return _Node.apply(this, arguments) || this;
  37888. }
  37889. var _proto = Namespace.prototype;
  37890. _proto.qualifiedName = function qualifiedName(value) {
  37891. if (this.namespace) {
  37892. return this.namespaceString + "|" + value;
  37893. } else {
  37894. return value;
  37895. }
  37896. };
  37897. _proto.valueToString = function valueToString() {
  37898. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  37899. };
  37900. _createClass(Namespace, [{
  37901. key: "namespace",
  37902. get: function get() {
  37903. return this._namespace;
  37904. },
  37905. set: function set(namespace) {
  37906. if (namespace === true || namespace === "*" || namespace === "&") {
  37907. this._namespace = namespace;
  37908. if (this.raws) {
  37909. delete this.raws.namespace;
  37910. }
  37911. return;
  37912. }
  37913. var escaped = (0, _cssesc["default"])(namespace, {
  37914. isIdentifier: true
  37915. });
  37916. this._namespace = namespace;
  37917. if (escaped !== namespace) {
  37918. (0, _util.ensureObject)(this, "raws");
  37919. this.raws.namespace = escaped;
  37920. } else if (this.raws) {
  37921. delete this.raws.namespace;
  37922. }
  37923. }
  37924. }, {
  37925. key: "ns",
  37926. get: function get() {
  37927. return this._namespace;
  37928. },
  37929. set: function set(namespace) {
  37930. this.namespace = namespace;
  37931. }
  37932. }, {
  37933. key: "namespaceString",
  37934. get: function get() {
  37935. if (this.namespace) {
  37936. var ns = this.stringifyProperty("namespace");
  37937. if (ns === true) {
  37938. return '';
  37939. } else {
  37940. return ns;
  37941. }
  37942. } else {
  37943. return '';
  37944. }
  37945. }
  37946. }]);
  37947. return Namespace;
  37948. }(_node["default"]);
  37949. module.exports = exports.default;
  37950. } (namespace, namespace.exports));
  37951. return namespace.exports;
  37952. }
  37953. var hasRequiredTag;
  37954. function requireTag () {
  37955. if (hasRequiredTag) return tag.exports;
  37956. hasRequiredTag = 1;
  37957. (function (module, exports) {
  37958. exports.__esModule = true;
  37959. exports["default"] = void 0;
  37960. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  37961. var _types = /*@__PURE__*/ requireTypes();
  37962. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37963. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  37964. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  37965. exports["default"] = /*#__PURE__*/function (_Namespace) {
  37966. _inheritsLoose(Tag, _Namespace);
  37967. function Tag(opts) {
  37968. var _this;
  37969. _this = _Namespace.call(this, opts) || this;
  37970. _this.type = _types.TAG;
  37971. return _this;
  37972. }
  37973. return Tag;
  37974. }(_namespace["default"]);
  37975. module.exports = exports.default;
  37976. } (tag, tag.exports));
  37977. return tag.exports;
  37978. }
  37979. var string = {exports: {}};
  37980. var hasRequiredString;
  37981. function requireString () {
  37982. if (hasRequiredString) return string.exports;
  37983. hasRequiredString = 1;
  37984. (function (module, exports) {
  37985. exports.__esModule = true;
  37986. exports["default"] = void 0;
  37987. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37988. var _types = /*@__PURE__*/ requireTypes();
  37989. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  37990. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  37991. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  37992. exports["default"] = /*#__PURE__*/function (_Node) {
  37993. _inheritsLoose(String, _Node);
  37994. function String(opts) {
  37995. var _this;
  37996. _this = _Node.call(this, opts) || this;
  37997. _this.type = _types.STRING;
  37998. return _this;
  37999. }
  38000. return String;
  38001. }(_node["default"]);
  38002. module.exports = exports.default;
  38003. } (string, string.exports));
  38004. return string.exports;
  38005. }
  38006. var pseudo = {exports: {}};
  38007. var hasRequiredPseudo;
  38008. function requirePseudo () {
  38009. if (hasRequiredPseudo) return pseudo.exports;
  38010. hasRequiredPseudo = 1;
  38011. (function (module, exports) {
  38012. exports.__esModule = true;
  38013. exports["default"] = void 0;
  38014. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  38015. var _types = /*@__PURE__*/ requireTypes();
  38016. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  38017. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  38018. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  38019. exports["default"] = /*#__PURE__*/function (_Container) {
  38020. _inheritsLoose(Pseudo, _Container);
  38021. function Pseudo(opts) {
  38022. var _this;
  38023. _this = _Container.call(this, opts) || this;
  38024. _this.type = _types.PSEUDO;
  38025. return _this;
  38026. }
  38027. var _proto = Pseudo.prototype;
  38028. _proto._stringify = function _stringify(options, depth, max) {
  38029. if (depth >= max) {
  38030. throw new Error("Cannot serialize selector: nesting depth exceeds the maximum of " + max + ".");
  38031. }
  38032. var params = this.length ? '(' + this.map(function (child) {
  38033. return child._stringify(options, depth + 1, max);
  38034. }).join(',') + ')' : '';
  38035. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  38036. };
  38037. return Pseudo;
  38038. }(_container["default"]);
  38039. module.exports = exports.default;
  38040. } (pseudo, pseudo.exports));
  38041. return pseudo.exports;
  38042. }
  38043. var attribute = {};
  38044. var node;
  38045. var hasRequiredNode;
  38046. function requireNode () {
  38047. if (hasRequiredNode) return node;
  38048. hasRequiredNode = 1;
  38049. /**
  38050. * For Node.js, simply re-export the core `util.deprecate` function.
  38051. */
  38052. node = require$$0.deprecate;
  38053. return node;
  38054. }
  38055. var hasRequiredAttribute;
  38056. function requireAttribute () {
  38057. if (hasRequiredAttribute) return attribute;
  38058. hasRequiredAttribute = 1;
  38059. (function (exports) {
  38060. exports.__esModule = true;
  38061. exports["default"] = void 0;
  38062. exports.unescapeValue = unescapeValue;
  38063. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  38064. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  38065. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  38066. var _types = /*@__PURE__*/ requireTypes();
  38067. var _CSSESC_QUOTE_OPTIONS;
  38068. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  38069. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  38070. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  38071. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  38072. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  38073. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  38074. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  38075. var deprecate = /*@__PURE__*/ requireNode();
  38076. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  38077. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  38078. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  38079. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  38080. function unescapeValue(value) {
  38081. var deprecatedUsage = false;
  38082. var quoteMark = null;
  38083. var unescaped = value;
  38084. var m = unescaped.match(WRAPPED_IN_QUOTES);
  38085. if (m) {
  38086. quoteMark = m[1];
  38087. unescaped = m[2];
  38088. }
  38089. unescaped = (0, _unesc["default"])(unescaped);
  38090. if (unescaped !== value) {
  38091. deprecatedUsage = true;
  38092. }
  38093. return {
  38094. deprecatedUsage: deprecatedUsage,
  38095. unescaped: unescaped,
  38096. quoteMark: quoteMark
  38097. };
  38098. }
  38099. function handleDeprecatedContructorOpts(opts) {
  38100. if (opts.quoteMark !== undefined) {
  38101. return opts;
  38102. }
  38103. if (opts.value === undefined) {
  38104. return opts;
  38105. }
  38106. warnOfDeprecatedConstructor();
  38107. var _unescapeValue = unescapeValue(opts.value),
  38108. quoteMark = _unescapeValue.quoteMark,
  38109. unescaped = _unescapeValue.unescaped;
  38110. if (!opts.raws) {
  38111. opts.raws = {};
  38112. }
  38113. if (opts.raws.value === undefined) {
  38114. opts.raws.value = opts.value;
  38115. }
  38116. opts.value = unescaped;
  38117. opts.quoteMark = quoteMark;
  38118. return opts;
  38119. }
  38120. var Attribute = exports["default"] = /*#__PURE__*/function (_Namespace) {
  38121. _inheritsLoose(Attribute, _Namespace);
  38122. function Attribute(opts) {
  38123. var _this;
  38124. if (opts === void 0) {
  38125. opts = {};
  38126. }
  38127. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  38128. _this.type = _types.ATTRIBUTE;
  38129. _this.raws = _this.raws || {};
  38130. Object.defineProperty(_this.raws, 'unquoted', {
  38131. get: deprecate(function () {
  38132. return _this.value;
  38133. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  38134. set: deprecate(function () {
  38135. return _this.value;
  38136. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  38137. });
  38138. _this._constructed = true;
  38139. return _this;
  38140. }
  38141. /**
  38142. * Returns the Attribute's value quoted such that it would be legal to use
  38143. * in the value of a css file. The original value's quotation setting
  38144. * used for stringification is left unchanged. See `setValue(value, options)`
  38145. * if you want to control the quote settings of a new value for the attribute.
  38146. *
  38147. * You can also change the quotation used for the current value by setting quoteMark.
  38148. *
  38149. * Options:
  38150. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  38151. * option is not set, the original value for quoteMark will be used. If
  38152. * indeterminate, a double quote is used. The legal values are:
  38153. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  38154. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  38155. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  38156. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  38157. * over the quoteMark option value.
  38158. * * smart {boolean} - if true, will select a quote mark based on the value
  38159. * and the other options specified here. See the `smartQuoteMark()`
  38160. * method.
  38161. **/
  38162. var _proto = Attribute.prototype;
  38163. _proto.getQuotedValue = function getQuotedValue(options) {
  38164. if (options === void 0) {
  38165. options = {};
  38166. }
  38167. var quoteMark = this._determineQuoteMark(options);
  38168. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  38169. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  38170. return escaped;
  38171. };
  38172. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  38173. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  38174. }
  38175. /**
  38176. * Set the unescaped value with the specified quotation options. The value
  38177. * provided must not include any wrapping quote marks -- those quotes will
  38178. * be interpreted as part of the value and escaped accordingly.
  38179. */;
  38180. _proto.setValue = function setValue(value, options) {
  38181. if (options === void 0) {
  38182. options = {};
  38183. }
  38184. this._value = value;
  38185. this._quoteMark = this._determineQuoteMark(options);
  38186. this._syncRawValue();
  38187. }
  38188. /**
  38189. * Intelligently select a quoteMark value based on the value's contents. If
  38190. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  38191. * mark will be picked that minimizes the number of escapes.
  38192. *
  38193. * If there's no clear winner, the quote mark from these options is used,
  38194. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  38195. * true). If the quoteMark is unspecified, a double quote is used.
  38196. *
  38197. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  38198. * from the quoteValue method.
  38199. */;
  38200. _proto.smartQuoteMark = function smartQuoteMark(options) {
  38201. var v = this.value;
  38202. var numSingleQuotes = v.replace(/[^']/g, '').length;
  38203. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  38204. if (numSingleQuotes + numDoubleQuotes === 0) {
  38205. var escaped = (0, _cssesc["default"])(v, {
  38206. isIdentifier: true
  38207. });
  38208. if (escaped === v) {
  38209. return Attribute.NO_QUOTE;
  38210. } else {
  38211. var pref = this.preferredQuoteMark(options);
  38212. if (pref === Attribute.NO_QUOTE) {
  38213. // pick a quote mark that isn't none and see if it's smaller
  38214. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  38215. var opts = CSSESC_QUOTE_OPTIONS[quote];
  38216. var quoteValue = (0, _cssesc["default"])(v, opts);
  38217. if (quoteValue.length < escaped.length) {
  38218. return quote;
  38219. }
  38220. }
  38221. return pref;
  38222. }
  38223. } else if (numDoubleQuotes === numSingleQuotes) {
  38224. return this.preferredQuoteMark(options);
  38225. } else if (numDoubleQuotes < numSingleQuotes) {
  38226. return Attribute.DOUBLE_QUOTE;
  38227. } else {
  38228. return Attribute.SINGLE_QUOTE;
  38229. }
  38230. }
  38231. /**
  38232. * Selects the preferred quote mark based on the options and the current quote mark value.
  38233. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  38234. * instead.
  38235. */;
  38236. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  38237. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  38238. if (quoteMark === undefined) {
  38239. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  38240. }
  38241. if (quoteMark === undefined) {
  38242. quoteMark = Attribute.DOUBLE_QUOTE;
  38243. }
  38244. return quoteMark;
  38245. };
  38246. _proto._syncRawValue = function _syncRawValue() {
  38247. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  38248. if (rawValue === this._value) {
  38249. if (this.raws) {
  38250. delete this.raws.value;
  38251. }
  38252. } else {
  38253. this.raws.value = rawValue;
  38254. }
  38255. };
  38256. _proto._handleEscapes = function _handleEscapes(prop, value) {
  38257. if (this._constructed) {
  38258. var escaped = (0, _cssesc["default"])(value, {
  38259. isIdentifier: true
  38260. });
  38261. if (escaped !== value) {
  38262. this.raws[prop] = escaped;
  38263. } else {
  38264. delete this.raws[prop];
  38265. }
  38266. }
  38267. };
  38268. _proto._spacesFor = function _spacesFor(name) {
  38269. var attrSpaces = {
  38270. before: '',
  38271. after: ''
  38272. };
  38273. var spaces = this.spaces[name] || {};
  38274. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  38275. return Object.assign(attrSpaces, spaces, rawSpaces);
  38276. };
  38277. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  38278. if (spaceName === void 0) {
  38279. spaceName = name;
  38280. }
  38281. if (concat === void 0) {
  38282. concat = defaultAttrConcat;
  38283. }
  38284. var attrSpaces = this._spacesFor(spaceName);
  38285. return concat(this.stringifyProperty(name), attrSpaces);
  38286. }
  38287. /**
  38288. * returns the offset of the attribute part specified relative to the
  38289. * start of the node of the output string.
  38290. *
  38291. * * "ns" - alias for "namespace"
  38292. * * "namespace" - the namespace if it exists.
  38293. * * "attribute" - the attribute name
  38294. * * "attributeNS" - the start of the attribute or its namespace
  38295. * * "operator" - the match operator of the attribute
  38296. * * "value" - The value (string or identifier)
  38297. * * "insensitive" - the case insensitivity flag;
  38298. * @param part One of the possible values inside an attribute.
  38299. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  38300. */;
  38301. _proto.offsetOf = function offsetOf(name) {
  38302. var count = 1;
  38303. var attributeSpaces = this._spacesFor("attribute");
  38304. count += attributeSpaces.before.length;
  38305. if (name === "namespace" || name === "ns") {
  38306. return this.namespace ? count : -1;
  38307. }
  38308. if (name === "attributeNS") {
  38309. return count;
  38310. }
  38311. count += this.namespaceString.length;
  38312. if (this.namespace) {
  38313. count += 1;
  38314. }
  38315. if (name === "attribute") {
  38316. return count;
  38317. }
  38318. count += this.stringifyProperty("attribute").length;
  38319. count += attributeSpaces.after.length;
  38320. var operatorSpaces = this._spacesFor("operator");
  38321. count += operatorSpaces.before.length;
  38322. var operator = this.stringifyProperty("operator");
  38323. if (name === "operator") {
  38324. return operator ? count : -1;
  38325. }
  38326. count += operator.length;
  38327. count += operatorSpaces.after.length;
  38328. var valueSpaces = this._spacesFor("value");
  38329. count += valueSpaces.before.length;
  38330. var value = this.stringifyProperty("value");
  38331. if (name === "value") {
  38332. return value ? count : -1;
  38333. }
  38334. count += value.length;
  38335. count += valueSpaces.after.length;
  38336. var insensitiveSpaces = this._spacesFor("insensitive");
  38337. count += insensitiveSpaces.before.length;
  38338. if (name === "insensitive") {
  38339. return this.insensitive ? count : -1;
  38340. }
  38341. return -1;
  38342. };
  38343. _proto.toString = function toString() {
  38344. var _this2 = this;
  38345. var selector = [this.rawSpaceBefore, '['];
  38346. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  38347. if (this.operator && (this.value || this.value === '')) {
  38348. selector.push(this._stringFor('operator'));
  38349. selector.push(this._stringFor('value'));
  38350. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  38351. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  38352. attrSpaces.before = " ";
  38353. }
  38354. return defaultAttrConcat(attrValue, attrSpaces);
  38355. }));
  38356. }
  38357. selector.push(']');
  38358. selector.push(this.rawSpaceAfter);
  38359. return selector.join('');
  38360. };
  38361. _createClass(Attribute, [{
  38362. key: "quoted",
  38363. get: function get() {
  38364. var qm = this.quoteMark;
  38365. return qm === "'" || qm === '"';
  38366. },
  38367. set: function set(value) {
  38368. warnOfDeprecatedQuotedAssignment();
  38369. }
  38370. /**
  38371. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  38372. * returns `null` if the value is not quoted.
  38373. * returns `undefined` if the quotation state is unknown (this can happen when
  38374. * the attribute is constructed without specifying a quote mark.)
  38375. */
  38376. }, {
  38377. key: "quoteMark",
  38378. get: function get() {
  38379. return this._quoteMark;
  38380. }
  38381. /**
  38382. * Set the quote mark to be used by this attribute's value.
  38383. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  38384. * value is updated accordingly.
  38385. *
  38386. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  38387. */,
  38388. set: function set(quoteMark) {
  38389. if (!this._constructed) {
  38390. this._quoteMark = quoteMark;
  38391. return;
  38392. }
  38393. if (this._quoteMark !== quoteMark) {
  38394. this._quoteMark = quoteMark;
  38395. this._syncRawValue();
  38396. }
  38397. }
  38398. }, {
  38399. key: "qualifiedAttribute",
  38400. get: function get() {
  38401. return this.qualifiedName(this.raws.attribute || this.attribute);
  38402. }
  38403. }, {
  38404. key: "insensitiveFlag",
  38405. get: function get() {
  38406. return this.insensitive ? 'i' : '';
  38407. }
  38408. }, {
  38409. key: "value",
  38410. get: function get() {
  38411. return this._value;
  38412. },
  38413. set:
  38414. /**
  38415. * Before 3.0, the value had to be set to an escaped value including any wrapped
  38416. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  38417. * is unescaped during parsing and any quote marks are removed.
  38418. *
  38419. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  38420. * a deprecation warning is raised when the new value contains any characters that would
  38421. * require escaping (including if it contains wrapped quotes).
  38422. *
  38423. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  38424. * how the new value is quoted.
  38425. */
  38426. function set(v) {
  38427. if (this._constructed) {
  38428. var _unescapeValue2 = unescapeValue(v),
  38429. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  38430. unescaped = _unescapeValue2.unescaped,
  38431. quoteMark = _unescapeValue2.quoteMark;
  38432. if (deprecatedUsage) {
  38433. warnOfDeprecatedValueAssignment();
  38434. }
  38435. if (unescaped === this._value && quoteMark === this._quoteMark) {
  38436. return;
  38437. }
  38438. this._value = unescaped;
  38439. this._quoteMark = quoteMark;
  38440. this._syncRawValue();
  38441. } else {
  38442. this._value = v;
  38443. }
  38444. }
  38445. }, {
  38446. key: "insensitive",
  38447. get: function get() {
  38448. return this._insensitive;
  38449. }
  38450. /**
  38451. * Set the case insensitive flag.
  38452. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  38453. * of the attribute is updated accordingly.
  38454. *
  38455. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  38456. */,
  38457. set: function set(insensitive) {
  38458. if (!insensitive) {
  38459. this._insensitive = false;
  38460. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  38461. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  38462. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  38463. this.raws.insensitiveFlag = undefined;
  38464. }
  38465. }
  38466. this._insensitive = insensitive;
  38467. }
  38468. }, {
  38469. key: "attribute",
  38470. get: function get() {
  38471. return this._attribute;
  38472. },
  38473. set: function set(name) {
  38474. this._handleEscapes("attribute", name);
  38475. this._attribute = name;
  38476. }
  38477. }]);
  38478. return Attribute;
  38479. }(_namespace["default"]);
  38480. Attribute.NO_QUOTE = null;
  38481. Attribute.SINGLE_QUOTE = "'";
  38482. Attribute.DOUBLE_QUOTE = '"';
  38483. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  38484. "'": {
  38485. quotes: 'single',
  38486. wrap: true
  38487. },
  38488. '"': {
  38489. quotes: 'double',
  38490. wrap: true
  38491. }
  38492. }, _CSSESC_QUOTE_OPTIONS[null] = {
  38493. isIdentifier: true
  38494. }, _CSSESC_QUOTE_OPTIONS);
  38495. function defaultAttrConcat(attrValue, attrSpaces) {
  38496. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  38497. }
  38498. } (attribute));
  38499. return attribute;
  38500. }
  38501. var universal = {exports: {}};
  38502. var hasRequiredUniversal;
  38503. function requireUniversal () {
  38504. if (hasRequiredUniversal) return universal.exports;
  38505. hasRequiredUniversal = 1;
  38506. (function (module, exports) {
  38507. exports.__esModule = true;
  38508. exports["default"] = void 0;
  38509. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  38510. var _types = /*@__PURE__*/ requireTypes();
  38511. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  38512. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  38513. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  38514. exports["default"] = /*#__PURE__*/function (_Namespace) {
  38515. _inheritsLoose(Universal, _Namespace);
  38516. function Universal(opts) {
  38517. var _this;
  38518. _this = _Namespace.call(this, opts) || this;
  38519. _this.type = _types.UNIVERSAL;
  38520. _this.value = '*';
  38521. return _this;
  38522. }
  38523. return Universal;
  38524. }(_namespace["default"]);
  38525. module.exports = exports.default;
  38526. } (universal, universal.exports));
  38527. return universal.exports;
  38528. }
  38529. var combinator = {exports: {}};
  38530. var hasRequiredCombinator;
  38531. function requireCombinator () {
  38532. if (hasRequiredCombinator) return combinator.exports;
  38533. hasRequiredCombinator = 1;
  38534. (function (module, exports) {
  38535. exports.__esModule = true;
  38536. exports["default"] = void 0;
  38537. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  38538. var _types = /*@__PURE__*/ requireTypes();
  38539. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  38540. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  38541. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  38542. exports["default"] = /*#__PURE__*/function (_Node) {
  38543. _inheritsLoose(Combinator, _Node);
  38544. function Combinator(opts) {
  38545. var _this;
  38546. _this = _Node.call(this, opts) || this;
  38547. _this.type = _types.COMBINATOR;
  38548. return _this;
  38549. }
  38550. return Combinator;
  38551. }(_node["default"]);
  38552. module.exports = exports.default;
  38553. } (combinator, combinator.exports));
  38554. return combinator.exports;
  38555. }
  38556. var nesting = {exports: {}};
  38557. var hasRequiredNesting;
  38558. function requireNesting () {
  38559. if (hasRequiredNesting) return nesting.exports;
  38560. hasRequiredNesting = 1;
  38561. (function (module, exports) {
  38562. exports.__esModule = true;
  38563. exports["default"] = void 0;
  38564. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  38565. var _types = /*@__PURE__*/ requireTypes();
  38566. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  38567. function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); }
  38568. function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
  38569. exports["default"] = /*#__PURE__*/function (_Node) {
  38570. _inheritsLoose(Nesting, _Node);
  38571. function Nesting(opts) {
  38572. var _this;
  38573. _this = _Node.call(this, opts) || this;
  38574. _this.type = _types.NESTING;
  38575. _this.value = '&';
  38576. return _this;
  38577. }
  38578. return Nesting;
  38579. }(_node["default"]);
  38580. module.exports = exports.default;
  38581. } (nesting, nesting.exports));
  38582. return nesting.exports;
  38583. }
  38584. var sortAscending = {exports: {}};
  38585. var hasRequiredSortAscending;
  38586. function requireSortAscending () {
  38587. if (hasRequiredSortAscending) return sortAscending.exports;
  38588. hasRequiredSortAscending = 1;
  38589. (function (module, exports) {
  38590. exports.__esModule = true;
  38591. exports["default"] = sortAscending;
  38592. function sortAscending(list) {
  38593. return list.sort(function (a, b) {
  38594. return a - b;
  38595. });
  38596. }
  38597. module.exports = exports.default;
  38598. } (sortAscending, sortAscending.exports));
  38599. return sortAscending.exports;
  38600. }
  38601. var tokenize = {};
  38602. var tokenTypes = {};
  38603. var hasRequiredTokenTypes;
  38604. function requireTokenTypes () {
  38605. if (hasRequiredTokenTypes) return tokenTypes;
  38606. hasRequiredTokenTypes = 1;
  38607. tokenTypes.__esModule = true;
  38608. 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;
  38609. tokenTypes.ampersand = 38; // `&`.charCodeAt(0);
  38610. tokenTypes.asterisk = 42; // `*`.charCodeAt(0);
  38611. tokenTypes.at = 64; // `@`.charCodeAt(0);
  38612. tokenTypes.comma = 44; // `,`.charCodeAt(0);
  38613. tokenTypes.colon = 58; // `:`.charCodeAt(0);
  38614. tokenTypes.semicolon = 59; // `;`.charCodeAt(0);
  38615. tokenTypes.openParenthesis = 40; // `(`.charCodeAt(0);
  38616. tokenTypes.closeParenthesis = 41; // `)`.charCodeAt(0);
  38617. tokenTypes.openSquare = 91; // `[`.charCodeAt(0);
  38618. tokenTypes.closeSquare = 93; // `]`.charCodeAt(0);
  38619. tokenTypes.dollar = 36; // `$`.charCodeAt(0);
  38620. tokenTypes.tilde = 126; // `~`.charCodeAt(0);
  38621. tokenTypes.caret = 94; // `^`.charCodeAt(0);
  38622. tokenTypes.plus = 43; // `+`.charCodeAt(0);
  38623. tokenTypes.equals = 61; // `=`.charCodeAt(0);
  38624. tokenTypes.pipe = 124; // `|`.charCodeAt(0);
  38625. tokenTypes.greaterThan = 62; // `>`.charCodeAt(0);
  38626. tokenTypes.space = 32; // ` `.charCodeAt(0);
  38627. var singleQuote = tokenTypes.singleQuote = 39; // `'`.charCodeAt(0);
  38628. tokenTypes.doubleQuote = 34; // `"`.charCodeAt(0);
  38629. tokenTypes.slash = 47; // `/`.charCodeAt(0);
  38630. tokenTypes.bang = 33; // `!`.charCodeAt(0);
  38631. tokenTypes.backslash = 92; // '\\'.charCodeAt(0);
  38632. tokenTypes.cr = 13; // '\r'.charCodeAt(0);
  38633. tokenTypes.feed = 12; // '\f'.charCodeAt(0);
  38634. tokenTypes.newline = 10; // '\n'.charCodeAt(0);
  38635. tokenTypes.tab = 9; // '\t'.charCodeAt(0);
  38636. // Expose aliases primarily for readability.
  38637. tokenTypes.str = singleQuote;
  38638. // No good single character representation!
  38639. tokenTypes.comment = -1;
  38640. tokenTypes.word = -2;
  38641. tokenTypes.combinator = -3;
  38642. return tokenTypes;
  38643. }
  38644. var hasRequiredTokenize;
  38645. function requireTokenize () {
  38646. if (hasRequiredTokenize) return tokenize;
  38647. hasRequiredTokenize = 1;
  38648. (function (exports) {
  38649. exports.__esModule = true;
  38650. exports.FIELDS = void 0;
  38651. exports["default"] = tokenize;
  38652. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  38653. var _unescapable, _wordDelimiters;
  38654. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  38655. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  38656. 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);
  38657. var hex = {};
  38658. var hexChars = "0123456789abcdefABCDEF";
  38659. for (var i = 0; i < hexChars.length; i++) {
  38660. hex[hexChars.charCodeAt(i)] = true;
  38661. }
  38662. /**
  38663. * Returns the last index of the bar css word
  38664. * @param {string} css The string in which the word begins
  38665. * @param {number} start The index into the string where word's first letter occurs
  38666. */
  38667. function consumeWord(css, start) {
  38668. var next = start;
  38669. var code;
  38670. do {
  38671. code = css.charCodeAt(next);
  38672. if (wordDelimiters[code]) {
  38673. return next - 1;
  38674. } else if (code === t.backslash) {
  38675. next = consumeEscape(css, next) + 1;
  38676. } else {
  38677. // All other characters are part of the word
  38678. next++;
  38679. }
  38680. } while (next < css.length);
  38681. return next - 1;
  38682. }
  38683. /**
  38684. * Returns the last index of the escape sequence
  38685. * @param {string} css The string in which the sequence begins
  38686. * @param {number} start The index into the string where escape character (`\`) occurs.
  38687. */
  38688. function consumeEscape(css, start) {
  38689. var next = start;
  38690. var code = css.charCodeAt(next + 1);
  38691. if (unescapable[code]) ; else if (hex[code]) {
  38692. var hexDigits = 0;
  38693. // consume up to 6 hex chars
  38694. do {
  38695. next++;
  38696. hexDigits++;
  38697. code = css.charCodeAt(next + 1);
  38698. } while (hex[code] && hexDigits < 6);
  38699. // if fewer than 6 hex chars, a trailing space ends the escape
  38700. if (hexDigits < 6 && code === t.space) {
  38701. next++;
  38702. }
  38703. } else {
  38704. // the next char is part of the current word
  38705. next++;
  38706. }
  38707. return next;
  38708. }
  38709. exports.FIELDS = {
  38710. TYPE: 0,
  38711. START_LINE: 1,
  38712. START_COL: 2,
  38713. END_LINE: 3,
  38714. END_COL: 4,
  38715. START_POS: 5,
  38716. END_POS: 6
  38717. };
  38718. function tokenize(input) {
  38719. var tokens = [];
  38720. var css = input.css.valueOf();
  38721. var _css = css,
  38722. length = _css.length;
  38723. var offset = -1;
  38724. var line = 1;
  38725. var start = 0;
  38726. var end = 0;
  38727. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  38728. function unclosed(what, fix) {
  38729. if (input.safe) {
  38730. // fyi: this is never set to true.
  38731. css += fix;
  38732. next = css.length - 1;
  38733. } else {
  38734. throw input.error('Unclosed ' + what, line, start - offset, start);
  38735. }
  38736. }
  38737. while (start < length) {
  38738. code = css.charCodeAt(start);
  38739. if (code === t.newline) {
  38740. offset = start;
  38741. line += 1;
  38742. }
  38743. switch (code) {
  38744. case t.space:
  38745. case t.tab:
  38746. case t.newline:
  38747. case t.cr:
  38748. case t.feed:
  38749. next = start;
  38750. do {
  38751. next += 1;
  38752. code = css.charCodeAt(next);
  38753. if (code === t.newline) {
  38754. offset = next;
  38755. line += 1;
  38756. }
  38757. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  38758. tokenType = t.space;
  38759. endLine = line;
  38760. endColumn = next - offset - 1;
  38761. end = next;
  38762. break;
  38763. case t.plus:
  38764. case t.greaterThan:
  38765. case t.tilde:
  38766. case t.pipe:
  38767. next = start;
  38768. do {
  38769. next += 1;
  38770. code = css.charCodeAt(next);
  38771. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  38772. tokenType = t.combinator;
  38773. endLine = line;
  38774. endColumn = start - offset;
  38775. end = next;
  38776. break;
  38777. // Consume these characters as single tokens.
  38778. case t.asterisk:
  38779. case t.ampersand:
  38780. case t.bang:
  38781. case t.comma:
  38782. case t.equals:
  38783. case t.dollar:
  38784. case t.caret:
  38785. case t.openSquare:
  38786. case t.closeSquare:
  38787. case t.colon:
  38788. case t.semicolon:
  38789. case t.openParenthesis:
  38790. case t.closeParenthesis:
  38791. next = start;
  38792. tokenType = code;
  38793. endLine = line;
  38794. endColumn = start - offset;
  38795. end = next + 1;
  38796. break;
  38797. case t.singleQuote:
  38798. case t.doubleQuote:
  38799. quote = code === t.singleQuote ? "'" : '"';
  38800. next = start;
  38801. do {
  38802. escaped = false;
  38803. next = css.indexOf(quote, next + 1);
  38804. if (next === -1) {
  38805. unclosed('quote', quote);
  38806. }
  38807. escapePos = next;
  38808. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  38809. escapePos -= 1;
  38810. escaped = !escaped;
  38811. }
  38812. } while (escaped);
  38813. tokenType = t.str;
  38814. endLine = line;
  38815. endColumn = start - offset;
  38816. end = next + 1;
  38817. break;
  38818. default:
  38819. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  38820. next = css.indexOf('*/', start + 2) + 1;
  38821. if (next === 0) {
  38822. unclosed('comment', '*/');
  38823. }
  38824. content = css.slice(start, next + 1);
  38825. lines = content.split('\n');
  38826. last = lines.length - 1;
  38827. if (last > 0) {
  38828. nextLine = line + last;
  38829. nextOffset = next - lines[last].length;
  38830. } else {
  38831. nextLine = line;
  38832. nextOffset = offset;
  38833. }
  38834. tokenType = t.comment;
  38835. line = nextLine;
  38836. endLine = nextLine;
  38837. endColumn = next - nextOffset;
  38838. } else if (code === t.slash) {
  38839. next = start;
  38840. tokenType = code;
  38841. endLine = line;
  38842. endColumn = start - offset;
  38843. end = next + 1;
  38844. } else {
  38845. next = consumeWord(css, start);
  38846. tokenType = t.word;
  38847. endLine = line;
  38848. endColumn = next - offset;
  38849. }
  38850. end = next + 1;
  38851. break;
  38852. }
  38853. // Ensure that the token structure remains consistent
  38854. tokens.push([tokenType,
  38855. // [0] Token type
  38856. line,
  38857. // [1] Starting line
  38858. start - offset,
  38859. // [2] Starting column
  38860. endLine,
  38861. // [3] Ending line
  38862. endColumn,
  38863. // [4] Ending column
  38864. start,
  38865. // [5] Start position / Source index
  38866. end // [6] End position
  38867. ]);
  38868. // Reset offset for the next token
  38869. if (nextOffset) {
  38870. offset = nextOffset;
  38871. nextOffset = null;
  38872. }
  38873. start = end;
  38874. }
  38875. return tokens;
  38876. }
  38877. } (tokenize));
  38878. return tokenize;
  38879. }
  38880. var hasRequiredParser;
  38881. function requireParser () {
  38882. if (hasRequiredParser) return parser.exports;
  38883. hasRequiredParser = 1;
  38884. (function (module, exports) {
  38885. exports.__esModule = true;
  38886. exports["default"] = void 0;
  38887. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  38888. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  38889. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  38890. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  38891. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  38892. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  38893. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  38894. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  38895. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  38896. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  38897. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  38898. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  38899. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  38900. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  38901. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  38902. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  38903. var _util = /*@__PURE__*/ requireUtil$1();
  38904. var _WHITESPACE_TOKENS, _Object$assign;
  38905. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  38906. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  38907. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  38908. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
  38909. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  38910. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
  38911. 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);
  38912. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  38913. function tokenStart(token) {
  38914. return {
  38915. line: token[_tokenize.FIELDS.START_LINE],
  38916. column: token[_tokenize.FIELDS.START_COL]
  38917. };
  38918. }
  38919. function tokenEnd(token) {
  38920. return {
  38921. line: token[_tokenize.FIELDS.END_LINE],
  38922. column: token[_tokenize.FIELDS.END_COL]
  38923. };
  38924. }
  38925. function getSource(startLine, startColumn, endLine, endColumn) {
  38926. return {
  38927. start: {
  38928. line: startLine,
  38929. column: startColumn
  38930. },
  38931. end: {
  38932. line: endLine,
  38933. column: endColumn
  38934. }
  38935. };
  38936. }
  38937. function getTokenSource(token) {
  38938. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  38939. }
  38940. function getTokenSourceSpan(startToken, endToken) {
  38941. if (!startToken) {
  38942. return undefined;
  38943. }
  38944. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  38945. }
  38946. function unescapeProp(node, prop) {
  38947. var value = node[prop];
  38948. if (typeof value !== "string") {
  38949. return;
  38950. }
  38951. if (value.indexOf("\\") !== -1) {
  38952. (0, _util.ensureObject)(node, 'raws');
  38953. node[prop] = (0, _util.unesc)(value);
  38954. if (node.raws[prop] === undefined) {
  38955. node.raws[prop] = value;
  38956. }
  38957. }
  38958. return node;
  38959. }
  38960. function indexesOf(array, item) {
  38961. var i = -1;
  38962. var indexes = [];
  38963. while ((i = array.indexOf(item, i + 1)) !== -1) {
  38964. indexes.push(i);
  38965. }
  38966. return indexes;
  38967. }
  38968. function uniqs() {
  38969. var list = Array.prototype.concat.apply([], arguments);
  38970. return list.filter(function (item, i) {
  38971. return i === list.indexOf(item);
  38972. });
  38973. }
  38974. exports["default"] = /*#__PURE__*/function () {
  38975. function Parser(rule, options) {
  38976. if (options === void 0) {
  38977. options = {};
  38978. }
  38979. this.rule = rule;
  38980. this.options = Object.assign({
  38981. lossy: false,
  38982. safe: false
  38983. }, options);
  38984. this.position = 0;
  38985. this.nestingDepth = 0;
  38986. this.maxNestingDepth = (0, _util.resolveMaxNestingDepth)(this.options.maxNestingDepth);
  38987. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  38988. this.tokens = (0, _tokenize["default"])({
  38989. css: this.css,
  38990. error: this._errorGenerator(),
  38991. safe: this.options.safe
  38992. });
  38993. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  38994. this.root = new _root["default"]({
  38995. source: rootSource
  38996. });
  38997. this.root.errorGenerator = this._errorGenerator();
  38998. var selector = new _selector["default"]({
  38999. source: {
  39000. start: {
  39001. line: 1,
  39002. column: 1
  39003. }
  39004. },
  39005. sourceIndex: 0
  39006. });
  39007. this.root.append(selector);
  39008. this.current = selector;
  39009. this.loop();
  39010. }
  39011. var _proto = Parser.prototype;
  39012. _proto._errorGenerator = function _errorGenerator() {
  39013. var _this = this;
  39014. return function (message, errorOptions) {
  39015. if (typeof _this.rule === 'string') {
  39016. return new Error(message);
  39017. }
  39018. return _this.rule.error(message, errorOptions);
  39019. };
  39020. };
  39021. _proto.attribute = function attribute() {
  39022. var attr = [];
  39023. var startingToken = this.currToken;
  39024. this.position++;
  39025. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  39026. attr.push(this.currToken);
  39027. this.position++;
  39028. }
  39029. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  39030. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  39031. }
  39032. var len = attr.length;
  39033. var node = {
  39034. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  39035. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  39036. };
  39037. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  39038. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  39039. }
  39040. var pos = 0;
  39041. var spaceBefore = '';
  39042. var commentBefore = '';
  39043. var lastAdded = null;
  39044. var spaceAfterMeaningfulToken = false;
  39045. while (pos < len) {
  39046. var token = attr[pos];
  39047. var content = this.content(token);
  39048. var next = attr[pos + 1];
  39049. switch (token[_tokenize.FIELDS.TYPE]) {
  39050. case tokens.space:
  39051. // if (
  39052. // len === 1 ||
  39053. // pos === 0 && this.content(next) === '|'
  39054. // ) {
  39055. // return this.expected('attribute', token[TOKEN.START_POS], content);
  39056. // }
  39057. spaceAfterMeaningfulToken = true;
  39058. if (this.options.lossy) {
  39059. break;
  39060. }
  39061. if (lastAdded) {
  39062. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  39063. var prevContent = node.spaces[lastAdded].after || '';
  39064. node.spaces[lastAdded].after = prevContent + content;
  39065. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  39066. if (existingComment) {
  39067. node.raws.spaces[lastAdded].after = existingComment + content;
  39068. }
  39069. } else {
  39070. spaceBefore = spaceBefore + content;
  39071. commentBefore = commentBefore + content;
  39072. }
  39073. break;
  39074. case tokens.asterisk:
  39075. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  39076. node.operator = content;
  39077. lastAdded = 'operator';
  39078. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  39079. if (spaceBefore) {
  39080. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  39081. node.spaces.attribute.before = spaceBefore;
  39082. spaceBefore = '';
  39083. }
  39084. if (commentBefore) {
  39085. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  39086. node.raws.spaces.attribute.before = spaceBefore;
  39087. commentBefore = '';
  39088. }
  39089. node.namespace = (node.namespace || "") + content;
  39090. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  39091. if (rawValue) {
  39092. node.raws.namespace += content;
  39093. }
  39094. lastAdded = 'namespace';
  39095. }
  39096. spaceAfterMeaningfulToken = false;
  39097. break;
  39098. case tokens.dollar:
  39099. if (lastAdded === "value") {
  39100. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  39101. node.value += "$";
  39102. if (oldRawValue) {
  39103. node.raws.value = oldRawValue + "$";
  39104. }
  39105. break;
  39106. }
  39107. // Falls through
  39108. case tokens.caret:
  39109. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  39110. node.operator = content;
  39111. lastAdded = 'operator';
  39112. }
  39113. spaceAfterMeaningfulToken = false;
  39114. break;
  39115. case tokens.combinator:
  39116. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  39117. node.operator = content;
  39118. lastAdded = 'operator';
  39119. }
  39120. if (content !== '|') {
  39121. spaceAfterMeaningfulToken = false;
  39122. break;
  39123. }
  39124. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  39125. node.operator = content;
  39126. lastAdded = 'operator';
  39127. } else if (!node.namespace && !node.attribute) {
  39128. node.namespace = true;
  39129. }
  39130. spaceAfterMeaningfulToken = false;
  39131. break;
  39132. case tokens.word:
  39133. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  39134. // this look-ahead probably fails with comment nodes involved.
  39135. !node.operator && !node.namespace) {
  39136. node.namespace = content;
  39137. lastAdded = 'namespace';
  39138. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  39139. if (spaceBefore) {
  39140. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  39141. node.spaces.attribute.before = spaceBefore;
  39142. spaceBefore = '';
  39143. }
  39144. if (commentBefore) {
  39145. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  39146. node.raws.spaces.attribute.before = commentBefore;
  39147. commentBefore = '';
  39148. }
  39149. node.attribute = (node.attribute || "") + content;
  39150. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  39151. if (_rawValue) {
  39152. node.raws.attribute += content;
  39153. }
  39154. lastAdded = 'attribute';
  39155. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  39156. var _unescaped = (0, _util.unesc)(content);
  39157. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  39158. var oldValue = node.value || '';
  39159. node.value = oldValue + _unescaped;
  39160. node.quoteMark = null;
  39161. if (_unescaped !== content || _oldRawValue) {
  39162. (0, _util.ensureObject)(node, 'raws');
  39163. node.raws.value = (_oldRawValue || oldValue) + content;
  39164. }
  39165. lastAdded = 'value';
  39166. } else {
  39167. var insensitive = content === 'i' || content === "I";
  39168. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  39169. node.insensitive = insensitive;
  39170. if (!insensitive || content === "I") {
  39171. (0, _util.ensureObject)(node, 'raws');
  39172. node.raws.insensitiveFlag = content;
  39173. }
  39174. lastAdded = 'insensitive';
  39175. if (spaceBefore) {
  39176. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  39177. node.spaces.insensitive.before = spaceBefore;
  39178. spaceBefore = '';
  39179. }
  39180. if (commentBefore) {
  39181. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  39182. node.raws.spaces.insensitive.before = commentBefore;
  39183. commentBefore = '';
  39184. }
  39185. } else if (node.value || node.value === '') {
  39186. lastAdded = 'value';
  39187. node.value += content;
  39188. if (node.raws.value) {
  39189. node.raws.value += content;
  39190. }
  39191. }
  39192. }
  39193. spaceAfterMeaningfulToken = false;
  39194. break;
  39195. case tokens.str:
  39196. if (!node.attribute || !node.operator) {
  39197. return this.error("Expected an attribute followed by an operator preceding the string.", {
  39198. index: token[_tokenize.FIELDS.START_POS]
  39199. });
  39200. }
  39201. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  39202. unescaped = _unescapeValue.unescaped,
  39203. quoteMark = _unescapeValue.quoteMark;
  39204. node.value = unescaped;
  39205. node.quoteMark = quoteMark;
  39206. lastAdded = 'value';
  39207. (0, _util.ensureObject)(node, 'raws');
  39208. node.raws.value = content;
  39209. spaceAfterMeaningfulToken = false;
  39210. break;
  39211. case tokens.equals:
  39212. if (!node.attribute) {
  39213. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  39214. }
  39215. if (node.value) {
  39216. return this.error('Unexpected "=" found; an operator was already defined.', {
  39217. index: token[_tokenize.FIELDS.START_POS]
  39218. });
  39219. }
  39220. node.operator = node.operator ? node.operator + content : content;
  39221. lastAdded = 'operator';
  39222. spaceAfterMeaningfulToken = false;
  39223. break;
  39224. case tokens.comment:
  39225. if (lastAdded) {
  39226. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  39227. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  39228. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  39229. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  39230. node.raws.spaces[lastAdded].after = rawLastComment + content;
  39231. } else {
  39232. var lastValue = node[lastAdded] || '';
  39233. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  39234. (0, _util.ensureObject)(node, 'raws');
  39235. node.raws[lastAdded] = rawLastValue + content;
  39236. }
  39237. } else {
  39238. commentBefore = commentBefore + content;
  39239. }
  39240. break;
  39241. default:
  39242. return this.error("Unexpected \"" + content + "\" found.", {
  39243. index: token[_tokenize.FIELDS.START_POS]
  39244. });
  39245. }
  39246. pos++;
  39247. }
  39248. unescapeProp(node, "attribute");
  39249. unescapeProp(node, "namespace");
  39250. this.newNode(new _attribute["default"](node));
  39251. this.position++;
  39252. }
  39253. /**
  39254. * return a node containing meaningless garbage up to (but not including) the specified token position.
  39255. * if the token position is negative, all remaining tokens are consumed.
  39256. *
  39257. * This returns an array containing a single string node if all whitespace,
  39258. * otherwise an array of comment nodes with space before and after.
  39259. *
  39260. * These tokens are not added to the current selector, the caller can add them or use them to amend
  39261. * a previous node's space metadata.
  39262. *
  39263. * In lossy mode, this returns only comments.
  39264. */;
  39265. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  39266. if (stopPosition < 0) {
  39267. stopPosition = this.tokens.length;
  39268. }
  39269. var startPosition = this.position;
  39270. var nodes = [];
  39271. var space = "";
  39272. var lastComment = undefined;
  39273. do {
  39274. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  39275. if (!this.options.lossy) {
  39276. space += this.content();
  39277. }
  39278. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  39279. var spaces = {};
  39280. if (space) {
  39281. spaces.before = space;
  39282. space = "";
  39283. }
  39284. lastComment = new _comment["default"]({
  39285. value: this.content(),
  39286. source: getTokenSource(this.currToken),
  39287. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  39288. spaces: spaces
  39289. });
  39290. nodes.push(lastComment);
  39291. }
  39292. } while (++this.position < stopPosition);
  39293. if (space) {
  39294. if (lastComment) {
  39295. lastComment.spaces.after = space;
  39296. } else if (!this.options.lossy) {
  39297. var firstToken = this.tokens[startPosition];
  39298. var lastToken = this.tokens[this.position - 1];
  39299. nodes.push(new _string["default"]({
  39300. value: '',
  39301. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  39302. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  39303. spaces: {
  39304. before: space,
  39305. after: ''
  39306. }
  39307. }));
  39308. }
  39309. }
  39310. return nodes;
  39311. }
  39312. /**
  39313. *
  39314. * @param {*} nodes
  39315. */;
  39316. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  39317. var _this2 = this;
  39318. if (requiredSpace === void 0) {
  39319. requiredSpace = false;
  39320. }
  39321. var space = "";
  39322. var rawSpace = "";
  39323. nodes.forEach(function (n) {
  39324. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  39325. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  39326. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  39327. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  39328. });
  39329. if (rawSpace === space) {
  39330. rawSpace = undefined;
  39331. }
  39332. var result = {
  39333. space: space,
  39334. rawSpace: rawSpace
  39335. };
  39336. return result;
  39337. };
  39338. _proto.isNamedCombinator = function isNamedCombinator(position) {
  39339. if (position === void 0) {
  39340. position = this.position;
  39341. }
  39342. 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;
  39343. };
  39344. _proto.namedCombinator = function namedCombinator() {
  39345. if (this.isNamedCombinator()) {
  39346. var nameRaw = this.content(this.tokens[this.position + 1]);
  39347. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  39348. var raws = {};
  39349. if (name !== nameRaw) {
  39350. raws.value = "/" + nameRaw + "/";
  39351. }
  39352. var node = new _combinator["default"]({
  39353. value: "/" + name + "/",
  39354. 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]),
  39355. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  39356. raws: raws
  39357. });
  39358. this.position = this.position + 3;
  39359. return node;
  39360. } else {
  39361. this.unexpected();
  39362. }
  39363. };
  39364. _proto.combinator = function combinator() {
  39365. var _this3 = this;
  39366. if (this.content() === '|') {
  39367. return this.namespace();
  39368. }
  39369. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  39370. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  39371. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  39372. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  39373. if (nodes.length > 0) {
  39374. var last = this.current.last;
  39375. if (last) {
  39376. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  39377. space = _this$convertWhitespa.space,
  39378. rawSpace = _this$convertWhitespa.rawSpace;
  39379. if (rawSpace !== undefined) {
  39380. last.rawSpaceAfter += rawSpace;
  39381. }
  39382. last.spaces.after += space;
  39383. } else {
  39384. nodes.forEach(function (n) {
  39385. return _this3.newNode(n);
  39386. });
  39387. }
  39388. }
  39389. return;
  39390. }
  39391. var firstToken = this.currToken;
  39392. var spaceOrDescendantSelectorNodes = undefined;
  39393. if (nextSigTokenPos > this.position) {
  39394. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  39395. }
  39396. var node;
  39397. if (this.isNamedCombinator()) {
  39398. node = this.namedCombinator();
  39399. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  39400. node = new _combinator["default"]({
  39401. value: this.content(),
  39402. source: getTokenSource(this.currToken),
  39403. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  39404. });
  39405. this.position++;
  39406. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  39407. this.unexpected();
  39408. }
  39409. if (node) {
  39410. if (spaceOrDescendantSelectorNodes) {
  39411. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  39412. _space = _this$convertWhitespa2.space,
  39413. _rawSpace = _this$convertWhitespa2.rawSpace;
  39414. node.spaces.before = _space;
  39415. node.rawSpaceBefore = _rawSpace;
  39416. }
  39417. } else {
  39418. // descendant combinator
  39419. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  39420. _space2 = _this$convertWhitespa3.space,
  39421. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  39422. if (!_rawSpace2) {
  39423. _rawSpace2 = _space2;
  39424. }
  39425. var spaces = {};
  39426. var raws = {
  39427. spaces: {}
  39428. };
  39429. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  39430. spaces.before = _space2.slice(0, _space2.length - 1);
  39431. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  39432. } else if (_space2[0] === ' ' && _rawSpace2[0] === ' ') {
  39433. spaces.after = _space2.slice(1);
  39434. raws.spaces.after = _rawSpace2.slice(1);
  39435. } else {
  39436. raws.value = _rawSpace2;
  39437. }
  39438. node = new _combinator["default"]({
  39439. value: ' ',
  39440. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  39441. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  39442. spaces: spaces,
  39443. raws: raws
  39444. });
  39445. }
  39446. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  39447. node.spaces.after = this.optionalSpace(this.content());
  39448. this.position++;
  39449. }
  39450. return this.newNode(node);
  39451. };
  39452. _proto.comma = function comma() {
  39453. if (this.position === this.tokens.length - 1) {
  39454. this.root.trailingComma = true;
  39455. this.position++;
  39456. return;
  39457. }
  39458. this.current._inferEndPosition();
  39459. var selector = new _selector["default"]({
  39460. source: {
  39461. start: tokenStart(this.tokens[this.position + 1])
  39462. },
  39463. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  39464. });
  39465. this.current.parent.append(selector);
  39466. this.current = selector;
  39467. this.position++;
  39468. };
  39469. _proto.comment = function comment() {
  39470. var current = this.currToken;
  39471. this.newNode(new _comment["default"]({
  39472. value: this.content(),
  39473. source: getTokenSource(current),
  39474. sourceIndex: current[_tokenize.FIELDS.START_POS]
  39475. }));
  39476. this.position++;
  39477. };
  39478. _proto.error = function error(message, opts) {
  39479. throw this.root.error(message, opts);
  39480. };
  39481. _proto.missingBackslash = function missingBackslash() {
  39482. return this.error('Expected a backslash preceding the semicolon.', {
  39483. index: this.currToken[_tokenize.FIELDS.START_POS]
  39484. });
  39485. };
  39486. _proto.missingParenthesis = function missingParenthesis() {
  39487. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  39488. };
  39489. _proto.missingSquareBracket = function missingSquareBracket() {
  39490. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  39491. };
  39492. _proto.unexpected = function unexpected() {
  39493. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  39494. };
  39495. _proto.unexpectedPipe = function unexpectedPipe() {
  39496. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  39497. };
  39498. _proto.namespace = function namespace() {
  39499. var before = this.prevToken && this.content(this.prevToken) || true;
  39500. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  39501. this.position++;
  39502. return this.word(before);
  39503. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  39504. this.position++;
  39505. return this.universal(before);
  39506. }
  39507. this.unexpectedPipe();
  39508. };
  39509. _proto.nesting = function nesting() {
  39510. if (this.nextToken) {
  39511. var nextContent = this.content(this.nextToken);
  39512. if (nextContent === "|") {
  39513. this.position++;
  39514. return;
  39515. }
  39516. }
  39517. var current = this.currToken;
  39518. this.newNode(new _nesting["default"]({
  39519. value: this.content(),
  39520. source: getTokenSource(current),
  39521. sourceIndex: current[_tokenize.FIELDS.START_POS]
  39522. }));
  39523. this.position++;
  39524. };
  39525. _proto.parentheses = function parentheses() {
  39526. var last = this.current.last;
  39527. var unbalanced = 1;
  39528. this.position++;
  39529. if (last && last.type === types.PSEUDO) {
  39530. var selector = new _selector["default"]({
  39531. source: {
  39532. start: tokenStart(this.tokens[this.position])
  39533. },
  39534. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  39535. });
  39536. var cache = this.current;
  39537. last.append(selector);
  39538. this.current = selector;
  39539. // Track nesting depth so deeply nested pseudo selectors raise a
  39540. // catchable error instead of overflowing the call stack. The
  39541. // counter is restored in `finally` so the parser is never left in
  39542. // an inconsistent state, even on the error path.
  39543. this.nestingDepth++;
  39544. try {
  39545. if (this.nestingDepth > this.maxNestingDepth) {
  39546. this.error("Cannot parse selector: nesting depth exceeds the maximum of " + this.maxNestingDepth + ".", {
  39547. index: this.currToken[_tokenize.FIELDS.START_POS]
  39548. });
  39549. }
  39550. while (this.position < this.tokens.length && unbalanced) {
  39551. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  39552. unbalanced++;
  39553. }
  39554. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  39555. unbalanced--;
  39556. }
  39557. if (unbalanced) {
  39558. this.parse();
  39559. } else {
  39560. this.current.source.end = tokenEnd(this.currToken);
  39561. this.current.parent.source.end = tokenEnd(this.currToken);
  39562. this.position++;
  39563. }
  39564. }
  39565. } finally {
  39566. this.nestingDepth--;
  39567. }
  39568. this.current = cache;
  39569. } else {
  39570. // I think this case should be an error. It's used to implement a basic parse of media queries
  39571. // but I don't think it's a good idea.
  39572. var parenStart = this.currToken;
  39573. var parenValue = "(";
  39574. var parenEnd;
  39575. while (this.position < this.tokens.length && unbalanced) {
  39576. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  39577. unbalanced++;
  39578. }
  39579. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  39580. unbalanced--;
  39581. }
  39582. parenEnd = this.currToken;
  39583. parenValue += this.parseParenthesisToken(this.currToken);
  39584. this.position++;
  39585. }
  39586. if (last) {
  39587. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  39588. } else {
  39589. this.newNode(new _string["default"]({
  39590. value: parenValue,
  39591. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  39592. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  39593. }));
  39594. }
  39595. }
  39596. if (unbalanced) {
  39597. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  39598. }
  39599. };
  39600. _proto.pseudo = function pseudo() {
  39601. var _this4 = this;
  39602. var pseudoStr = '';
  39603. var startingToken = this.currToken;
  39604. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  39605. pseudoStr += this.content();
  39606. this.position++;
  39607. }
  39608. if (!this.currToken) {
  39609. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  39610. }
  39611. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  39612. this.splitWord(false, function (first, length) {
  39613. pseudoStr += first;
  39614. _this4.newNode(new _pseudo["default"]({
  39615. value: pseudoStr,
  39616. source: getTokenSourceSpan(startingToken, _this4.currToken),
  39617. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  39618. }));
  39619. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  39620. _this4.error('Misplaced parenthesis.', {
  39621. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  39622. });
  39623. }
  39624. });
  39625. } else {
  39626. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  39627. }
  39628. };
  39629. _proto.space = function space() {
  39630. var content = this.content();
  39631. // Handle space before and after the selector
  39632. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  39633. return node.type === 'comment';
  39634. })) {
  39635. this.spaces = this.optionalSpace(content);
  39636. this.position++;
  39637. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  39638. this.current.last.spaces.after = this.optionalSpace(content);
  39639. this.position++;
  39640. } else {
  39641. this.combinator();
  39642. }
  39643. };
  39644. _proto.string = function string() {
  39645. var current = this.currToken;
  39646. this.newNode(new _string["default"]({
  39647. value: this.content(),
  39648. source: getTokenSource(current),
  39649. sourceIndex: current[_tokenize.FIELDS.START_POS]
  39650. }));
  39651. this.position++;
  39652. };
  39653. _proto.universal = function universal(namespace) {
  39654. var nextToken = this.nextToken;
  39655. if (nextToken && this.content(nextToken) === '|') {
  39656. this.position++;
  39657. return this.namespace();
  39658. }
  39659. var current = this.currToken;
  39660. this.newNode(new _universal["default"]({
  39661. value: this.content(),
  39662. source: getTokenSource(current),
  39663. sourceIndex: current[_tokenize.FIELDS.START_POS]
  39664. }), namespace);
  39665. this.position++;
  39666. };
  39667. _proto.splitWord = function splitWord(namespace, firstCallback) {
  39668. var _this5 = this;
  39669. var nextToken = this.nextToken;
  39670. var word = this.content();
  39671. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  39672. this.position++;
  39673. var current = this.content();
  39674. word += current;
  39675. if (current.lastIndexOf('\\') === current.length - 1) {
  39676. var next = this.nextToken;
  39677. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  39678. word += this.requiredSpace(this.content(next));
  39679. this.position++;
  39680. }
  39681. }
  39682. nextToken = this.nextToken;
  39683. }
  39684. var hasClass = indexesOf(word, '.').filter(function (i) {
  39685. // Allow escaped dot within class name
  39686. var escapedDot = word[i - 1] === '\\';
  39687. // Allow decimal numbers percent in @keyframes
  39688. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  39689. return !escapedDot && !isKeyframesPercent;
  39690. });
  39691. var hasId = indexesOf(word, '#').filter(function (i) {
  39692. return word[i - 1] !== '\\';
  39693. });
  39694. // Eliminate Sass interpolations from the list of id indexes
  39695. var interpolations = indexesOf(word, '#{');
  39696. if (interpolations.length) {
  39697. hasId = hasId.filter(function (hashIndex) {
  39698. return !~interpolations.indexOf(hashIndex);
  39699. });
  39700. }
  39701. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  39702. indices.forEach(function (ind, i) {
  39703. var index = indices[i + 1] || word.length;
  39704. var value = word.slice(ind, index);
  39705. if (i === 0 && firstCallback) {
  39706. return firstCallback.call(_this5, value, indices.length);
  39707. }
  39708. var node;
  39709. var current = _this5.currToken;
  39710. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  39711. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  39712. if (~hasClass.indexOf(ind)) {
  39713. var classNameOpts = {
  39714. value: value.slice(1),
  39715. source: source,
  39716. sourceIndex: sourceIndex
  39717. };
  39718. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  39719. } else if (~hasId.indexOf(ind)) {
  39720. var idOpts = {
  39721. value: value.slice(1),
  39722. source: source,
  39723. sourceIndex: sourceIndex
  39724. };
  39725. node = new _id["default"](unescapeProp(idOpts, "value"));
  39726. } else {
  39727. var tagOpts = {
  39728. value: value,
  39729. source: source,
  39730. sourceIndex: sourceIndex
  39731. };
  39732. unescapeProp(tagOpts, "value");
  39733. node = new _tag["default"](tagOpts);
  39734. }
  39735. _this5.newNode(node, namespace);
  39736. // Ensure that the namespace is used only once
  39737. namespace = null;
  39738. });
  39739. this.position++;
  39740. };
  39741. _proto.word = function word(namespace) {
  39742. var nextToken = this.nextToken;
  39743. if (nextToken && this.content(nextToken) === '|') {
  39744. this.position++;
  39745. return this.namespace();
  39746. }
  39747. return this.splitWord(namespace);
  39748. };
  39749. _proto.loop = function loop() {
  39750. while (this.position < this.tokens.length) {
  39751. this.parse(true);
  39752. }
  39753. this.current._inferEndPosition();
  39754. return this.root;
  39755. };
  39756. _proto.parse = function parse(throwOnParenthesis) {
  39757. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  39758. case tokens.space:
  39759. this.space();
  39760. break;
  39761. case tokens.comment:
  39762. this.comment();
  39763. break;
  39764. case tokens.openParenthesis:
  39765. this.parentheses();
  39766. break;
  39767. case tokens.closeParenthesis:
  39768. if (throwOnParenthesis) {
  39769. this.missingParenthesis();
  39770. }
  39771. break;
  39772. case tokens.openSquare:
  39773. this.attribute();
  39774. break;
  39775. case tokens.dollar:
  39776. case tokens.caret:
  39777. case tokens.equals:
  39778. case tokens.word:
  39779. this.word();
  39780. break;
  39781. case tokens.colon:
  39782. this.pseudo();
  39783. break;
  39784. case tokens.comma:
  39785. this.comma();
  39786. break;
  39787. case tokens.asterisk:
  39788. this.universal();
  39789. break;
  39790. case tokens.ampersand:
  39791. this.nesting();
  39792. break;
  39793. case tokens.slash:
  39794. case tokens.combinator:
  39795. this.combinator();
  39796. break;
  39797. case tokens.str:
  39798. this.string();
  39799. break;
  39800. // These cases throw; no break needed.
  39801. case tokens.closeSquare:
  39802. this.missingSquareBracket();
  39803. case tokens.semicolon:
  39804. this.missingBackslash();
  39805. default:
  39806. this.unexpected();
  39807. }
  39808. }
  39809. /**
  39810. * Helpers
  39811. */;
  39812. _proto.expected = function expected(description, index, found) {
  39813. if (Array.isArray(description)) {
  39814. var last = description.pop();
  39815. description = description.join(', ') + " or " + last;
  39816. }
  39817. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  39818. if (!found) {
  39819. return this.error("Expected " + an + " " + description + ".", {
  39820. index: index
  39821. });
  39822. }
  39823. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  39824. index: index
  39825. });
  39826. };
  39827. _proto.requiredSpace = function requiredSpace(space) {
  39828. return this.options.lossy ? ' ' : space;
  39829. };
  39830. _proto.optionalSpace = function optionalSpace(space) {
  39831. return this.options.lossy ? '' : space;
  39832. };
  39833. _proto.lossySpace = function lossySpace(space, required) {
  39834. if (this.options.lossy) {
  39835. return required ? ' ' : '';
  39836. } else {
  39837. return space;
  39838. }
  39839. };
  39840. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  39841. var content = this.content(token);
  39842. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  39843. return this.requiredSpace(content);
  39844. } else {
  39845. return content;
  39846. }
  39847. };
  39848. _proto.newNode = function newNode(node, namespace) {
  39849. if (namespace) {
  39850. if (/^ +$/.test(namespace)) {
  39851. if (!this.options.lossy) {
  39852. this.spaces = (this.spaces || '') + namespace;
  39853. }
  39854. namespace = true;
  39855. }
  39856. node.namespace = namespace;
  39857. unescapeProp(node, "namespace");
  39858. }
  39859. if (this.spaces) {
  39860. node.spaces.before = this.spaces;
  39861. this.spaces = '';
  39862. }
  39863. return this.current.append(node);
  39864. };
  39865. _proto.content = function content(token) {
  39866. if (token === void 0) {
  39867. token = this.currToken;
  39868. }
  39869. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  39870. };
  39871. /**
  39872. * returns the index of the next non-whitespace, non-comment token.
  39873. * returns -1 if no meaningful token is found.
  39874. */
  39875. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  39876. if (startPosition === void 0) {
  39877. startPosition = this.position + 1;
  39878. }
  39879. var searchPosition = startPosition;
  39880. while (searchPosition < this.tokens.length) {
  39881. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  39882. searchPosition++;
  39883. continue;
  39884. } else {
  39885. return searchPosition;
  39886. }
  39887. }
  39888. return -1;
  39889. };
  39890. _createClass(Parser, [{
  39891. key: "currToken",
  39892. get: function get() {
  39893. return this.tokens[this.position];
  39894. }
  39895. }, {
  39896. key: "nextToken",
  39897. get: function get() {
  39898. return this.tokens[this.position + 1];
  39899. }
  39900. }, {
  39901. key: "prevToken",
  39902. get: function get() {
  39903. return this.tokens[this.position - 1];
  39904. }
  39905. }]);
  39906. return Parser;
  39907. }();
  39908. module.exports = exports.default;
  39909. } (parser, parser.exports));
  39910. return parser.exports;
  39911. }
  39912. var hasRequiredProcessor;
  39913. function requireProcessor () {
  39914. if (hasRequiredProcessor) return processor.exports;
  39915. hasRequiredProcessor = 1;
  39916. (function (module, exports) {
  39917. exports.__esModule = true;
  39918. exports["default"] = void 0;
  39919. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  39920. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  39921. exports["default"] = /*#__PURE__*/function () {
  39922. function Processor(func, options) {
  39923. this.func = func || function noop() {};
  39924. this.funcRes = null;
  39925. this.options = options;
  39926. }
  39927. var _proto = Processor.prototype;
  39928. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  39929. if (options === void 0) {
  39930. options = {};
  39931. }
  39932. var merged = Object.assign({}, this.options, options);
  39933. if (merged.updateSelector === false) {
  39934. return false;
  39935. } else {
  39936. return typeof rule !== "string";
  39937. }
  39938. };
  39939. _proto._isLossy = function _isLossy(options) {
  39940. if (options === void 0) {
  39941. options = {};
  39942. }
  39943. var merged = Object.assign({}, this.options, options);
  39944. if (merged.lossless === false) {
  39945. return true;
  39946. } else {
  39947. return false;
  39948. }
  39949. };
  39950. _proto._root = function _root(rule, options) {
  39951. if (options === void 0) {
  39952. options = {};
  39953. }
  39954. var parser = new _parser["default"](rule, this._parseOptions(options));
  39955. return parser.root;
  39956. };
  39957. _proto._parseOptions = function _parseOptions(options) {
  39958. var merged = Object.assign({}, this.options, options);
  39959. return {
  39960. lossy: this._isLossy(merged),
  39961. maxNestingDepth: merged.maxNestingDepth
  39962. };
  39963. };
  39964. _proto._stringifyOptions = function _stringifyOptions(options) {
  39965. var merged = Object.assign({}, this.options, options);
  39966. return {
  39967. maxNestingDepth: merged.maxNestingDepth
  39968. };
  39969. };
  39970. _proto._run = function _run(rule, options) {
  39971. var _this = this;
  39972. if (options === void 0) {
  39973. options = {};
  39974. }
  39975. return new Promise(function (resolve, reject) {
  39976. try {
  39977. var root = _this._root(rule, options);
  39978. Promise.resolve(_this.func(root)).then(function (transform) {
  39979. var string = undefined;
  39980. if (_this._shouldUpdateSelector(rule, options)) {
  39981. string = root.toString(_this._stringifyOptions(options));
  39982. rule.selector = string;
  39983. }
  39984. return {
  39985. transform: transform,
  39986. root: root,
  39987. string: string
  39988. };
  39989. }).then(resolve, reject);
  39990. } catch (e) {
  39991. reject(e);
  39992. return;
  39993. }
  39994. });
  39995. };
  39996. _proto._runSync = function _runSync(rule, options) {
  39997. if (options === void 0) {
  39998. options = {};
  39999. }
  40000. var root = this._root(rule, options);
  40001. var transform = this.func(root);
  40002. if (transform && typeof transform.then === "function") {
  40003. throw new Error("Selector processor returned a promise to a synchronous call.");
  40004. }
  40005. var string = undefined;
  40006. if (options.updateSelector && typeof rule !== "string") {
  40007. string = root.toString(this._stringifyOptions(options));
  40008. rule.selector = string;
  40009. }
  40010. return {
  40011. transform: transform,
  40012. root: root,
  40013. string: string
  40014. };
  40015. }
  40016. /**
  40017. * Process rule into a selector AST.
  40018. *
  40019. * @param rule {postcss.Rule | string} The css selector to be processed
  40020. * @param options The options for processing
  40021. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  40022. */;
  40023. _proto.ast = function ast(rule, options) {
  40024. return this._run(rule, options).then(function (result) {
  40025. return result.root;
  40026. });
  40027. }
  40028. /**
  40029. * Process rule into a selector AST synchronously.
  40030. *
  40031. * @param rule {postcss.Rule | string} The css selector to be processed
  40032. * @param options The options for processing
  40033. * @returns {parser.Root} The AST of the selector after processing it.
  40034. */;
  40035. _proto.astSync = function astSync(rule, options) {
  40036. return this._runSync(rule, options).root;
  40037. }
  40038. /**
  40039. * Process a selector into a transformed value asynchronously
  40040. *
  40041. * @param rule {postcss.Rule | string} The css selector to be processed
  40042. * @param options The options for processing
  40043. * @returns {Promise<any>} The value returned by the processor.
  40044. */;
  40045. _proto.transform = function transform(rule, options) {
  40046. return this._run(rule, options).then(function (result) {
  40047. return result.transform;
  40048. });
  40049. }
  40050. /**
  40051. * Process a selector into a transformed value synchronously.
  40052. *
  40053. * @param rule {postcss.Rule | string} The css selector to be processed
  40054. * @param options The options for processing
  40055. * @returns {any} The value returned by the processor.
  40056. */;
  40057. _proto.transformSync = function transformSync(rule, options) {
  40058. return this._runSync(rule, options).transform;
  40059. }
  40060. /**
  40061. * Process a selector into a new selector string asynchronously.
  40062. *
  40063. * @param rule {postcss.Rule | string} The css selector to be processed
  40064. * @param options The options for processing
  40065. * @returns {string} the selector after processing.
  40066. */;
  40067. _proto.process = function process(rule, options) {
  40068. var _this2 = this;
  40069. return this._run(rule, options).then(function (result) {
  40070. return result.string || result.root.toString(_this2._stringifyOptions(options));
  40071. });
  40072. }
  40073. /**
  40074. * Process a selector into a new selector string synchronously.
  40075. *
  40076. * @param rule {postcss.Rule | string} The css selector to be processed
  40077. * @param options The options for processing
  40078. * @returns {string} the selector after processing.
  40079. */;
  40080. _proto.processSync = function processSync(rule, options) {
  40081. var result = this._runSync(rule, options);
  40082. return result.string || result.root.toString(this._stringifyOptions(options));
  40083. };
  40084. return Processor;
  40085. }();
  40086. module.exports = exports.default;
  40087. } (processor, processor.exports));
  40088. return processor.exports;
  40089. }
  40090. var selectors = {};
  40091. var constructors = {};
  40092. var hasRequiredConstructors;
  40093. function requireConstructors () {
  40094. if (hasRequiredConstructors) return constructors;
  40095. hasRequiredConstructors = 1;
  40096. constructors.__esModule = true;
  40097. 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;
  40098. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  40099. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  40100. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  40101. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  40102. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  40103. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  40104. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  40105. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  40106. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  40107. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  40108. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  40109. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  40110. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  40111. constructors.attribute = function attribute(opts) {
  40112. return new _attribute["default"](opts);
  40113. };
  40114. constructors.className = function className(opts) {
  40115. return new _className["default"](opts);
  40116. };
  40117. constructors.combinator = function combinator(opts) {
  40118. return new _combinator["default"](opts);
  40119. };
  40120. constructors.comment = function comment(opts) {
  40121. return new _comment["default"](opts);
  40122. };
  40123. constructors.id = function id(opts) {
  40124. return new _id["default"](opts);
  40125. };
  40126. constructors.nesting = function nesting(opts) {
  40127. return new _nesting["default"](opts);
  40128. };
  40129. constructors.pseudo = function pseudo(opts) {
  40130. return new _pseudo["default"](opts);
  40131. };
  40132. constructors.root = function root(opts) {
  40133. return new _root["default"](opts);
  40134. };
  40135. constructors.selector = function selector(opts) {
  40136. return new _selector["default"](opts);
  40137. };
  40138. constructors.string = function string(opts) {
  40139. return new _string["default"](opts);
  40140. };
  40141. constructors.tag = function tag(opts) {
  40142. return new _tag["default"](opts);
  40143. };
  40144. constructors.universal = function universal(opts) {
  40145. return new _universal["default"](opts);
  40146. };
  40147. return constructors;
  40148. }
  40149. var guards = {};
  40150. var hasRequiredGuards;
  40151. function requireGuards () {
  40152. if (hasRequiredGuards) return guards;
  40153. hasRequiredGuards = 1;
  40154. guards.__esModule = true;
  40155. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  40156. guards.isContainer = isContainer;
  40157. guards.isIdentifier = void 0;
  40158. guards.isNamespace = isNamespace;
  40159. guards.isNesting = void 0;
  40160. guards.isNode = isNode;
  40161. guards.isPseudo = void 0;
  40162. guards.isPseudoClass = isPseudoClass;
  40163. guards.isPseudoElement = isPseudoElement;
  40164. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  40165. var _types = /*@__PURE__*/ requireTypes();
  40166. var _IS_TYPE;
  40167. 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);
  40168. function isNode(node) {
  40169. return typeof node === "object" && IS_TYPE[node.type];
  40170. }
  40171. function isNodeType(type, node) {
  40172. return isNode(node) && node.type === type;
  40173. }
  40174. var isAttribute = guards.isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  40175. guards.isClassName = isNodeType.bind(null, _types.CLASS);
  40176. guards.isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  40177. guards.isComment = isNodeType.bind(null, _types.COMMENT);
  40178. guards.isIdentifier = isNodeType.bind(null, _types.ID);
  40179. guards.isNesting = isNodeType.bind(null, _types.NESTING);
  40180. var isPseudo = guards.isPseudo = isNodeType.bind(null, _types.PSEUDO);
  40181. guards.isRoot = isNodeType.bind(null, _types.ROOT);
  40182. guards.isSelector = isNodeType.bind(null, _types.SELECTOR);
  40183. guards.isString = isNodeType.bind(null, _types.STRING);
  40184. var isTag = guards.isTag = isNodeType.bind(null, _types.TAG);
  40185. guards.isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  40186. function isPseudoElement(node) {
  40187. 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");
  40188. }
  40189. function isPseudoClass(node) {
  40190. return isPseudo(node) && !isPseudoElement(node);
  40191. }
  40192. function isContainer(node) {
  40193. return !!(isNode(node) && node.walk);
  40194. }
  40195. function isNamespace(node) {
  40196. return isAttribute(node) || isTag(node);
  40197. }
  40198. return guards;
  40199. }
  40200. var hasRequiredSelectors;
  40201. function requireSelectors () {
  40202. if (hasRequiredSelectors) return selectors;
  40203. hasRequiredSelectors = 1;
  40204. (function (exports) {
  40205. exports.__esModule = true;
  40206. var _types = /*@__PURE__*/ requireTypes();
  40207. Object.keys(_types).forEach(function (key) {
  40208. if (key === "default" || key === "__esModule") return;
  40209. if (key in exports && exports[key] === _types[key]) return;
  40210. exports[key] = _types[key];
  40211. });
  40212. var _constructors = /*@__PURE__*/ requireConstructors();
  40213. Object.keys(_constructors).forEach(function (key) {
  40214. if (key === "default" || key === "__esModule") return;
  40215. if (key in exports && exports[key] === _constructors[key]) return;
  40216. exports[key] = _constructors[key];
  40217. });
  40218. var _guards = /*@__PURE__*/ requireGuards();
  40219. Object.keys(_guards).forEach(function (key) {
  40220. if (key === "default" || key === "__esModule") return;
  40221. if (key in exports && exports[key] === _guards[key]) return;
  40222. exports[key] = _guards[key];
  40223. });
  40224. } (selectors));
  40225. return selectors;
  40226. }
  40227. var hasRequiredDist;
  40228. function requireDist () {
  40229. if (hasRequiredDist) return dist.exports;
  40230. hasRequiredDist = 1;
  40231. (function (module, exports) {
  40232. exports.__esModule = true;
  40233. exports["default"] = void 0;
  40234. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  40235. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  40236. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
  40237. function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
  40238. var parser = function parser(processor) {
  40239. return new _processor["default"](processor);
  40240. };
  40241. Object.assign(parser, selectors);
  40242. delete parser.__esModule;
  40243. exports["default"] = parser;
  40244. module.exports = exports.default;
  40245. } (dist, dist.exports));
  40246. return dist.exports;
  40247. }
  40248. var distExports = /*@__PURE__*/ requireDist();
  40249. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  40250. const animationNameRE = /^(?:-\w+-)?animation-name$/;
  40251. const animationRE = /^(?:-\w+-)?animation$/;
  40252. const keyframesRE = /^(?:-\w+-)?keyframes$/;
  40253. const scopedPlugin = (id = "") => {
  40254. const keyframes = /* @__PURE__ */ Object.create(null);
  40255. const shortId = id.replace(/^data-v-/, "");
  40256. return {
  40257. postcssPlugin: "vue-sfc-scoped",
  40258. Rule(rule) {
  40259. processRule(id, rule);
  40260. },
  40261. AtRule(node) {
  40262. if (keyframesRE.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  40263. keyframes[node.params] = node.params = node.params + "-" + shortId;
  40264. }
  40265. },
  40266. OnceExit(root) {
  40267. if (Object.keys(keyframes).length) {
  40268. root.walkDecls((decl) => {
  40269. if (animationNameRE.test(decl.prop)) {
  40270. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  40271. }
  40272. if (animationRE.test(decl.prop)) {
  40273. decl.value = decl.value.split(",").map((v) => {
  40274. const vals = v.trim().split(/\s+/);
  40275. const i = vals.findIndex((val) => keyframes[val]);
  40276. if (i !== -1) {
  40277. vals.splice(i, 1, keyframes[vals[i]]);
  40278. return vals.join(" ");
  40279. } else {
  40280. return v;
  40281. }
  40282. }).join(",");
  40283. }
  40284. });
  40285. }
  40286. }
  40287. };
  40288. };
  40289. const processedRules = /* @__PURE__ */ new WeakSet();
  40290. function processRule(id, rule) {
  40291. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && keyframesRE.test(rule.parent.name)) {
  40292. return;
  40293. }
  40294. processedRules.add(rule);
  40295. let deep = false;
  40296. let parent = rule.parent;
  40297. while (parent && parent.type !== "root") {
  40298. if (parent.__deep) {
  40299. deep = true;
  40300. break;
  40301. }
  40302. parent = parent.parent;
  40303. }
  40304. rule.selector = selectorParser((selectorRoot) => {
  40305. selectorRoot.each((selector) => {
  40306. rewriteSelector(id, rule, selector, selectorRoot, deep);
  40307. });
  40308. }).processSync(rule.selector);
  40309. }
  40310. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  40311. let node = null;
  40312. let shouldInject = !deep;
  40313. let hasNestedDeep = false;
  40314. let splitForNestedDeep = false;
  40315. selector.each((n) => {
  40316. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  40317. n.value = " ";
  40318. n.spaces.before = n.spaces.after = "";
  40319. warn(
  40320. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  40321. );
  40322. return false;
  40323. }
  40324. if (n.type === "pseudo") {
  40325. const { value } = n;
  40326. if (isDeepContainerPseudo(n)) {
  40327. const hasDeepSelectors = n.nodes.some(
  40328. (selector2) => selector2.some(isDeepSelector)
  40329. );
  40330. if (hasDeepSelectors) {
  40331. const hasScopeAnchor = !!node;
  40332. const hasMixedSelectors = n.nodes.some(
  40333. (selector2) => !selector2.some(isDeepSelector)
  40334. );
  40335. const hasTrailingNodes = selector.index(n) < selector.length - 1;
  40336. if (canSplitDeepContainerPseudo(n) && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  40337. splitSelectorForNestedDeep(
  40338. id,
  40339. rule,
  40340. selector,
  40341. selectorRoot,
  40342. n,
  40343. deep,
  40344. slotted
  40345. );
  40346. splitForNestedDeep = true;
  40347. return false;
  40348. }
  40349. if (value === ":not" && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  40350. return;
  40351. }
  40352. n.nodes.forEach(
  40353. (selector2) => rewriteSelector(
  40354. id,
  40355. rule,
  40356. selector2,
  40357. selectorRoot,
  40358. deep || hasScopeAnchor,
  40359. slotted
  40360. )
  40361. );
  40362. if (!hasScopeAnchor) {
  40363. node = n;
  40364. shouldInject = false;
  40365. }
  40366. hasNestedDeep = true;
  40367. }
  40368. }
  40369. if (value === ":deep" || value === "::v-deep") {
  40370. rule.__deep = true;
  40371. if (n.nodes.length) {
  40372. let last = n;
  40373. n.nodes[0].each((ss) => {
  40374. selector.insertAfter(last, ss);
  40375. last = ss;
  40376. });
  40377. const prev = selector.at(selector.index(n) - 1);
  40378. if (!prev || !isSpaceCombinator(prev)) {
  40379. selector.insertAfter(
  40380. n,
  40381. selectorParser.combinator({
  40382. value: " "
  40383. })
  40384. );
  40385. }
  40386. selector.removeChild(n);
  40387. } else {
  40388. warn(
  40389. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  40390. );
  40391. const prev = selector.at(selector.index(n) - 1);
  40392. if (prev && isSpaceCombinator(prev)) {
  40393. selector.removeChild(prev);
  40394. }
  40395. selector.removeChild(n);
  40396. }
  40397. return false;
  40398. }
  40399. if (value === ":slotted" || value === "::v-slotted") {
  40400. rewriteSelector(
  40401. id,
  40402. rule,
  40403. n.nodes[0],
  40404. selectorRoot,
  40405. deep,
  40406. true
  40407. );
  40408. let last = n;
  40409. n.nodes[0].each((ss) => {
  40410. selector.insertAfter(last, ss);
  40411. last = ss;
  40412. });
  40413. selector.removeChild(n);
  40414. shouldInject = false;
  40415. return false;
  40416. }
  40417. if (value === ":global" || value === "::v-global") {
  40418. selector.replaceWith(n.nodes[0]);
  40419. return false;
  40420. }
  40421. }
  40422. if (n.type === "universal") {
  40423. const prev = selector.at(selector.index(n) - 1);
  40424. const next = selector.at(selector.index(n) + 1);
  40425. if (!prev) {
  40426. if (next) {
  40427. if (next.type === "combinator" && next.value === " ") {
  40428. selector.removeChild(next);
  40429. }
  40430. selector.removeChild(n);
  40431. return;
  40432. } else {
  40433. node = selectorParser.combinator({
  40434. value: ""
  40435. });
  40436. selector.insertBefore(n, node);
  40437. selector.removeChild(n);
  40438. return false;
  40439. }
  40440. }
  40441. if (node) return;
  40442. }
  40443. if (!hasNestedDeep && (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node)) {
  40444. node = n;
  40445. }
  40446. });
  40447. if (splitForNestedDeep) {
  40448. return;
  40449. }
  40450. if (rule.nodes.some((node2) => node2.type === "rule")) {
  40451. const deep2 = rule.__deep;
  40452. if (!deep2) {
  40453. extractAndWrapNodes(rule);
  40454. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  40455. for (const atnode of atruleNodes) {
  40456. extractAndWrapNodes(atnode);
  40457. }
  40458. }
  40459. shouldInject = deep2;
  40460. }
  40461. if (node && !hasNestedDeep) {
  40462. const { type, value } = node;
  40463. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  40464. node.nodes.forEach(
  40465. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  40466. );
  40467. shouldInject = false;
  40468. }
  40469. }
  40470. if (node) {
  40471. node.spaces.after = "";
  40472. } else {
  40473. selector.first.spaces.before = "";
  40474. }
  40475. if (shouldInject) {
  40476. const idToAdd = slotted ? id + "-s" : id;
  40477. selector.insertAfter(
  40478. // If node is null it means we need to inject [id] at the start
  40479. // insertAfter can handle `null` here
  40480. node,
  40481. selectorParser.attribute({
  40482. attribute: idToAdd,
  40483. value: idToAdd,
  40484. raws: {},
  40485. quoteMark: `"`
  40486. })
  40487. );
  40488. }
  40489. }
  40490. function isSpaceCombinator(node) {
  40491. return node.type === "combinator" && /^\s+$/.test(node.value);
  40492. }
  40493. function isDeepSelector(node) {
  40494. var _a;
  40495. if (node.type === "pseudo" && (node.value === ":deep" || node.value === "::v-deep")) {
  40496. return true;
  40497. }
  40498. return !!((_a = node.nodes) == null ? void 0 : _a.some((child) => isDeepSelector(child)));
  40499. }
  40500. function isDeepContainerPseudo(node) {
  40501. return node.type === "pseudo" && (node.value === ":is" || node.value === ":where" || node.value === ":has" || node.value === ":not");
  40502. }
  40503. function canSplitDeepContainerPseudo(node) {
  40504. return node.value === ":is" || node.value === ":where" || node.value === ":has";
  40505. }
  40506. function splitSelectorForNestedDeep(id, rule, selector, selectorRoot, pseudo, deep, slotted) {
  40507. const pseudoIndex = selector.index(pseudo);
  40508. const selectors = pseudo.nodes.map((branch, index) => {
  40509. const branchSelector = selector.clone();
  40510. if (branchSelector.first) {
  40511. branchSelector.first.spaces.before = index === 0 ? selector.first.spaces.before : " ";
  40512. }
  40513. const branchPseudo = branchSelector.at(pseudoIndex);
  40514. const branchClone = branch.clone();
  40515. if (branchClone.first) {
  40516. branchClone.first.spaces.before = "";
  40517. }
  40518. branchPseudo.removeAll();
  40519. branchPseudo.append(branchClone);
  40520. rewriteSelector(id, rule, branchSelector, selectorRoot, deep, slotted);
  40521. return branchSelector;
  40522. });
  40523. selector.replaceWith(...selectors);
  40524. }
  40525. function extractAndWrapNodes(parentNode) {
  40526. if (!parentNode.nodes) return;
  40527. const nodes = parentNode.nodes.filter(
  40528. (node) => node.type === "decl" || node.type === "comment"
  40529. );
  40530. if (nodes.length) {
  40531. for (const node of nodes) {
  40532. parentNode.removeChild(node);
  40533. }
  40534. const wrappedRule = new Rule({
  40535. nodes,
  40536. selector: "&"
  40537. });
  40538. parentNode.prepend(wrappedRule);
  40539. }
  40540. }
  40541. scopedPlugin.postcss = true;
  40542. var sourceMap = {};
  40543. var sourceMapGenerator = {};
  40544. var base64Vlq = {};
  40545. var base64 = {};
  40546. /* -*- Mode: js; js-indent-level: 2; -*- */
  40547. var hasRequiredBase64;
  40548. function requireBase64 () {
  40549. if (hasRequiredBase64) return base64;
  40550. hasRequiredBase64 = 1;
  40551. /*
  40552. * Copyright 2011 Mozilla Foundation and contributors
  40553. * Licensed under the New BSD license. See LICENSE or:
  40554. * http://opensource.org/licenses/BSD-3-Clause
  40555. */
  40556. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  40557. /**
  40558. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  40559. */
  40560. base64.encode = function (number) {
  40561. if (0 <= number && number < intToCharMap.length) {
  40562. return intToCharMap[number];
  40563. }
  40564. throw new TypeError("Must be between 0 and 63: " + number);
  40565. };
  40566. /**
  40567. * Decode a single base 64 character code digit to an integer. Returns -1 on
  40568. * failure.
  40569. */
  40570. base64.decode = function (charCode) {
  40571. var bigA = 65; // 'A'
  40572. var bigZ = 90; // 'Z'
  40573. var littleA = 97; // 'a'
  40574. var littleZ = 122; // 'z'
  40575. var zero = 48; // '0'
  40576. var nine = 57; // '9'
  40577. var plus = 43; // '+'
  40578. var slash = 47; // '/'
  40579. var littleOffset = 26;
  40580. var numberOffset = 52;
  40581. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  40582. if (bigA <= charCode && charCode <= bigZ) {
  40583. return (charCode - bigA);
  40584. }
  40585. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  40586. if (littleA <= charCode && charCode <= littleZ) {
  40587. return (charCode - littleA + littleOffset);
  40588. }
  40589. // 52 - 61: 0123456789
  40590. if (zero <= charCode && charCode <= nine) {
  40591. return (charCode - zero + numberOffset);
  40592. }
  40593. // 62: +
  40594. if (charCode == plus) {
  40595. return 62;
  40596. }
  40597. // 63: /
  40598. if (charCode == slash) {
  40599. return 63;
  40600. }
  40601. // Invalid base64 digit.
  40602. return -1;
  40603. };
  40604. return base64;
  40605. }
  40606. /* -*- Mode: js; js-indent-level: 2; -*- */
  40607. var hasRequiredBase64Vlq;
  40608. function requireBase64Vlq () {
  40609. if (hasRequiredBase64Vlq) return base64Vlq;
  40610. hasRequiredBase64Vlq = 1;
  40611. /*
  40612. * Copyright 2011 Mozilla Foundation and contributors
  40613. * Licensed under the New BSD license. See LICENSE or:
  40614. * http://opensource.org/licenses/BSD-3-Clause
  40615. *
  40616. * Based on the Base 64 VLQ implementation in Closure Compiler:
  40617. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  40618. *
  40619. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  40620. * Redistribution and use in source and binary forms, with or without
  40621. * modification, are permitted provided that the following conditions are
  40622. * met:
  40623. *
  40624. * * Redistributions of source code must retain the above copyright
  40625. * notice, this list of conditions and the following disclaimer.
  40626. * * Redistributions in binary form must reproduce the above
  40627. * copyright notice, this list of conditions and the following
  40628. * disclaimer in the documentation and/or other materials provided
  40629. * with the distribution.
  40630. * * Neither the name of Google Inc. nor the names of its
  40631. * contributors may be used to endorse or promote products derived
  40632. * from this software without specific prior written permission.
  40633. *
  40634. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  40635. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  40636. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  40637. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  40638. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40639. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  40640. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  40641. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  40642. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  40643. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  40644. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40645. */
  40646. var base64 = /*@__PURE__*/ requireBase64();
  40647. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  40648. // length quantities we use in the source map spec, the first bit is the sign,
  40649. // the next four bits are the actual value, and the 6th bit is the
  40650. // continuation bit. The continuation bit tells us whether there are more
  40651. // digits in this value following this digit.
  40652. //
  40653. // Continuation
  40654. // | Sign
  40655. // | |
  40656. // V V
  40657. // 101011
  40658. var VLQ_BASE_SHIFT = 5;
  40659. // binary: 100000
  40660. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  40661. // binary: 011111
  40662. var VLQ_BASE_MASK = VLQ_BASE - 1;
  40663. // binary: 100000
  40664. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  40665. /**
  40666. * Converts from a two-complement value to a value where the sign bit is
  40667. * placed in the least significant bit. For example, as decimals:
  40668. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  40669. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  40670. */
  40671. function toVLQSigned(aValue) {
  40672. return aValue < 0
  40673. ? ((-aValue) << 1) + 1
  40674. : (aValue << 1) + 0;
  40675. }
  40676. /**
  40677. * Converts to a two-complement value from a value where the sign bit is
  40678. * placed in the least significant bit. For example, as decimals:
  40679. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  40680. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  40681. */
  40682. function fromVLQSigned(aValue) {
  40683. var isNegative = (aValue & 1) === 1;
  40684. var shifted = aValue >> 1;
  40685. return isNegative
  40686. ? -shifted
  40687. : shifted;
  40688. }
  40689. /**
  40690. * Returns the base 64 VLQ encoded value.
  40691. */
  40692. base64Vlq.encode = function base64VLQ_encode(aValue) {
  40693. var encoded = "";
  40694. var digit;
  40695. var vlq = toVLQSigned(aValue);
  40696. do {
  40697. digit = vlq & VLQ_BASE_MASK;
  40698. vlq >>>= VLQ_BASE_SHIFT;
  40699. if (vlq > 0) {
  40700. // There are still more digits in this value, so we must make sure the
  40701. // continuation bit is marked.
  40702. digit |= VLQ_CONTINUATION_BIT;
  40703. }
  40704. encoded += base64.encode(digit);
  40705. } while (vlq > 0);
  40706. return encoded;
  40707. };
  40708. /**
  40709. * Decodes the next base 64 VLQ value from the given string and returns the
  40710. * value and the rest of the string via the out parameter.
  40711. */
  40712. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  40713. var strLen = aStr.length;
  40714. var result = 0;
  40715. var shift = 0;
  40716. var continuation, digit;
  40717. do {
  40718. if (aIndex >= strLen) {
  40719. throw new Error("Expected more digits in base 64 VLQ value.");
  40720. }
  40721. digit = base64.decode(aStr.charCodeAt(aIndex++));
  40722. if (digit === -1) {
  40723. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  40724. }
  40725. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  40726. digit &= VLQ_BASE_MASK;
  40727. result = result + (digit << shift);
  40728. shift += VLQ_BASE_SHIFT;
  40729. } while (continuation);
  40730. aOutParam.value = fromVLQSigned(result);
  40731. aOutParam.rest = aIndex;
  40732. };
  40733. return base64Vlq;
  40734. }
  40735. var util = {};
  40736. /* -*- Mode: js; js-indent-level: 2; -*- */
  40737. var hasRequiredUtil;
  40738. function requireUtil () {
  40739. if (hasRequiredUtil) return util;
  40740. hasRequiredUtil = 1;
  40741. (function (exports) {
  40742. /*
  40743. * Copyright 2011 Mozilla Foundation and contributors
  40744. * Licensed under the New BSD license. See LICENSE or:
  40745. * http://opensource.org/licenses/BSD-3-Clause
  40746. */
  40747. /**
  40748. * This is a helper function for getting values from parameter/options
  40749. * objects.
  40750. *
  40751. * @param args The object we are extracting values from
  40752. * @param name The name of the property we are getting.
  40753. * @param defaultValue An optional value to return if the property is missing
  40754. * from the object. If this is not specified and the property is missing, an
  40755. * error will be thrown.
  40756. */
  40757. function getArg(aArgs, aName, aDefaultValue) {
  40758. if (aName in aArgs) {
  40759. return aArgs[aName];
  40760. } else if (arguments.length === 3) {
  40761. return aDefaultValue;
  40762. } else {
  40763. throw new Error('"' + aName + '" is a required argument.');
  40764. }
  40765. }
  40766. exports.getArg = getArg;
  40767. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  40768. var dataUrlRegexp = /^data:.+\,.+$/;
  40769. function urlParse(aUrl) {
  40770. var match = aUrl.match(urlRegexp);
  40771. if (!match) {
  40772. return null;
  40773. }
  40774. return {
  40775. scheme: match[1],
  40776. auth: match[2],
  40777. host: match[3],
  40778. port: match[4],
  40779. path: match[5]
  40780. };
  40781. }
  40782. exports.urlParse = urlParse;
  40783. function urlGenerate(aParsedUrl) {
  40784. var url = '';
  40785. if (aParsedUrl.scheme) {
  40786. url += aParsedUrl.scheme + ':';
  40787. }
  40788. url += '//';
  40789. if (aParsedUrl.auth) {
  40790. url += aParsedUrl.auth + '@';
  40791. }
  40792. if (aParsedUrl.host) {
  40793. url += aParsedUrl.host;
  40794. }
  40795. if (aParsedUrl.port) {
  40796. url += ":" + aParsedUrl.port;
  40797. }
  40798. if (aParsedUrl.path) {
  40799. url += aParsedUrl.path;
  40800. }
  40801. return url;
  40802. }
  40803. exports.urlGenerate = urlGenerate;
  40804. /**
  40805. * Normalizes a path, or the path portion of a URL:
  40806. *
  40807. * - Replaces consecutive slashes with one slash.
  40808. * - Removes unnecessary '.' parts.
  40809. * - Removes unnecessary '<dir>/..' parts.
  40810. *
  40811. * Based on code in the Node.js 'path' core module.
  40812. *
  40813. * @param aPath The path or url to normalize.
  40814. */
  40815. function normalize(aPath) {
  40816. var path = aPath;
  40817. var url = urlParse(aPath);
  40818. if (url) {
  40819. if (!url.path) {
  40820. return aPath;
  40821. }
  40822. path = url.path;
  40823. }
  40824. var isAbsolute = exports.isAbsolute(path);
  40825. var parts = path.split(/\/+/);
  40826. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  40827. part = parts[i];
  40828. if (part === '.') {
  40829. parts.splice(i, 1);
  40830. } else if (part === '..') {
  40831. up++;
  40832. } else if (up > 0) {
  40833. if (part === '') {
  40834. // The first part is blank if the path is absolute. Trying to go
  40835. // above the root is a no-op. Therefore we can remove all '..' parts
  40836. // directly after the root.
  40837. parts.splice(i + 1, up);
  40838. up = 0;
  40839. } else {
  40840. parts.splice(i, 2);
  40841. up--;
  40842. }
  40843. }
  40844. }
  40845. path = parts.join('/');
  40846. if (path === '') {
  40847. path = isAbsolute ? '/' : '.';
  40848. }
  40849. if (url) {
  40850. url.path = path;
  40851. return urlGenerate(url);
  40852. }
  40853. return path;
  40854. }
  40855. exports.normalize = normalize;
  40856. /**
  40857. * Joins two paths/URLs.
  40858. *
  40859. * @param aRoot The root path or URL.
  40860. * @param aPath The path or URL to be joined with the root.
  40861. *
  40862. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  40863. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  40864. * first.
  40865. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  40866. * is updated with the result and aRoot is returned. Otherwise the result
  40867. * is returned.
  40868. * - If aPath is absolute, the result is aPath.
  40869. * - Otherwise the two paths are joined with a slash.
  40870. * - Joining for example 'http://' and 'www.example.com' is also supported.
  40871. */
  40872. function join(aRoot, aPath) {
  40873. if (aRoot === "") {
  40874. aRoot = ".";
  40875. }
  40876. if (aPath === "") {
  40877. aPath = ".";
  40878. }
  40879. var aPathUrl = urlParse(aPath);
  40880. var aRootUrl = urlParse(aRoot);
  40881. if (aRootUrl) {
  40882. aRoot = aRootUrl.path || '/';
  40883. }
  40884. // `join(foo, '//www.example.org')`
  40885. if (aPathUrl && !aPathUrl.scheme) {
  40886. if (aRootUrl) {
  40887. aPathUrl.scheme = aRootUrl.scheme;
  40888. }
  40889. return urlGenerate(aPathUrl);
  40890. }
  40891. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  40892. return aPath;
  40893. }
  40894. // `join('http://', 'www.example.com')`
  40895. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  40896. aRootUrl.host = aPath;
  40897. return urlGenerate(aRootUrl);
  40898. }
  40899. var joined = aPath.charAt(0) === '/'
  40900. ? aPath
  40901. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  40902. if (aRootUrl) {
  40903. aRootUrl.path = joined;
  40904. return urlGenerate(aRootUrl);
  40905. }
  40906. return joined;
  40907. }
  40908. exports.join = join;
  40909. exports.isAbsolute = function (aPath) {
  40910. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  40911. };
  40912. /**
  40913. * Make a path relative to a URL or another path.
  40914. *
  40915. * @param aRoot The root path or URL.
  40916. * @param aPath The path or URL to be made relative to aRoot.
  40917. */
  40918. function relative(aRoot, aPath) {
  40919. if (aRoot === "") {
  40920. aRoot = ".";
  40921. }
  40922. aRoot = aRoot.replace(/\/$/, '');
  40923. // It is possible for the path to be above the root. In this case, simply
  40924. // checking whether the root is a prefix of the path won't work. Instead, we
  40925. // need to remove components from the root one by one, until either we find
  40926. // a prefix that fits, or we run out of components to remove.
  40927. var level = 0;
  40928. while (aPath.indexOf(aRoot + '/') !== 0) {
  40929. var index = aRoot.lastIndexOf("/");
  40930. if (index < 0) {
  40931. return aPath;
  40932. }
  40933. // If the only part of the root that is left is the scheme (i.e. http://,
  40934. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  40935. // have exhausted all components, so the path is not relative to the root.
  40936. aRoot = aRoot.slice(0, index);
  40937. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  40938. return aPath;
  40939. }
  40940. ++level;
  40941. }
  40942. // Make sure we add a "../" for each component we removed from the root.
  40943. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  40944. }
  40945. exports.relative = relative;
  40946. var supportsNullProto = (function () {
  40947. var obj = Object.create(null);
  40948. return !('__proto__' in obj);
  40949. }());
  40950. function identity (s) {
  40951. return s;
  40952. }
  40953. /**
  40954. * Because behavior goes wacky when you set `__proto__` on objects, we
  40955. * have to prefix all the strings in our set with an arbitrary character.
  40956. *
  40957. * See https://github.com/mozilla/source-map/pull/31 and
  40958. * https://github.com/mozilla/source-map/issues/30
  40959. *
  40960. * @param String aStr
  40961. */
  40962. function toSetString(aStr) {
  40963. if (isProtoString(aStr)) {
  40964. return '$' + aStr;
  40965. }
  40966. return aStr;
  40967. }
  40968. exports.toSetString = supportsNullProto ? identity : toSetString;
  40969. function fromSetString(aStr) {
  40970. if (isProtoString(aStr)) {
  40971. return aStr.slice(1);
  40972. }
  40973. return aStr;
  40974. }
  40975. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  40976. function isProtoString(s) {
  40977. if (!s) {
  40978. return false;
  40979. }
  40980. var length = s.length;
  40981. if (length < 9 /* "__proto__".length */) {
  40982. return false;
  40983. }
  40984. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  40985. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  40986. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  40987. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  40988. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  40989. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  40990. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  40991. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  40992. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  40993. return false;
  40994. }
  40995. for (var i = length - 10; i >= 0; i--) {
  40996. if (s.charCodeAt(i) !== 36 /* '$' */) {
  40997. return false;
  40998. }
  40999. }
  41000. return true;
  41001. }
  41002. /**
  41003. * Comparator between two mappings where the original positions are compared.
  41004. *
  41005. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  41006. * mappings with the same original source/line/column, but different generated
  41007. * line and column the same. Useful when searching for a mapping with a
  41008. * stubbed out mapping.
  41009. */
  41010. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  41011. var cmp = strcmp(mappingA.source, mappingB.source);
  41012. if (cmp !== 0) {
  41013. return cmp;
  41014. }
  41015. cmp = mappingA.originalLine - mappingB.originalLine;
  41016. if (cmp !== 0) {
  41017. return cmp;
  41018. }
  41019. cmp = mappingA.originalColumn - mappingB.originalColumn;
  41020. if (cmp !== 0 || onlyCompareOriginal) {
  41021. return cmp;
  41022. }
  41023. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  41024. if (cmp !== 0) {
  41025. return cmp;
  41026. }
  41027. cmp = mappingA.generatedLine - mappingB.generatedLine;
  41028. if (cmp !== 0) {
  41029. return cmp;
  41030. }
  41031. return strcmp(mappingA.name, mappingB.name);
  41032. }
  41033. exports.compareByOriginalPositions = compareByOriginalPositions;
  41034. /**
  41035. * Comparator between two mappings with deflated source and name indices where
  41036. * the generated positions are compared.
  41037. *
  41038. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  41039. * mappings with the same generated line and column, but different
  41040. * source/name/original line and column the same. Useful when searching for a
  41041. * mapping with a stubbed out mapping.
  41042. */
  41043. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  41044. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  41045. if (cmp !== 0) {
  41046. return cmp;
  41047. }
  41048. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  41049. if (cmp !== 0 || onlyCompareGenerated) {
  41050. return cmp;
  41051. }
  41052. cmp = strcmp(mappingA.source, mappingB.source);
  41053. if (cmp !== 0) {
  41054. return cmp;
  41055. }
  41056. cmp = mappingA.originalLine - mappingB.originalLine;
  41057. if (cmp !== 0) {
  41058. return cmp;
  41059. }
  41060. cmp = mappingA.originalColumn - mappingB.originalColumn;
  41061. if (cmp !== 0) {
  41062. return cmp;
  41063. }
  41064. return strcmp(mappingA.name, mappingB.name);
  41065. }
  41066. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  41067. function strcmp(aStr1, aStr2) {
  41068. if (aStr1 === aStr2) {
  41069. return 0;
  41070. }
  41071. if (aStr1 === null) {
  41072. return 1; // aStr2 !== null
  41073. }
  41074. if (aStr2 === null) {
  41075. return -1; // aStr1 !== null
  41076. }
  41077. if (aStr1 > aStr2) {
  41078. return 1;
  41079. }
  41080. return -1;
  41081. }
  41082. /**
  41083. * Comparator between two mappings with inflated source and name strings where
  41084. * the generated positions are compared.
  41085. */
  41086. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  41087. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  41088. if (cmp !== 0) {
  41089. return cmp;
  41090. }
  41091. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  41092. if (cmp !== 0) {
  41093. return cmp;
  41094. }
  41095. cmp = strcmp(mappingA.source, mappingB.source);
  41096. if (cmp !== 0) {
  41097. return cmp;
  41098. }
  41099. cmp = mappingA.originalLine - mappingB.originalLine;
  41100. if (cmp !== 0) {
  41101. return cmp;
  41102. }
  41103. cmp = mappingA.originalColumn - mappingB.originalColumn;
  41104. if (cmp !== 0) {
  41105. return cmp;
  41106. }
  41107. return strcmp(mappingA.name, mappingB.name);
  41108. }
  41109. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  41110. /**
  41111. * Strip any JSON XSSI avoidance prefix from the string (as documented
  41112. * in the source maps specification), and then parse the string as
  41113. * JSON.
  41114. */
  41115. function parseSourceMapInput(str) {
  41116. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  41117. }
  41118. exports.parseSourceMapInput = parseSourceMapInput;
  41119. /**
  41120. * Compute the URL of a source given the the source root, the source's
  41121. * URL, and the source map's URL.
  41122. */
  41123. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  41124. sourceURL = sourceURL || '';
  41125. if (sourceRoot) {
  41126. // This follows what Chrome does.
  41127. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  41128. sourceRoot += '/';
  41129. }
  41130. // The spec says:
  41131. // Line 4: An optional source root, useful for relocating source
  41132. // files on a server or removing repeated values in the
  41133. // “sources” entry. This value is prepended to the individual
  41134. // entries in the “source” field.
  41135. sourceURL = sourceRoot + sourceURL;
  41136. }
  41137. // Historically, SourceMapConsumer did not take the sourceMapURL as
  41138. // a parameter. This mode is still somewhat supported, which is why
  41139. // this code block is conditional. However, it's preferable to pass
  41140. // the source map URL to SourceMapConsumer, so that this function
  41141. // can implement the source URL resolution algorithm as outlined in
  41142. // the spec. This block is basically the equivalent of:
  41143. // new URL(sourceURL, sourceMapURL).toString()
  41144. // ... except it avoids using URL, which wasn't available in the
  41145. // older releases of node still supported by this library.
  41146. //
  41147. // The spec says:
  41148. // If the sources are not absolute URLs after prepending of the
  41149. // “sourceRoot”, the sources are resolved relative to the
  41150. // SourceMap (like resolving script src in a html document).
  41151. if (sourceMapURL) {
  41152. var parsed = urlParse(sourceMapURL);
  41153. if (!parsed) {
  41154. throw new Error("sourceMapURL could not be parsed");
  41155. }
  41156. if (parsed.path) {
  41157. // Strip the last path component, but keep the "/".
  41158. var index = parsed.path.lastIndexOf('/');
  41159. if (index >= 0) {
  41160. parsed.path = parsed.path.substring(0, index + 1);
  41161. }
  41162. }
  41163. sourceURL = join(urlGenerate(parsed), sourceURL);
  41164. }
  41165. return normalize(sourceURL);
  41166. }
  41167. exports.computeSourceURL = computeSourceURL;
  41168. } (util));
  41169. return util;
  41170. }
  41171. var arraySet = {};
  41172. /* -*- Mode: js; js-indent-level: 2; -*- */
  41173. var hasRequiredArraySet;
  41174. function requireArraySet () {
  41175. if (hasRequiredArraySet) return arraySet;
  41176. hasRequiredArraySet = 1;
  41177. /*
  41178. * Copyright 2011 Mozilla Foundation and contributors
  41179. * Licensed under the New BSD license. See LICENSE or:
  41180. * http://opensource.org/licenses/BSD-3-Clause
  41181. */
  41182. var util = /*@__PURE__*/ requireUtil();
  41183. var has = Object.prototype.hasOwnProperty;
  41184. var hasNativeMap = typeof Map !== "undefined";
  41185. /**
  41186. * A data structure which is a combination of an array and a set. Adding a new
  41187. * member is O(1), testing for membership is O(1), and finding the index of an
  41188. * element is O(1). Removing elements from the set is not supported. Only
  41189. * strings are supported for membership.
  41190. */
  41191. function ArraySet() {
  41192. this._array = [];
  41193. this._set = hasNativeMap ? new Map() : Object.create(null);
  41194. }
  41195. /**
  41196. * Static method for creating ArraySet instances from an existing array.
  41197. */
  41198. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  41199. var set = new ArraySet();
  41200. for (var i = 0, len = aArray.length; i < len; i++) {
  41201. set.add(aArray[i], aAllowDuplicates);
  41202. }
  41203. return set;
  41204. };
  41205. /**
  41206. * Return how many unique items are in this ArraySet. If duplicates have been
  41207. * added, than those do not count towards the size.
  41208. *
  41209. * @returns Number
  41210. */
  41211. ArraySet.prototype.size = function ArraySet_size() {
  41212. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  41213. };
  41214. /**
  41215. * Add the given string to this set.
  41216. *
  41217. * @param String aStr
  41218. */
  41219. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  41220. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  41221. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  41222. var idx = this._array.length;
  41223. if (!isDuplicate || aAllowDuplicates) {
  41224. this._array.push(aStr);
  41225. }
  41226. if (!isDuplicate) {
  41227. if (hasNativeMap) {
  41228. this._set.set(aStr, idx);
  41229. } else {
  41230. this._set[sStr] = idx;
  41231. }
  41232. }
  41233. };
  41234. /**
  41235. * Is the given string a member of this set?
  41236. *
  41237. * @param String aStr
  41238. */
  41239. ArraySet.prototype.has = function ArraySet_has(aStr) {
  41240. if (hasNativeMap) {
  41241. return this._set.has(aStr);
  41242. } else {
  41243. var sStr = util.toSetString(aStr);
  41244. return has.call(this._set, sStr);
  41245. }
  41246. };
  41247. /**
  41248. * What is the index of the given string in the array?
  41249. *
  41250. * @param String aStr
  41251. */
  41252. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  41253. if (hasNativeMap) {
  41254. var idx = this._set.get(aStr);
  41255. if (idx >= 0) {
  41256. return idx;
  41257. }
  41258. } else {
  41259. var sStr = util.toSetString(aStr);
  41260. if (has.call(this._set, sStr)) {
  41261. return this._set[sStr];
  41262. }
  41263. }
  41264. throw new Error('"' + aStr + '" is not in the set.');
  41265. };
  41266. /**
  41267. * What is the element at the given index?
  41268. *
  41269. * @param Number aIdx
  41270. */
  41271. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  41272. if (aIdx >= 0 && aIdx < this._array.length) {
  41273. return this._array[aIdx];
  41274. }
  41275. throw new Error('No element indexed by ' + aIdx);
  41276. };
  41277. /**
  41278. * Returns the array representation of this set (which has the proper indices
  41279. * indicated by indexOf). Note that this is a copy of the internal array used
  41280. * for storing the members so that no one can mess with internal state.
  41281. */
  41282. ArraySet.prototype.toArray = function ArraySet_toArray() {
  41283. return this._array.slice();
  41284. };
  41285. arraySet.ArraySet = ArraySet;
  41286. return arraySet;
  41287. }
  41288. var mappingList = {};
  41289. /* -*- Mode: js; js-indent-level: 2; -*- */
  41290. var hasRequiredMappingList;
  41291. function requireMappingList () {
  41292. if (hasRequiredMappingList) return mappingList;
  41293. hasRequiredMappingList = 1;
  41294. /*
  41295. * Copyright 2014 Mozilla Foundation and contributors
  41296. * Licensed under the New BSD license. See LICENSE or:
  41297. * http://opensource.org/licenses/BSD-3-Clause
  41298. */
  41299. var util = /*@__PURE__*/ requireUtil();
  41300. /**
  41301. * Determine whether mappingB is after mappingA with respect to generated
  41302. * position.
  41303. */
  41304. function generatedPositionAfter(mappingA, mappingB) {
  41305. // Optimized for most common case
  41306. var lineA = mappingA.generatedLine;
  41307. var lineB = mappingB.generatedLine;
  41308. var columnA = mappingA.generatedColumn;
  41309. var columnB = mappingB.generatedColumn;
  41310. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  41311. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  41312. }
  41313. /**
  41314. * A data structure to provide a sorted view of accumulated mappings in a
  41315. * performance conscious manner. It trades a neglibable overhead in general
  41316. * case for a large speedup in case of mappings being added in order.
  41317. */
  41318. function MappingList() {
  41319. this._array = [];
  41320. this._sorted = true;
  41321. // Serves as infimum
  41322. this._last = {generatedLine: -1, generatedColumn: 0};
  41323. }
  41324. /**
  41325. * Iterate through internal items. This method takes the same arguments that
  41326. * `Array.prototype.forEach` takes.
  41327. *
  41328. * NOTE: The order of the mappings is NOT guaranteed.
  41329. */
  41330. MappingList.prototype.unsortedForEach =
  41331. function MappingList_forEach(aCallback, aThisArg) {
  41332. this._array.forEach(aCallback, aThisArg);
  41333. };
  41334. /**
  41335. * Add the given source mapping.
  41336. *
  41337. * @param Object aMapping
  41338. */
  41339. MappingList.prototype.add = function MappingList_add(aMapping) {
  41340. if (generatedPositionAfter(this._last, aMapping)) {
  41341. this._last = aMapping;
  41342. this._array.push(aMapping);
  41343. } else {
  41344. this._sorted = false;
  41345. this._array.push(aMapping);
  41346. }
  41347. };
  41348. /**
  41349. * Returns the flat, sorted array of mappings. The mappings are sorted by
  41350. * generated position.
  41351. *
  41352. * WARNING: This method returns internal data without copying, for
  41353. * performance. The return value must NOT be mutated, and should be treated as
  41354. * an immutable borrow. If you want to take ownership, you must make your own
  41355. * copy.
  41356. */
  41357. MappingList.prototype.toArray = function MappingList_toArray() {
  41358. if (!this._sorted) {
  41359. this._array.sort(util.compareByGeneratedPositionsInflated);
  41360. this._sorted = true;
  41361. }
  41362. return this._array;
  41363. };
  41364. mappingList.MappingList = MappingList;
  41365. return mappingList;
  41366. }
  41367. /* -*- Mode: js; js-indent-level: 2; -*- */
  41368. var hasRequiredSourceMapGenerator;
  41369. function requireSourceMapGenerator () {
  41370. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  41371. hasRequiredSourceMapGenerator = 1;
  41372. /*
  41373. * Copyright 2011 Mozilla Foundation and contributors
  41374. * Licensed under the New BSD license. See LICENSE or:
  41375. * http://opensource.org/licenses/BSD-3-Clause
  41376. */
  41377. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  41378. var util = /*@__PURE__*/ requireUtil();
  41379. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  41380. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  41381. /**
  41382. * An instance of the SourceMapGenerator represents a source map which is
  41383. * being built incrementally. You may pass an object with the following
  41384. * properties:
  41385. *
  41386. * - file: The filename of the generated source.
  41387. * - sourceRoot: A root for all relative URLs in this source map.
  41388. */
  41389. function SourceMapGenerator(aArgs) {
  41390. if (!aArgs) {
  41391. aArgs = {};
  41392. }
  41393. this._file = util.getArg(aArgs, 'file', null);
  41394. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  41395. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  41396. this._sources = new ArraySet();
  41397. this._names = new ArraySet();
  41398. this._mappings = new MappingList();
  41399. this._sourcesContents = null;
  41400. }
  41401. SourceMapGenerator.prototype._version = 3;
  41402. /**
  41403. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  41404. *
  41405. * @param aSourceMapConsumer The SourceMap.
  41406. */
  41407. SourceMapGenerator.fromSourceMap =
  41408. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  41409. var sourceRoot = aSourceMapConsumer.sourceRoot;
  41410. var generator = new SourceMapGenerator({
  41411. file: aSourceMapConsumer.file,
  41412. sourceRoot: sourceRoot
  41413. });
  41414. aSourceMapConsumer.eachMapping(function (mapping) {
  41415. var newMapping = {
  41416. generated: {
  41417. line: mapping.generatedLine,
  41418. column: mapping.generatedColumn
  41419. }
  41420. };
  41421. if (mapping.source != null) {
  41422. newMapping.source = mapping.source;
  41423. if (sourceRoot != null) {
  41424. newMapping.source = util.relative(sourceRoot, newMapping.source);
  41425. }
  41426. newMapping.original = {
  41427. line: mapping.originalLine,
  41428. column: mapping.originalColumn
  41429. };
  41430. if (mapping.name != null) {
  41431. newMapping.name = mapping.name;
  41432. }
  41433. }
  41434. generator.addMapping(newMapping);
  41435. });
  41436. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  41437. var sourceRelative = sourceFile;
  41438. if (sourceRoot !== null) {
  41439. sourceRelative = util.relative(sourceRoot, sourceFile);
  41440. }
  41441. if (!generator._sources.has(sourceRelative)) {
  41442. generator._sources.add(sourceRelative);
  41443. }
  41444. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  41445. if (content != null) {
  41446. generator.setSourceContent(sourceFile, content);
  41447. }
  41448. });
  41449. return generator;
  41450. };
  41451. /**
  41452. * Add a single mapping from original source line and column to the generated
  41453. * source's line and column for this source map being created. The mapping
  41454. * object should have the following properties:
  41455. *
  41456. * - generated: An object with the generated line and column positions.
  41457. * - original: An object with the original line and column positions.
  41458. * - source: The original source file (relative to the sourceRoot).
  41459. * - name: An optional original token name for this mapping.
  41460. */
  41461. SourceMapGenerator.prototype.addMapping =
  41462. function SourceMapGenerator_addMapping(aArgs) {
  41463. var generated = util.getArg(aArgs, 'generated');
  41464. var original = util.getArg(aArgs, 'original', null);
  41465. var source = util.getArg(aArgs, 'source', null);
  41466. var name = util.getArg(aArgs, 'name', null);
  41467. if (!this._skipValidation) {
  41468. this._validateMapping(generated, original, source, name);
  41469. }
  41470. if (source != null) {
  41471. source = String(source);
  41472. if (!this._sources.has(source)) {
  41473. this._sources.add(source);
  41474. }
  41475. }
  41476. if (name != null) {
  41477. name = String(name);
  41478. if (!this._names.has(name)) {
  41479. this._names.add(name);
  41480. }
  41481. }
  41482. this._mappings.add({
  41483. generatedLine: generated.line,
  41484. generatedColumn: generated.column,
  41485. originalLine: original != null && original.line,
  41486. originalColumn: original != null && original.column,
  41487. source: source,
  41488. name: name
  41489. });
  41490. };
  41491. /**
  41492. * Set the source content for a source file.
  41493. */
  41494. SourceMapGenerator.prototype.setSourceContent =
  41495. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  41496. var source = aSourceFile;
  41497. if (this._sourceRoot != null) {
  41498. source = util.relative(this._sourceRoot, source);
  41499. }
  41500. if (aSourceContent != null) {
  41501. // Add the source content to the _sourcesContents map.
  41502. // Create a new _sourcesContents map if the property is null.
  41503. if (!this._sourcesContents) {
  41504. this._sourcesContents = Object.create(null);
  41505. }
  41506. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  41507. } else if (this._sourcesContents) {
  41508. // Remove the source file from the _sourcesContents map.
  41509. // If the _sourcesContents map is empty, set the property to null.
  41510. delete this._sourcesContents[util.toSetString(source)];
  41511. if (Object.keys(this._sourcesContents).length === 0) {
  41512. this._sourcesContents = null;
  41513. }
  41514. }
  41515. };
  41516. /**
  41517. * Applies the mappings of a sub-source-map for a specific source file to the
  41518. * source map being generated. Each mapping to the supplied source file is
  41519. * rewritten using the supplied source map. Note: The resolution for the
  41520. * resulting mappings is the minimium of this map and the supplied map.
  41521. *
  41522. * @param aSourceMapConsumer The source map to be applied.
  41523. * @param aSourceFile Optional. The filename of the source file.
  41524. * If omitted, SourceMapConsumer's file property will be used.
  41525. * @param aSourceMapPath Optional. The dirname of the path to the source map
  41526. * to be applied. If relative, it is relative to the SourceMapConsumer.
  41527. * This parameter is needed when the two source maps aren't in the same
  41528. * directory, and the source map to be applied contains relative source
  41529. * paths. If so, those relative source paths need to be rewritten
  41530. * relative to the SourceMapGenerator.
  41531. */
  41532. SourceMapGenerator.prototype.applySourceMap =
  41533. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  41534. var sourceFile = aSourceFile;
  41535. // If aSourceFile is omitted, we will use the file property of the SourceMap
  41536. if (aSourceFile == null) {
  41537. if (aSourceMapConsumer.file == null) {
  41538. throw new Error(
  41539. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  41540. 'or the source map\'s "file" property. Both were omitted.'
  41541. );
  41542. }
  41543. sourceFile = aSourceMapConsumer.file;
  41544. }
  41545. var sourceRoot = this._sourceRoot;
  41546. // Make "sourceFile" relative if an absolute Url is passed.
  41547. if (sourceRoot != null) {
  41548. sourceFile = util.relative(sourceRoot, sourceFile);
  41549. }
  41550. // Applying the SourceMap can add and remove items from the sources and
  41551. // the names array.
  41552. var newSources = new ArraySet();
  41553. var newNames = new ArraySet();
  41554. // Find mappings for the "sourceFile"
  41555. this._mappings.unsortedForEach(function (mapping) {
  41556. if (mapping.source === sourceFile && mapping.originalLine != null) {
  41557. // Check if it can be mapped by the source map, then update the mapping.
  41558. var original = aSourceMapConsumer.originalPositionFor({
  41559. line: mapping.originalLine,
  41560. column: mapping.originalColumn
  41561. });
  41562. if (original.source != null) {
  41563. // Copy mapping
  41564. mapping.source = original.source;
  41565. if (aSourceMapPath != null) {
  41566. mapping.source = util.join(aSourceMapPath, mapping.source);
  41567. }
  41568. if (sourceRoot != null) {
  41569. mapping.source = util.relative(sourceRoot, mapping.source);
  41570. }
  41571. mapping.originalLine = original.line;
  41572. mapping.originalColumn = original.column;
  41573. if (original.name != null) {
  41574. mapping.name = original.name;
  41575. }
  41576. }
  41577. }
  41578. var source = mapping.source;
  41579. if (source != null && !newSources.has(source)) {
  41580. newSources.add(source);
  41581. }
  41582. var name = mapping.name;
  41583. if (name != null && !newNames.has(name)) {
  41584. newNames.add(name);
  41585. }
  41586. }, this);
  41587. this._sources = newSources;
  41588. this._names = newNames;
  41589. // Copy sourcesContents of applied map.
  41590. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  41591. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  41592. if (content != null) {
  41593. if (aSourceMapPath != null) {
  41594. sourceFile = util.join(aSourceMapPath, sourceFile);
  41595. }
  41596. if (sourceRoot != null) {
  41597. sourceFile = util.relative(sourceRoot, sourceFile);
  41598. }
  41599. this.setSourceContent(sourceFile, content);
  41600. }
  41601. }, this);
  41602. };
  41603. /**
  41604. * A mapping can have one of the three levels of data:
  41605. *
  41606. * 1. Just the generated position.
  41607. * 2. The Generated position, original position, and original source.
  41608. * 3. Generated and original position, original source, as well as a name
  41609. * token.
  41610. *
  41611. * To maintain consistency, we validate that any new mapping being added falls
  41612. * in to one of these categories.
  41613. */
  41614. SourceMapGenerator.prototype._validateMapping =
  41615. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  41616. aName) {
  41617. // When aOriginal is truthy but has empty values for .line and .column,
  41618. // it is most likely a programmer error. In this case we throw a very
  41619. // specific error message to try to guide them the right way.
  41620. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  41621. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  41622. throw new Error(
  41623. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  41624. 'the original mapping entirely and only map the generated position. If so, pass ' +
  41625. 'null for the original mapping instead of an object with empty or null values.'
  41626. );
  41627. }
  41628. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  41629. && aGenerated.line > 0 && aGenerated.column >= 0
  41630. && !aOriginal && !aSource && !aName) {
  41631. // Case 1.
  41632. return;
  41633. }
  41634. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  41635. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  41636. && aGenerated.line > 0 && aGenerated.column >= 0
  41637. && aOriginal.line > 0 && aOriginal.column >= 0
  41638. && aSource) {
  41639. // Cases 2 and 3.
  41640. return;
  41641. }
  41642. else {
  41643. throw new Error('Invalid mapping: ' + JSON.stringify({
  41644. generated: aGenerated,
  41645. source: aSource,
  41646. original: aOriginal,
  41647. name: aName
  41648. }));
  41649. }
  41650. };
  41651. /**
  41652. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  41653. * specified by the source map format.
  41654. */
  41655. SourceMapGenerator.prototype._serializeMappings =
  41656. function SourceMapGenerator_serializeMappings() {
  41657. var previousGeneratedColumn = 0;
  41658. var previousGeneratedLine = 1;
  41659. var previousOriginalColumn = 0;
  41660. var previousOriginalLine = 0;
  41661. var previousName = 0;
  41662. var previousSource = 0;
  41663. var result = '';
  41664. var next;
  41665. var mapping;
  41666. var nameIdx;
  41667. var sourceIdx;
  41668. var mappings = this._mappings.toArray();
  41669. for (var i = 0, len = mappings.length; i < len; i++) {
  41670. mapping = mappings[i];
  41671. next = '';
  41672. if (mapping.generatedLine !== previousGeneratedLine) {
  41673. previousGeneratedColumn = 0;
  41674. while (mapping.generatedLine !== previousGeneratedLine) {
  41675. next += ';';
  41676. previousGeneratedLine++;
  41677. }
  41678. }
  41679. else {
  41680. if (i > 0) {
  41681. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  41682. continue;
  41683. }
  41684. next += ',';
  41685. }
  41686. }
  41687. next += base64VLQ.encode(mapping.generatedColumn
  41688. - previousGeneratedColumn);
  41689. previousGeneratedColumn = mapping.generatedColumn;
  41690. if (mapping.source != null) {
  41691. sourceIdx = this._sources.indexOf(mapping.source);
  41692. next += base64VLQ.encode(sourceIdx - previousSource);
  41693. previousSource = sourceIdx;
  41694. // lines are stored 0-based in SourceMap spec version 3
  41695. next += base64VLQ.encode(mapping.originalLine - 1
  41696. - previousOriginalLine);
  41697. previousOriginalLine = mapping.originalLine - 1;
  41698. next += base64VLQ.encode(mapping.originalColumn
  41699. - previousOriginalColumn);
  41700. previousOriginalColumn = mapping.originalColumn;
  41701. if (mapping.name != null) {
  41702. nameIdx = this._names.indexOf(mapping.name);
  41703. next += base64VLQ.encode(nameIdx - previousName);
  41704. previousName = nameIdx;
  41705. }
  41706. }
  41707. result += next;
  41708. }
  41709. return result;
  41710. };
  41711. SourceMapGenerator.prototype._generateSourcesContent =
  41712. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  41713. return aSources.map(function (source) {
  41714. if (!this._sourcesContents) {
  41715. return null;
  41716. }
  41717. if (aSourceRoot != null) {
  41718. source = util.relative(aSourceRoot, source);
  41719. }
  41720. var key = util.toSetString(source);
  41721. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  41722. ? this._sourcesContents[key]
  41723. : null;
  41724. }, this);
  41725. };
  41726. /**
  41727. * Externalize the source map.
  41728. */
  41729. SourceMapGenerator.prototype.toJSON =
  41730. function SourceMapGenerator_toJSON() {
  41731. var map = {
  41732. version: this._version,
  41733. sources: this._sources.toArray(),
  41734. names: this._names.toArray(),
  41735. mappings: this._serializeMappings()
  41736. };
  41737. if (this._file != null) {
  41738. map.file = this._file;
  41739. }
  41740. if (this._sourceRoot != null) {
  41741. map.sourceRoot = this._sourceRoot;
  41742. }
  41743. if (this._sourcesContents) {
  41744. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  41745. }
  41746. return map;
  41747. };
  41748. /**
  41749. * Render the source map being generated to a string.
  41750. */
  41751. SourceMapGenerator.prototype.toString =
  41752. function SourceMapGenerator_toString() {
  41753. return JSON.stringify(this.toJSON());
  41754. };
  41755. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  41756. return sourceMapGenerator;
  41757. }
  41758. var sourceMapConsumer = {};
  41759. var binarySearch = {};
  41760. /* -*- Mode: js; js-indent-level: 2; -*- */
  41761. var hasRequiredBinarySearch;
  41762. function requireBinarySearch () {
  41763. if (hasRequiredBinarySearch) return binarySearch;
  41764. hasRequiredBinarySearch = 1;
  41765. (function (exports) {
  41766. /*
  41767. * Copyright 2011 Mozilla Foundation and contributors
  41768. * Licensed under the New BSD license. See LICENSE or:
  41769. * http://opensource.org/licenses/BSD-3-Clause
  41770. */
  41771. exports.GREATEST_LOWER_BOUND = 1;
  41772. exports.LEAST_UPPER_BOUND = 2;
  41773. /**
  41774. * Recursive implementation of binary search.
  41775. *
  41776. * @param aLow Indices here and lower do not contain the needle.
  41777. * @param aHigh Indices here and higher do not contain the needle.
  41778. * @param aNeedle The element being searched for.
  41779. * @param aHaystack The non-empty array being searched.
  41780. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  41781. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  41782. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  41783. * closest element that is smaller than or greater than the one we are
  41784. * searching for, respectively, if the exact element cannot be found.
  41785. */
  41786. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  41787. // This function terminates when one of the following is true:
  41788. //
  41789. // 1. We find the exact element we are looking for.
  41790. //
  41791. // 2. We did not find the exact element, but we can return the index of
  41792. // the next-closest element.
  41793. //
  41794. // 3. We did not find the exact element, and there is no next-closest
  41795. // element than the one we are searching for, so we return -1.
  41796. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  41797. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  41798. if (cmp === 0) {
  41799. // Found the element we are looking for.
  41800. return mid;
  41801. }
  41802. else if (cmp > 0) {
  41803. // Our needle is greater than aHaystack[mid].
  41804. if (aHigh - mid > 1) {
  41805. // The element is in the upper half.
  41806. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  41807. }
  41808. // The exact needle element was not found in this haystack. Determine if
  41809. // we are in termination case (3) or (2) and return the appropriate thing.
  41810. if (aBias == exports.LEAST_UPPER_BOUND) {
  41811. return aHigh < aHaystack.length ? aHigh : -1;
  41812. } else {
  41813. return mid;
  41814. }
  41815. }
  41816. else {
  41817. // Our needle is less than aHaystack[mid].
  41818. if (mid - aLow > 1) {
  41819. // The element is in the lower half.
  41820. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  41821. }
  41822. // we are in termination case (3) or (2) and return the appropriate thing.
  41823. if (aBias == exports.LEAST_UPPER_BOUND) {
  41824. return mid;
  41825. } else {
  41826. return aLow < 0 ? -1 : aLow;
  41827. }
  41828. }
  41829. }
  41830. /**
  41831. * This is an implementation of binary search which will always try and return
  41832. * the index of the closest element if there is no exact hit. This is because
  41833. * mappings between original and generated line/col pairs are single points,
  41834. * and there is an implicit region between each of them, so a miss just means
  41835. * that you aren't on the very start of a region.
  41836. *
  41837. * @param aNeedle The element you are looking for.
  41838. * @param aHaystack The array that is being searched.
  41839. * @param aCompare A function which takes the needle and an element in the
  41840. * array and returns -1, 0, or 1 depending on whether the needle is less
  41841. * than, equal to, or greater than the element, respectively.
  41842. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  41843. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  41844. * closest element that is smaller than or greater than the one we are
  41845. * searching for, respectively, if the exact element cannot be found.
  41846. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  41847. */
  41848. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  41849. if (aHaystack.length === 0) {
  41850. return -1;
  41851. }
  41852. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  41853. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  41854. if (index < 0) {
  41855. return -1;
  41856. }
  41857. // We have found either the exact element, or the next-closest element than
  41858. // the one we are searching for. However, there may be more than one such
  41859. // element. Make sure we always return the smallest of these.
  41860. while (index - 1 >= 0) {
  41861. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  41862. break;
  41863. }
  41864. --index;
  41865. }
  41866. return index;
  41867. };
  41868. } (binarySearch));
  41869. return binarySearch;
  41870. }
  41871. var quickSort = {};
  41872. /* -*- Mode: js; js-indent-level: 2; -*- */
  41873. var hasRequiredQuickSort;
  41874. function requireQuickSort () {
  41875. if (hasRequiredQuickSort) return quickSort;
  41876. hasRequiredQuickSort = 1;
  41877. /*
  41878. * Copyright 2011 Mozilla Foundation and contributors
  41879. * Licensed under the New BSD license. See LICENSE or:
  41880. * http://opensource.org/licenses/BSD-3-Clause
  41881. */
  41882. // It turns out that some (most?) JavaScript engines don't self-host
  41883. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  41884. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  41885. // custom comparator function, calling back and forth between the VM's C++ and
  41886. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  41887. // worse generated code for the comparator function than would be optimal. In
  41888. // fact, when sorting with a comparator, these costs outweigh the benefits of
  41889. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  41890. // a ~3500ms mean speed-up in `bench/bench.html`.
  41891. /**
  41892. * Swap the elements indexed by `x` and `y` in the array `ary`.
  41893. *
  41894. * @param {Array} ary
  41895. * The array.
  41896. * @param {Number} x
  41897. * The index of the first item.
  41898. * @param {Number} y
  41899. * The index of the second item.
  41900. */
  41901. function swap(ary, x, y) {
  41902. var temp = ary[x];
  41903. ary[x] = ary[y];
  41904. ary[y] = temp;
  41905. }
  41906. /**
  41907. * Returns a random integer within the range `low .. high` inclusive.
  41908. *
  41909. * @param {Number} low
  41910. * The lower bound on the range.
  41911. * @param {Number} high
  41912. * The upper bound on the range.
  41913. */
  41914. function randomIntInRange(low, high) {
  41915. return Math.round(low + (Math.random() * (high - low)));
  41916. }
  41917. /**
  41918. * The Quick Sort algorithm.
  41919. *
  41920. * @param {Array} ary
  41921. * An array to sort.
  41922. * @param {function} comparator
  41923. * Function to use to compare two items.
  41924. * @param {Number} p
  41925. * Start index of the array
  41926. * @param {Number} r
  41927. * End index of the array
  41928. */
  41929. function doQuickSort(ary, comparator, p, r) {
  41930. // If our lower bound is less than our upper bound, we (1) partition the
  41931. // array into two pieces and (2) recurse on each half. If it is not, this is
  41932. // the empty array and our base case.
  41933. if (p < r) {
  41934. // (1) Partitioning.
  41935. //
  41936. // The partitioning chooses a pivot between `p` and `r` and moves all
  41937. // elements that are less than or equal to the pivot to the before it, and
  41938. // all the elements that are greater than it after it. The effect is that
  41939. // once partition is done, the pivot is in the exact place it will be when
  41940. // the array is put in sorted order, and it will not need to be moved
  41941. // again. This runs in O(n) time.
  41942. // Always choose a random pivot so that an input array which is reverse
  41943. // sorted does not cause O(n^2) running time.
  41944. var pivotIndex = randomIntInRange(p, r);
  41945. var i = p - 1;
  41946. swap(ary, pivotIndex, r);
  41947. var pivot = ary[r];
  41948. // Immediately after `j` is incremented in this loop, the following hold
  41949. // true:
  41950. //
  41951. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  41952. //
  41953. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  41954. for (var j = p; j < r; j++) {
  41955. if (comparator(ary[j], pivot) <= 0) {
  41956. i += 1;
  41957. swap(ary, i, j);
  41958. }
  41959. }
  41960. swap(ary, i + 1, j);
  41961. var q = i + 1;
  41962. // (2) Recurse on each half.
  41963. doQuickSort(ary, comparator, p, q - 1);
  41964. doQuickSort(ary, comparator, q + 1, r);
  41965. }
  41966. }
  41967. /**
  41968. * Sort the given array in-place with the given comparator function.
  41969. *
  41970. * @param {Array} ary
  41971. * An array to sort.
  41972. * @param {function} comparator
  41973. * Function to use to compare two items.
  41974. */
  41975. quickSort.quickSort = function (ary, comparator) {
  41976. doQuickSort(ary, comparator, 0, ary.length - 1);
  41977. };
  41978. return quickSort;
  41979. }
  41980. /* -*- Mode: js; js-indent-level: 2; -*- */
  41981. var hasRequiredSourceMapConsumer;
  41982. function requireSourceMapConsumer () {
  41983. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  41984. hasRequiredSourceMapConsumer = 1;
  41985. /*
  41986. * Copyright 2011 Mozilla Foundation and contributors
  41987. * Licensed under the New BSD license. See LICENSE or:
  41988. * http://opensource.org/licenses/BSD-3-Clause
  41989. */
  41990. var util = /*@__PURE__*/ requireUtil();
  41991. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  41992. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  41993. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  41994. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  41995. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  41996. var sourceMap = aSourceMap;
  41997. if (typeof aSourceMap === 'string') {
  41998. sourceMap = util.parseSourceMapInput(aSourceMap);
  41999. }
  42000. return sourceMap.sections != null
  42001. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  42002. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  42003. }
  42004. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  42005. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  42006. };
  42007. /**
  42008. * The version of the source mapping spec that we are consuming.
  42009. */
  42010. SourceMapConsumer.prototype._version = 3;
  42011. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  42012. // parsed mapping coordinates from the source map's "mappings" attribute. They
  42013. // are lazily instantiated, accessed via the `_generatedMappings` and
  42014. // `_originalMappings` getters respectively, and we only parse the mappings
  42015. // and create these arrays once queried for a source location. We jump through
  42016. // these hoops because there can be many thousands of mappings, and parsing
  42017. // them is expensive, so we only want to do it if we must.
  42018. //
  42019. // Each object in the arrays is of the form:
  42020. //
  42021. // {
  42022. // generatedLine: The line number in the generated code,
  42023. // generatedColumn: The column number in the generated code,
  42024. // source: The path to the original source file that generated this
  42025. // chunk of code,
  42026. // originalLine: The line number in the original source that
  42027. // corresponds to this chunk of generated code,
  42028. // originalColumn: The column number in the original source that
  42029. // corresponds to this chunk of generated code,
  42030. // name: The name of the original symbol which generated this chunk of
  42031. // code.
  42032. // }
  42033. //
  42034. // All properties except for `generatedLine` and `generatedColumn` can be
  42035. // `null`.
  42036. //
  42037. // `_generatedMappings` is ordered by the generated positions.
  42038. //
  42039. // `_originalMappings` is ordered by the original positions.
  42040. SourceMapConsumer.prototype.__generatedMappings = null;
  42041. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  42042. configurable: true,
  42043. enumerable: true,
  42044. get: function () {
  42045. if (!this.__generatedMappings) {
  42046. this._parseMappings(this._mappings, this.sourceRoot);
  42047. }
  42048. return this.__generatedMappings;
  42049. }
  42050. });
  42051. SourceMapConsumer.prototype.__originalMappings = null;
  42052. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  42053. configurable: true,
  42054. enumerable: true,
  42055. get: function () {
  42056. if (!this.__originalMappings) {
  42057. this._parseMappings(this._mappings, this.sourceRoot);
  42058. }
  42059. return this.__originalMappings;
  42060. }
  42061. });
  42062. SourceMapConsumer.prototype._charIsMappingSeparator =
  42063. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  42064. var c = aStr.charAt(index);
  42065. return c === ";" || c === ",";
  42066. };
  42067. /**
  42068. * Parse the mappings in a string in to a data structure which we can easily
  42069. * query (the ordered arrays in the `this.__generatedMappings` and
  42070. * `this.__originalMappings` properties).
  42071. */
  42072. SourceMapConsumer.prototype._parseMappings =
  42073. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  42074. throw new Error("Subclasses must implement _parseMappings");
  42075. };
  42076. SourceMapConsumer.GENERATED_ORDER = 1;
  42077. SourceMapConsumer.ORIGINAL_ORDER = 2;
  42078. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  42079. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  42080. /**
  42081. * Iterate over each mapping between an original source/line/column and a
  42082. * generated line/column in this source map.
  42083. *
  42084. * @param Function aCallback
  42085. * The function that is called with each mapping.
  42086. * @param Object aContext
  42087. * Optional. If specified, this object will be the value of `this` every
  42088. * time that `aCallback` is called.
  42089. * @param aOrder
  42090. * Either `SourceMapConsumer.GENERATED_ORDER` or
  42091. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  42092. * iterate over the mappings sorted by the generated file's line/column
  42093. * order or the original's source/line/column order, respectively. Defaults to
  42094. * `SourceMapConsumer.GENERATED_ORDER`.
  42095. */
  42096. SourceMapConsumer.prototype.eachMapping =
  42097. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  42098. var context = aContext || null;
  42099. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  42100. var mappings;
  42101. switch (order) {
  42102. case SourceMapConsumer.GENERATED_ORDER:
  42103. mappings = this._generatedMappings;
  42104. break;
  42105. case SourceMapConsumer.ORIGINAL_ORDER:
  42106. mappings = this._originalMappings;
  42107. break;
  42108. default:
  42109. throw new Error("Unknown order of iteration.");
  42110. }
  42111. var sourceRoot = this.sourceRoot;
  42112. mappings.map(function (mapping) {
  42113. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  42114. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  42115. return {
  42116. source: source,
  42117. generatedLine: mapping.generatedLine,
  42118. generatedColumn: mapping.generatedColumn,
  42119. originalLine: mapping.originalLine,
  42120. originalColumn: mapping.originalColumn,
  42121. name: mapping.name === null ? null : this._names.at(mapping.name)
  42122. };
  42123. }, this).forEach(aCallback, context);
  42124. };
  42125. /**
  42126. * Returns all generated line and column information for the original source,
  42127. * line, and column provided. If no column is provided, returns all mappings
  42128. * corresponding to a either the line we are searching for or the next
  42129. * closest line that has any mappings. Otherwise, returns all mappings
  42130. * corresponding to the given line and either the column we are searching for
  42131. * or the next closest column that has any offsets.
  42132. *
  42133. * The only argument is an object with the following properties:
  42134. *
  42135. * - source: The filename of the original source.
  42136. * - line: The line number in the original source. The line number is 1-based.
  42137. * - column: Optional. the column number in the original source.
  42138. * The column number is 0-based.
  42139. *
  42140. * and an array of objects is returned, each with the following properties:
  42141. *
  42142. * - line: The line number in the generated source, or null. The
  42143. * line number is 1-based.
  42144. * - column: The column number in the generated source, or null.
  42145. * The column number is 0-based.
  42146. */
  42147. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  42148. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  42149. var line = util.getArg(aArgs, 'line');
  42150. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  42151. // returns the index of the closest mapping less than the needle. By
  42152. // setting needle.originalColumn to 0, we thus find the last mapping for
  42153. // the given line, provided such a mapping exists.
  42154. var needle = {
  42155. source: util.getArg(aArgs, 'source'),
  42156. originalLine: line,
  42157. originalColumn: util.getArg(aArgs, 'column', 0)
  42158. };
  42159. needle.source = this._findSourceIndex(needle.source);
  42160. if (needle.source < 0) {
  42161. return [];
  42162. }
  42163. var mappings = [];
  42164. var index = this._findMapping(needle,
  42165. this._originalMappings,
  42166. "originalLine",
  42167. "originalColumn",
  42168. util.compareByOriginalPositions,
  42169. binarySearch.LEAST_UPPER_BOUND);
  42170. if (index >= 0) {
  42171. var mapping = this._originalMappings[index];
  42172. if (aArgs.column === undefined) {
  42173. var originalLine = mapping.originalLine;
  42174. // Iterate until either we run out of mappings, or we run into
  42175. // a mapping for a different line than the one we found. Since
  42176. // mappings are sorted, this is guaranteed to find all mappings for
  42177. // the line we found.
  42178. while (mapping && mapping.originalLine === originalLine) {
  42179. mappings.push({
  42180. line: util.getArg(mapping, 'generatedLine', null),
  42181. column: util.getArg(mapping, 'generatedColumn', null),
  42182. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  42183. });
  42184. mapping = this._originalMappings[++index];
  42185. }
  42186. } else {
  42187. var originalColumn = mapping.originalColumn;
  42188. // Iterate until either we run out of mappings, or we run into
  42189. // a mapping for a different line than the one we were searching for.
  42190. // Since mappings are sorted, this is guaranteed to find all mappings for
  42191. // the line we are searching for.
  42192. while (mapping &&
  42193. mapping.originalLine === line &&
  42194. mapping.originalColumn == originalColumn) {
  42195. mappings.push({
  42196. line: util.getArg(mapping, 'generatedLine', null),
  42197. column: util.getArg(mapping, 'generatedColumn', null),
  42198. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  42199. });
  42200. mapping = this._originalMappings[++index];
  42201. }
  42202. }
  42203. }
  42204. return mappings;
  42205. };
  42206. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  42207. /**
  42208. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  42209. * query for information about the original file positions by giving it a file
  42210. * position in the generated source.
  42211. *
  42212. * The first parameter is the raw source map (either as a JSON string, or
  42213. * already parsed to an object). According to the spec, source maps have the
  42214. * following attributes:
  42215. *
  42216. * - version: Which version of the source map spec this map is following.
  42217. * - sources: An array of URLs to the original source files.
  42218. * - names: An array of identifiers which can be referrenced by individual mappings.
  42219. * - sourceRoot: Optional. The URL root from which all sources are relative.
  42220. * - sourcesContent: Optional. An array of contents of the original source files.
  42221. * - mappings: A string of base64 VLQs which contain the actual mappings.
  42222. * - file: Optional. The generated file this source map is associated with.
  42223. *
  42224. * Here is an example source map, taken from the source map spec[0]:
  42225. *
  42226. * {
  42227. * version : 3,
  42228. * file: "out.js",
  42229. * sourceRoot : "",
  42230. * sources: ["foo.js", "bar.js"],
  42231. * names: ["src", "maps", "are", "fun"],
  42232. * mappings: "AA,AB;;ABCDE;"
  42233. * }
  42234. *
  42235. * The second parameter, if given, is a string whose value is the URL
  42236. * at which the source map was found. This URL is used to compute the
  42237. * sources array.
  42238. *
  42239. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  42240. */
  42241. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  42242. var sourceMap = aSourceMap;
  42243. if (typeof aSourceMap === 'string') {
  42244. sourceMap = util.parseSourceMapInput(aSourceMap);
  42245. }
  42246. var version = util.getArg(sourceMap, 'version');
  42247. var sources = util.getArg(sourceMap, 'sources');
  42248. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  42249. // requires the array) to play nice here.
  42250. var names = util.getArg(sourceMap, 'names', []);
  42251. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  42252. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  42253. var mappings = util.getArg(sourceMap, 'mappings');
  42254. var file = util.getArg(sourceMap, 'file', null);
  42255. // Once again, Sass deviates from the spec and supplies the version as a
  42256. // string rather than a number, so we use loose equality checking here.
  42257. if (version != this._version) {
  42258. throw new Error('Unsupported version: ' + version);
  42259. }
  42260. if (sourceRoot) {
  42261. sourceRoot = util.normalize(sourceRoot);
  42262. }
  42263. sources = sources
  42264. .map(String)
  42265. // Some source maps produce relative source paths like "./foo.js" instead of
  42266. // "foo.js". Normalize these first so that future comparisons will succeed.
  42267. // See bugzil.la/1090768.
  42268. .map(util.normalize)
  42269. // Always ensure that absolute sources are internally stored relative to
  42270. // the source root, if the source root is absolute. Not doing this would
  42271. // be particularly problematic when the source root is a prefix of the
  42272. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  42273. .map(function (source) {
  42274. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  42275. ? util.relative(sourceRoot, source)
  42276. : source;
  42277. });
  42278. // Pass `true` below to allow duplicate names and sources. While source maps
  42279. // are intended to be compressed and deduplicated, the TypeScript compiler
  42280. // sometimes generates source maps with duplicates in them. See Github issue
  42281. // #72 and bugzil.la/889492.
  42282. this._names = ArraySet.fromArray(names.map(String), true);
  42283. this._sources = ArraySet.fromArray(sources, true);
  42284. this._absoluteSources = this._sources.toArray().map(function (s) {
  42285. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  42286. });
  42287. this.sourceRoot = sourceRoot;
  42288. this.sourcesContent = sourcesContent;
  42289. this._mappings = mappings;
  42290. this._sourceMapURL = aSourceMapURL;
  42291. this.file = file;
  42292. }
  42293. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  42294. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  42295. /**
  42296. * Utility function to find the index of a source. Returns -1 if not
  42297. * found.
  42298. */
  42299. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  42300. var relativeSource = aSource;
  42301. if (this.sourceRoot != null) {
  42302. relativeSource = util.relative(this.sourceRoot, relativeSource);
  42303. }
  42304. if (this._sources.has(relativeSource)) {
  42305. return this._sources.indexOf(relativeSource);
  42306. }
  42307. // Maybe aSource is an absolute URL as returned by |sources|. In
  42308. // this case we can't simply undo the transform.
  42309. var i;
  42310. for (i = 0; i < this._absoluteSources.length; ++i) {
  42311. if (this._absoluteSources[i] == aSource) {
  42312. return i;
  42313. }
  42314. }
  42315. return -1;
  42316. };
  42317. /**
  42318. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  42319. *
  42320. * @param SourceMapGenerator aSourceMap
  42321. * The source map that will be consumed.
  42322. * @param String aSourceMapURL
  42323. * The URL at which the source map can be found (optional)
  42324. * @returns BasicSourceMapConsumer
  42325. */
  42326. BasicSourceMapConsumer.fromSourceMap =
  42327. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  42328. var smc = Object.create(BasicSourceMapConsumer.prototype);
  42329. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  42330. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  42331. smc.sourceRoot = aSourceMap._sourceRoot;
  42332. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  42333. smc.sourceRoot);
  42334. smc.file = aSourceMap._file;
  42335. smc._sourceMapURL = aSourceMapURL;
  42336. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  42337. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  42338. });
  42339. // Because we are modifying the entries (by converting string sources and
  42340. // names to indices into the sources and names ArraySets), we have to make
  42341. // a copy of the entry or else bad things happen. Shared mutable state
  42342. // strikes again! See github issue #191.
  42343. var generatedMappings = aSourceMap._mappings.toArray().slice();
  42344. var destGeneratedMappings = smc.__generatedMappings = [];
  42345. var destOriginalMappings = smc.__originalMappings = [];
  42346. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  42347. var srcMapping = generatedMappings[i];
  42348. var destMapping = new Mapping;
  42349. destMapping.generatedLine = srcMapping.generatedLine;
  42350. destMapping.generatedColumn = srcMapping.generatedColumn;
  42351. if (srcMapping.source) {
  42352. destMapping.source = sources.indexOf(srcMapping.source);
  42353. destMapping.originalLine = srcMapping.originalLine;
  42354. destMapping.originalColumn = srcMapping.originalColumn;
  42355. if (srcMapping.name) {
  42356. destMapping.name = names.indexOf(srcMapping.name);
  42357. }
  42358. destOriginalMappings.push(destMapping);
  42359. }
  42360. destGeneratedMappings.push(destMapping);
  42361. }
  42362. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  42363. return smc;
  42364. };
  42365. /**
  42366. * The version of the source mapping spec that we are consuming.
  42367. */
  42368. BasicSourceMapConsumer.prototype._version = 3;
  42369. /**
  42370. * The list of original sources.
  42371. */
  42372. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  42373. get: function () {
  42374. return this._absoluteSources.slice();
  42375. }
  42376. });
  42377. /**
  42378. * Provide the JIT with a nice shape / hidden class.
  42379. */
  42380. function Mapping() {
  42381. this.generatedLine = 0;
  42382. this.generatedColumn = 0;
  42383. this.source = null;
  42384. this.originalLine = null;
  42385. this.originalColumn = null;
  42386. this.name = null;
  42387. }
  42388. /**
  42389. * Parse the mappings in a string in to a data structure which we can easily
  42390. * query (the ordered arrays in the `this.__generatedMappings` and
  42391. * `this.__originalMappings` properties).
  42392. */
  42393. BasicSourceMapConsumer.prototype._parseMappings =
  42394. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  42395. var generatedLine = 1;
  42396. var previousGeneratedColumn = 0;
  42397. var previousOriginalLine = 0;
  42398. var previousOriginalColumn = 0;
  42399. var previousSource = 0;
  42400. var previousName = 0;
  42401. var length = aStr.length;
  42402. var index = 0;
  42403. var cachedSegments = {};
  42404. var temp = {};
  42405. var originalMappings = [];
  42406. var generatedMappings = [];
  42407. var mapping, str, segment, end, value;
  42408. while (index < length) {
  42409. if (aStr.charAt(index) === ';') {
  42410. generatedLine++;
  42411. index++;
  42412. previousGeneratedColumn = 0;
  42413. }
  42414. else if (aStr.charAt(index) === ',') {
  42415. index++;
  42416. }
  42417. else {
  42418. mapping = new Mapping();
  42419. mapping.generatedLine = generatedLine;
  42420. // Because each offset is encoded relative to the previous one,
  42421. // many segments often have the same encoding. We can exploit this
  42422. // fact by caching the parsed variable length fields of each segment,
  42423. // allowing us to avoid a second parse if we encounter the same
  42424. // segment again.
  42425. for (end = index; end < length; end++) {
  42426. if (this._charIsMappingSeparator(aStr, end)) {
  42427. break;
  42428. }
  42429. }
  42430. str = aStr.slice(index, end);
  42431. segment = cachedSegments[str];
  42432. if (segment) {
  42433. index += str.length;
  42434. } else {
  42435. segment = [];
  42436. while (index < end) {
  42437. base64VLQ.decode(aStr, index, temp);
  42438. value = temp.value;
  42439. index = temp.rest;
  42440. segment.push(value);
  42441. }
  42442. if (segment.length === 2) {
  42443. throw new Error('Found a source, but no line and column');
  42444. }
  42445. if (segment.length === 3) {
  42446. throw new Error('Found a source and line, but no column');
  42447. }
  42448. cachedSegments[str] = segment;
  42449. }
  42450. // Generated column.
  42451. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  42452. previousGeneratedColumn = mapping.generatedColumn;
  42453. if (segment.length > 1) {
  42454. // Original source.
  42455. mapping.source = previousSource + segment[1];
  42456. previousSource += segment[1];
  42457. // Original line.
  42458. mapping.originalLine = previousOriginalLine + segment[2];
  42459. previousOriginalLine = mapping.originalLine;
  42460. // Lines are stored 0-based
  42461. mapping.originalLine += 1;
  42462. // Original column.
  42463. mapping.originalColumn = previousOriginalColumn + segment[3];
  42464. previousOriginalColumn = mapping.originalColumn;
  42465. if (segment.length > 4) {
  42466. // Original name.
  42467. mapping.name = previousName + segment[4];
  42468. previousName += segment[4];
  42469. }
  42470. }
  42471. generatedMappings.push(mapping);
  42472. if (typeof mapping.originalLine === 'number') {
  42473. originalMappings.push(mapping);
  42474. }
  42475. }
  42476. }
  42477. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  42478. this.__generatedMappings = generatedMappings;
  42479. quickSort(originalMappings, util.compareByOriginalPositions);
  42480. this.__originalMappings = originalMappings;
  42481. };
  42482. /**
  42483. * Find the mapping that best matches the hypothetical "needle" mapping that
  42484. * we are searching for in the given "haystack" of mappings.
  42485. */
  42486. BasicSourceMapConsumer.prototype._findMapping =
  42487. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  42488. aColumnName, aComparator, aBias) {
  42489. // To return the position we are searching for, we must first find the
  42490. // mapping for the given position and then return the opposite position it
  42491. // points to. Because the mappings are sorted, we can use binary search to
  42492. // find the best mapping.
  42493. if (aNeedle[aLineName] <= 0) {
  42494. throw new TypeError('Line must be greater than or equal to 1, got '
  42495. + aNeedle[aLineName]);
  42496. }
  42497. if (aNeedle[aColumnName] < 0) {
  42498. throw new TypeError('Column must be greater than or equal to 0, got '
  42499. + aNeedle[aColumnName]);
  42500. }
  42501. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  42502. };
  42503. /**
  42504. * Compute the last column for each generated mapping. The last column is
  42505. * inclusive.
  42506. */
  42507. BasicSourceMapConsumer.prototype.computeColumnSpans =
  42508. function SourceMapConsumer_computeColumnSpans() {
  42509. for (var index = 0; index < this._generatedMappings.length; ++index) {
  42510. var mapping = this._generatedMappings[index];
  42511. // Mappings do not contain a field for the last generated columnt. We
  42512. // can come up with an optimistic estimate, however, by assuming that
  42513. // mappings are contiguous (i.e. given two consecutive mappings, the
  42514. // first mapping ends where the second one starts).
  42515. if (index + 1 < this._generatedMappings.length) {
  42516. var nextMapping = this._generatedMappings[index + 1];
  42517. if (mapping.generatedLine === nextMapping.generatedLine) {
  42518. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  42519. continue;
  42520. }
  42521. }
  42522. // The last mapping for each line spans the entire line.
  42523. mapping.lastGeneratedColumn = Infinity;
  42524. }
  42525. };
  42526. /**
  42527. * Returns the original source, line, and column information for the generated
  42528. * source's line and column positions provided. The only argument is an object
  42529. * with the following properties:
  42530. *
  42531. * - line: The line number in the generated source. The line number
  42532. * is 1-based.
  42533. * - column: The column number in the generated source. The column
  42534. * number is 0-based.
  42535. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  42536. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  42537. * closest element that is smaller than or greater than the one we are
  42538. * searching for, respectively, if the exact element cannot be found.
  42539. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  42540. *
  42541. * and an object is returned with the following properties:
  42542. *
  42543. * - source: The original source file, or null.
  42544. * - line: The line number in the original source, or null. The
  42545. * line number is 1-based.
  42546. * - column: The column number in the original source, or null. The
  42547. * column number is 0-based.
  42548. * - name: The original identifier, or null.
  42549. */
  42550. BasicSourceMapConsumer.prototype.originalPositionFor =
  42551. function SourceMapConsumer_originalPositionFor(aArgs) {
  42552. var needle = {
  42553. generatedLine: util.getArg(aArgs, 'line'),
  42554. generatedColumn: util.getArg(aArgs, 'column')
  42555. };
  42556. var index = this._findMapping(
  42557. needle,
  42558. this._generatedMappings,
  42559. "generatedLine",
  42560. "generatedColumn",
  42561. util.compareByGeneratedPositionsDeflated,
  42562. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  42563. );
  42564. if (index >= 0) {
  42565. var mapping = this._generatedMappings[index];
  42566. if (mapping.generatedLine === needle.generatedLine) {
  42567. var source = util.getArg(mapping, 'source', null);
  42568. if (source !== null) {
  42569. source = this._sources.at(source);
  42570. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  42571. }
  42572. var name = util.getArg(mapping, 'name', null);
  42573. if (name !== null) {
  42574. name = this._names.at(name);
  42575. }
  42576. return {
  42577. source: source,
  42578. line: util.getArg(mapping, 'originalLine', null),
  42579. column: util.getArg(mapping, 'originalColumn', null),
  42580. name: name
  42581. };
  42582. }
  42583. }
  42584. return {
  42585. source: null,
  42586. line: null,
  42587. column: null,
  42588. name: null
  42589. };
  42590. };
  42591. /**
  42592. * Return true if we have the source content for every source in the source
  42593. * map, false otherwise.
  42594. */
  42595. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  42596. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  42597. if (!this.sourcesContent) {
  42598. return false;
  42599. }
  42600. return this.sourcesContent.length >= this._sources.size() &&
  42601. !this.sourcesContent.some(function (sc) { return sc == null; });
  42602. };
  42603. /**
  42604. * Returns the original source content. The only argument is the url of the
  42605. * original source file. Returns null if no original source content is
  42606. * available.
  42607. */
  42608. BasicSourceMapConsumer.prototype.sourceContentFor =
  42609. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  42610. if (!this.sourcesContent) {
  42611. return null;
  42612. }
  42613. var index = this._findSourceIndex(aSource);
  42614. if (index >= 0) {
  42615. return this.sourcesContent[index];
  42616. }
  42617. var relativeSource = aSource;
  42618. if (this.sourceRoot != null) {
  42619. relativeSource = util.relative(this.sourceRoot, relativeSource);
  42620. }
  42621. var url;
  42622. if (this.sourceRoot != null
  42623. && (url = util.urlParse(this.sourceRoot))) {
  42624. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  42625. // many users. We can help them out when they expect file:// URIs to
  42626. // behave like it would if they were running a local HTTP server. See
  42627. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  42628. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  42629. if (url.scheme == "file"
  42630. && this._sources.has(fileUriAbsPath)) {
  42631. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  42632. }
  42633. if ((!url.path || url.path == "/")
  42634. && this._sources.has("/" + relativeSource)) {
  42635. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  42636. }
  42637. }
  42638. // This function is used recursively from
  42639. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  42640. // don't want to throw if we can't find the source - we just want to
  42641. // return null, so we provide a flag to exit gracefully.
  42642. if (nullOnMissing) {
  42643. return null;
  42644. }
  42645. else {
  42646. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  42647. }
  42648. };
  42649. /**
  42650. * Returns the generated line and column information for the original source,
  42651. * line, and column positions provided. The only argument is an object with
  42652. * the following properties:
  42653. *
  42654. * - source: The filename of the original source.
  42655. * - line: The line number in the original source. The line number
  42656. * is 1-based.
  42657. * - column: The column number in the original source. The column
  42658. * number is 0-based.
  42659. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  42660. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  42661. * closest element that is smaller than or greater than the one we are
  42662. * searching for, respectively, if the exact element cannot be found.
  42663. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  42664. *
  42665. * and an object is returned with the following properties:
  42666. *
  42667. * - line: The line number in the generated source, or null. The
  42668. * line number is 1-based.
  42669. * - column: The column number in the generated source, or null.
  42670. * The column number is 0-based.
  42671. */
  42672. BasicSourceMapConsumer.prototype.generatedPositionFor =
  42673. function SourceMapConsumer_generatedPositionFor(aArgs) {
  42674. var source = util.getArg(aArgs, 'source');
  42675. source = this._findSourceIndex(source);
  42676. if (source < 0) {
  42677. return {
  42678. line: null,
  42679. column: null,
  42680. lastColumn: null
  42681. };
  42682. }
  42683. var needle = {
  42684. source: source,
  42685. originalLine: util.getArg(aArgs, 'line'),
  42686. originalColumn: util.getArg(aArgs, 'column')
  42687. };
  42688. var index = this._findMapping(
  42689. needle,
  42690. this._originalMappings,
  42691. "originalLine",
  42692. "originalColumn",
  42693. util.compareByOriginalPositions,
  42694. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  42695. );
  42696. if (index >= 0) {
  42697. var mapping = this._originalMappings[index];
  42698. if (mapping.source === needle.source) {
  42699. return {
  42700. line: util.getArg(mapping, 'generatedLine', null),
  42701. column: util.getArg(mapping, 'generatedColumn', null),
  42702. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  42703. };
  42704. }
  42705. }
  42706. return {
  42707. line: null,
  42708. column: null,
  42709. lastColumn: null
  42710. };
  42711. };
  42712. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  42713. /**
  42714. * An IndexedSourceMapConsumer instance represents a parsed source map which
  42715. * we can query for information. It differs from BasicSourceMapConsumer in
  42716. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  42717. * input.
  42718. *
  42719. * The first parameter is a raw source map (either as a JSON string, or already
  42720. * parsed to an object). According to the spec for indexed source maps, they
  42721. * have the following attributes:
  42722. *
  42723. * - version: Which version of the source map spec this map is following.
  42724. * - file: Optional. The generated file this source map is associated with.
  42725. * - sections: A list of section definitions.
  42726. *
  42727. * Each value under the "sections" field has two fields:
  42728. * - offset: The offset into the original specified at which this section
  42729. * begins to apply, defined as an object with a "line" and "column"
  42730. * field.
  42731. * - map: A source map definition. This source map could also be indexed,
  42732. * but doesn't have to be.
  42733. *
  42734. * Instead of the "map" field, it's also possible to have a "url" field
  42735. * specifying a URL to retrieve a source map from, but that's currently
  42736. * unsupported.
  42737. *
  42738. * Here's an example source map, taken from the source map spec[0], but
  42739. * modified to omit a section which uses the "url" field.
  42740. *
  42741. * {
  42742. * version : 3,
  42743. * file: "app.js",
  42744. * sections: [{
  42745. * offset: {line:100, column:10},
  42746. * map: {
  42747. * version : 3,
  42748. * file: "section.js",
  42749. * sources: ["foo.js", "bar.js"],
  42750. * names: ["src", "maps", "are", "fun"],
  42751. * mappings: "AAAA,E;;ABCDE;"
  42752. * }
  42753. * }],
  42754. * }
  42755. *
  42756. * The second parameter, if given, is a string whose value is the URL
  42757. * at which the source map was found. This URL is used to compute the
  42758. * sources array.
  42759. *
  42760. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  42761. */
  42762. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  42763. var sourceMap = aSourceMap;
  42764. if (typeof aSourceMap === 'string') {
  42765. sourceMap = util.parseSourceMapInput(aSourceMap);
  42766. }
  42767. var version = util.getArg(sourceMap, 'version');
  42768. var sections = util.getArg(sourceMap, 'sections');
  42769. if (version != this._version) {
  42770. throw new Error('Unsupported version: ' + version);
  42771. }
  42772. this._sources = new ArraySet();
  42773. this._names = new ArraySet();
  42774. var lastOffset = {
  42775. line: -1,
  42776. column: 0
  42777. };
  42778. this._sections = sections.map(function (s) {
  42779. if (s.url) {
  42780. // The url field will require support for asynchronicity.
  42781. // See https://github.com/mozilla/source-map/issues/16
  42782. throw new Error('Support for url field in sections not implemented.');
  42783. }
  42784. var offset = util.getArg(s, 'offset');
  42785. var offsetLine = util.getArg(offset, 'line');
  42786. var offsetColumn = util.getArg(offset, 'column');
  42787. if (offsetLine < lastOffset.line ||
  42788. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  42789. throw new Error('Section offsets must be ordered and non-overlapping.');
  42790. }
  42791. lastOffset = offset;
  42792. return {
  42793. generatedOffset: {
  42794. // The offset fields are 0-based, but we use 1-based indices when
  42795. // encoding/decoding from VLQ.
  42796. generatedLine: offsetLine + 1,
  42797. generatedColumn: offsetColumn + 1
  42798. },
  42799. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  42800. }
  42801. });
  42802. }
  42803. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  42804. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  42805. /**
  42806. * The version of the source mapping spec that we are consuming.
  42807. */
  42808. IndexedSourceMapConsumer.prototype._version = 3;
  42809. /**
  42810. * The list of original sources.
  42811. */
  42812. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  42813. get: function () {
  42814. var sources = [];
  42815. for (var i = 0; i < this._sections.length; i++) {
  42816. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  42817. sources.push(this._sections[i].consumer.sources[j]);
  42818. }
  42819. }
  42820. return sources;
  42821. }
  42822. });
  42823. /**
  42824. * Returns the original source, line, and column information for the generated
  42825. * source's line and column positions provided. The only argument is an object
  42826. * with the following properties:
  42827. *
  42828. * - line: The line number in the generated source. The line number
  42829. * is 1-based.
  42830. * - column: The column number in the generated source. The column
  42831. * number is 0-based.
  42832. *
  42833. * and an object is returned with the following properties:
  42834. *
  42835. * - source: The original source file, or null.
  42836. * - line: The line number in the original source, or null. The
  42837. * line number is 1-based.
  42838. * - column: The column number in the original source, or null. The
  42839. * column number is 0-based.
  42840. * - name: The original identifier, or null.
  42841. */
  42842. IndexedSourceMapConsumer.prototype.originalPositionFor =
  42843. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  42844. var needle = {
  42845. generatedLine: util.getArg(aArgs, 'line'),
  42846. generatedColumn: util.getArg(aArgs, 'column')
  42847. };
  42848. // Find the section containing the generated position we're trying to map
  42849. // to an original position.
  42850. var sectionIndex = binarySearch.search(needle, this._sections,
  42851. function(needle, section) {
  42852. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  42853. if (cmp) {
  42854. return cmp;
  42855. }
  42856. return (needle.generatedColumn -
  42857. section.generatedOffset.generatedColumn);
  42858. });
  42859. var section = this._sections[sectionIndex];
  42860. if (!section) {
  42861. return {
  42862. source: null,
  42863. line: null,
  42864. column: null,
  42865. name: null
  42866. };
  42867. }
  42868. return section.consumer.originalPositionFor({
  42869. line: needle.generatedLine -
  42870. (section.generatedOffset.generatedLine - 1),
  42871. column: needle.generatedColumn -
  42872. (section.generatedOffset.generatedLine === needle.generatedLine
  42873. ? section.generatedOffset.generatedColumn - 1
  42874. : 0),
  42875. bias: aArgs.bias
  42876. });
  42877. };
  42878. /**
  42879. * Return true if we have the source content for every source in the source
  42880. * map, false otherwise.
  42881. */
  42882. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  42883. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  42884. return this._sections.every(function (s) {
  42885. return s.consumer.hasContentsOfAllSources();
  42886. });
  42887. };
  42888. /**
  42889. * Returns the original source content. The only argument is the url of the
  42890. * original source file. Returns null if no original source content is
  42891. * available.
  42892. */
  42893. IndexedSourceMapConsumer.prototype.sourceContentFor =
  42894. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  42895. for (var i = 0; i < this._sections.length; i++) {
  42896. var section = this._sections[i];
  42897. var content = section.consumer.sourceContentFor(aSource, true);
  42898. if (content) {
  42899. return content;
  42900. }
  42901. }
  42902. if (nullOnMissing) {
  42903. return null;
  42904. }
  42905. else {
  42906. throw new Error('"' + aSource + '" is not in the SourceMap.');
  42907. }
  42908. };
  42909. /**
  42910. * Returns the generated line and column information for the original source,
  42911. * line, and column positions provided. The only argument is an object with
  42912. * the following properties:
  42913. *
  42914. * - source: The filename of the original source.
  42915. * - line: The line number in the original source. The line number
  42916. * is 1-based.
  42917. * - column: The column number in the original source. The column
  42918. * number is 0-based.
  42919. *
  42920. * and an object is returned with the following properties:
  42921. *
  42922. * - line: The line number in the generated source, or null. The
  42923. * line number is 1-based.
  42924. * - column: The column number in the generated source, or null.
  42925. * The column number is 0-based.
  42926. */
  42927. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  42928. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  42929. for (var i = 0; i < this._sections.length; i++) {
  42930. var section = this._sections[i];
  42931. // Only consider this section if the requested source is in the list of
  42932. // sources of the consumer.
  42933. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  42934. continue;
  42935. }
  42936. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  42937. if (generatedPosition) {
  42938. var ret = {
  42939. line: generatedPosition.line +
  42940. (section.generatedOffset.generatedLine - 1),
  42941. column: generatedPosition.column +
  42942. (section.generatedOffset.generatedLine === generatedPosition.line
  42943. ? section.generatedOffset.generatedColumn - 1
  42944. : 0)
  42945. };
  42946. return ret;
  42947. }
  42948. }
  42949. return {
  42950. line: null,
  42951. column: null
  42952. };
  42953. };
  42954. /**
  42955. * Parse the mappings in a string in to a data structure which we can easily
  42956. * query (the ordered arrays in the `this.__generatedMappings` and
  42957. * `this.__originalMappings` properties).
  42958. */
  42959. IndexedSourceMapConsumer.prototype._parseMappings =
  42960. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  42961. this.__generatedMappings = [];
  42962. this.__originalMappings = [];
  42963. for (var i = 0; i < this._sections.length; i++) {
  42964. var section = this._sections[i];
  42965. var sectionMappings = section.consumer._generatedMappings;
  42966. for (var j = 0; j < sectionMappings.length; j++) {
  42967. var mapping = sectionMappings[j];
  42968. var source = section.consumer._sources.at(mapping.source);
  42969. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  42970. this._sources.add(source);
  42971. source = this._sources.indexOf(source);
  42972. var name = null;
  42973. if (mapping.name) {
  42974. name = section.consumer._names.at(mapping.name);
  42975. this._names.add(name);
  42976. name = this._names.indexOf(name);
  42977. }
  42978. // The mappings coming from the consumer for the section have
  42979. // generated positions relative to the start of the section, so we
  42980. // need to offset them to be relative to the start of the concatenated
  42981. // generated file.
  42982. var adjustedMapping = {
  42983. source: source,
  42984. generatedLine: mapping.generatedLine +
  42985. (section.generatedOffset.generatedLine - 1),
  42986. generatedColumn: mapping.generatedColumn +
  42987. (section.generatedOffset.generatedLine === mapping.generatedLine
  42988. ? section.generatedOffset.generatedColumn - 1
  42989. : 0),
  42990. originalLine: mapping.originalLine,
  42991. originalColumn: mapping.originalColumn,
  42992. name: name
  42993. };
  42994. this.__generatedMappings.push(adjustedMapping);
  42995. if (typeof adjustedMapping.originalLine === 'number') {
  42996. this.__originalMappings.push(adjustedMapping);
  42997. }
  42998. }
  42999. }
  43000. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  43001. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  43002. };
  43003. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  43004. return sourceMapConsumer;
  43005. }
  43006. var sourceNode = {};
  43007. /* -*- Mode: js; js-indent-level: 2; -*- */
  43008. var hasRequiredSourceNode;
  43009. function requireSourceNode () {
  43010. if (hasRequiredSourceNode) return sourceNode;
  43011. hasRequiredSourceNode = 1;
  43012. /*
  43013. * Copyright 2011 Mozilla Foundation and contributors
  43014. * Licensed under the New BSD license. See LICENSE or:
  43015. * http://opensource.org/licenses/BSD-3-Clause
  43016. */
  43017. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  43018. var util = /*@__PURE__*/ requireUtil();
  43019. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  43020. // operating systems these days (capturing the result).
  43021. var REGEX_NEWLINE = /(\r?\n)/;
  43022. // Newline character code for charCodeAt() comparisons
  43023. var NEWLINE_CODE = 10;
  43024. // Private symbol for identifying `SourceNode`s when multiple versions of
  43025. // the source-map library are loaded. This MUST NOT CHANGE across
  43026. // versions!
  43027. var isSourceNode = "$$$isSourceNode$$$";
  43028. /**
  43029. * SourceNodes provide a way to abstract over interpolating/concatenating
  43030. * snippets of generated JavaScript source code while maintaining the line and
  43031. * column information associated with the original source code.
  43032. *
  43033. * @param aLine The original line number.
  43034. * @param aColumn The original column number.
  43035. * @param aSource The original source's filename.
  43036. * @param aChunks Optional. An array of strings which are snippets of
  43037. * generated JS, or other SourceNodes.
  43038. * @param aName The original identifier.
  43039. */
  43040. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  43041. this.children = [];
  43042. this.sourceContents = {};
  43043. this.line = aLine == null ? null : aLine;
  43044. this.column = aColumn == null ? null : aColumn;
  43045. this.source = aSource == null ? null : aSource;
  43046. this.name = aName == null ? null : aName;
  43047. this[isSourceNode] = true;
  43048. if (aChunks != null) this.add(aChunks);
  43049. }
  43050. /**
  43051. * Creates a SourceNode from generated code and a SourceMapConsumer.
  43052. *
  43053. * @param aGeneratedCode The generated code
  43054. * @param aSourceMapConsumer The SourceMap for the generated code
  43055. * @param aRelativePath Optional. The path that relative sources in the
  43056. * SourceMapConsumer should be relative to.
  43057. */
  43058. SourceNode.fromStringWithSourceMap =
  43059. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  43060. // The SourceNode we want to fill with the generated code
  43061. // and the SourceMap
  43062. var node = new SourceNode();
  43063. // All even indices of this array are one line of the generated code,
  43064. // while all odd indices are the newlines between two adjacent lines
  43065. // (since `REGEX_NEWLINE` captures its match).
  43066. // Processed fragments are accessed by calling `shiftNextLine`.
  43067. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  43068. var remainingLinesIndex = 0;
  43069. var shiftNextLine = function() {
  43070. var lineContents = getNextLine();
  43071. // The last line of a file might not have a newline.
  43072. var newLine = getNextLine() || "";
  43073. return lineContents + newLine;
  43074. function getNextLine() {
  43075. return remainingLinesIndex < remainingLines.length ?
  43076. remainingLines[remainingLinesIndex++] : undefined;
  43077. }
  43078. };
  43079. // We need to remember the position of "remainingLines"
  43080. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  43081. // The generate SourceNodes we need a code range.
  43082. // To extract it current and last mapping is used.
  43083. // Here we store the last mapping.
  43084. var lastMapping = null;
  43085. aSourceMapConsumer.eachMapping(function (mapping) {
  43086. if (lastMapping !== null) {
  43087. // We add the code from "lastMapping" to "mapping":
  43088. // First check if there is a new line in between.
  43089. if (lastGeneratedLine < mapping.generatedLine) {
  43090. // Associate first line with "lastMapping"
  43091. addMappingWithCode(lastMapping, shiftNextLine());
  43092. lastGeneratedLine++;
  43093. lastGeneratedColumn = 0;
  43094. // The remaining code is added without mapping
  43095. } else {
  43096. // There is no new line in between.
  43097. // Associate the code between "lastGeneratedColumn" and
  43098. // "mapping.generatedColumn" with "lastMapping"
  43099. var nextLine = remainingLines[remainingLinesIndex] || '';
  43100. var code = nextLine.substr(0, mapping.generatedColumn -
  43101. lastGeneratedColumn);
  43102. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  43103. lastGeneratedColumn);
  43104. lastGeneratedColumn = mapping.generatedColumn;
  43105. addMappingWithCode(lastMapping, code);
  43106. // No more remaining code, continue
  43107. lastMapping = mapping;
  43108. return;
  43109. }
  43110. }
  43111. // We add the generated code until the first mapping
  43112. // to the SourceNode without any mapping.
  43113. // Each line is added as separate string.
  43114. while (lastGeneratedLine < mapping.generatedLine) {
  43115. node.add(shiftNextLine());
  43116. lastGeneratedLine++;
  43117. }
  43118. if (lastGeneratedColumn < mapping.generatedColumn) {
  43119. var nextLine = remainingLines[remainingLinesIndex] || '';
  43120. node.add(nextLine.substr(0, mapping.generatedColumn));
  43121. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  43122. lastGeneratedColumn = mapping.generatedColumn;
  43123. }
  43124. lastMapping = mapping;
  43125. }, this);
  43126. // We have processed all mappings.
  43127. if (remainingLinesIndex < remainingLines.length) {
  43128. if (lastMapping) {
  43129. // Associate the remaining code in the current line with "lastMapping"
  43130. addMappingWithCode(lastMapping, shiftNextLine());
  43131. }
  43132. // and add the remaining lines without any mapping
  43133. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  43134. }
  43135. // Copy sourcesContent into SourceNode
  43136. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  43137. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  43138. if (content != null) {
  43139. if (aRelativePath != null) {
  43140. sourceFile = util.join(aRelativePath, sourceFile);
  43141. }
  43142. node.setSourceContent(sourceFile, content);
  43143. }
  43144. });
  43145. return node;
  43146. function addMappingWithCode(mapping, code) {
  43147. if (mapping === null || mapping.source === undefined) {
  43148. node.add(code);
  43149. } else {
  43150. var source = aRelativePath
  43151. ? util.join(aRelativePath, mapping.source)
  43152. : mapping.source;
  43153. node.add(new SourceNode(mapping.originalLine,
  43154. mapping.originalColumn,
  43155. source,
  43156. code,
  43157. mapping.name));
  43158. }
  43159. }
  43160. };
  43161. /**
  43162. * Add a chunk of generated JS to this source node.
  43163. *
  43164. * @param aChunk A string snippet of generated JS code, another instance of
  43165. * SourceNode, or an array where each member is one of those things.
  43166. */
  43167. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  43168. if (Array.isArray(aChunk)) {
  43169. aChunk.forEach(function (chunk) {
  43170. this.add(chunk);
  43171. }, this);
  43172. }
  43173. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  43174. if (aChunk) {
  43175. this.children.push(aChunk);
  43176. }
  43177. }
  43178. else {
  43179. throw new TypeError(
  43180. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  43181. );
  43182. }
  43183. return this;
  43184. };
  43185. /**
  43186. * Add a chunk of generated JS to the beginning of this source node.
  43187. *
  43188. * @param aChunk A string snippet of generated JS code, another instance of
  43189. * SourceNode, or an array where each member is one of those things.
  43190. */
  43191. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  43192. if (Array.isArray(aChunk)) {
  43193. for (var i = aChunk.length-1; i >= 0; i--) {
  43194. this.prepend(aChunk[i]);
  43195. }
  43196. }
  43197. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  43198. this.children.unshift(aChunk);
  43199. }
  43200. else {
  43201. throw new TypeError(
  43202. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  43203. );
  43204. }
  43205. return this;
  43206. };
  43207. /**
  43208. * Walk over the tree of JS snippets in this node and its children. The
  43209. * walking function is called once for each snippet of JS and is passed that
  43210. * snippet and the its original associated source's line/column location.
  43211. *
  43212. * @param aFn The traversal function.
  43213. */
  43214. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  43215. var chunk;
  43216. for (var i = 0, len = this.children.length; i < len; i++) {
  43217. chunk = this.children[i];
  43218. if (chunk[isSourceNode]) {
  43219. chunk.walk(aFn);
  43220. }
  43221. else {
  43222. if (chunk !== '') {
  43223. aFn(chunk, { source: this.source,
  43224. line: this.line,
  43225. column: this.column,
  43226. name: this.name });
  43227. }
  43228. }
  43229. }
  43230. };
  43231. /**
  43232. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  43233. * each of `this.children`.
  43234. *
  43235. * @param aSep The separator.
  43236. */
  43237. SourceNode.prototype.join = function SourceNode_join(aSep) {
  43238. var newChildren;
  43239. var i;
  43240. var len = this.children.length;
  43241. if (len > 0) {
  43242. newChildren = [];
  43243. for (i = 0; i < len-1; i++) {
  43244. newChildren.push(this.children[i]);
  43245. newChildren.push(aSep);
  43246. }
  43247. newChildren.push(this.children[i]);
  43248. this.children = newChildren;
  43249. }
  43250. return this;
  43251. };
  43252. /**
  43253. * Call String.prototype.replace on the very right-most source snippet. Useful
  43254. * for trimming whitespace from the end of a source node, etc.
  43255. *
  43256. * @param aPattern The pattern to replace.
  43257. * @param aReplacement The thing to replace the pattern with.
  43258. */
  43259. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  43260. var lastChild = this.children[this.children.length - 1];
  43261. if (lastChild[isSourceNode]) {
  43262. lastChild.replaceRight(aPattern, aReplacement);
  43263. }
  43264. else if (typeof lastChild === 'string') {
  43265. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  43266. }
  43267. else {
  43268. this.children.push(''.replace(aPattern, aReplacement));
  43269. }
  43270. return this;
  43271. };
  43272. /**
  43273. * Set the source content for a source file. This will be added to the SourceMapGenerator
  43274. * in the sourcesContent field.
  43275. *
  43276. * @param aSourceFile The filename of the source file
  43277. * @param aSourceContent The content of the source file
  43278. */
  43279. SourceNode.prototype.setSourceContent =
  43280. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  43281. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  43282. };
  43283. /**
  43284. * Walk over the tree of SourceNodes. The walking function is called for each
  43285. * source file content and is passed the filename and source content.
  43286. *
  43287. * @param aFn The traversal function.
  43288. */
  43289. SourceNode.prototype.walkSourceContents =
  43290. function SourceNode_walkSourceContents(aFn) {
  43291. for (var i = 0, len = this.children.length; i < len; i++) {
  43292. if (this.children[i][isSourceNode]) {
  43293. this.children[i].walkSourceContents(aFn);
  43294. }
  43295. }
  43296. var sources = Object.keys(this.sourceContents);
  43297. for (var i = 0, len = sources.length; i < len; i++) {
  43298. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  43299. }
  43300. };
  43301. /**
  43302. * Return the string representation of this source node. Walks over the tree
  43303. * and concatenates all the various snippets together to one string.
  43304. */
  43305. SourceNode.prototype.toString = function SourceNode_toString() {
  43306. var str = "";
  43307. this.walk(function (chunk) {
  43308. str += chunk;
  43309. });
  43310. return str;
  43311. };
  43312. /**
  43313. * Returns the string representation of this source node along with a source
  43314. * map.
  43315. */
  43316. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  43317. var generated = {
  43318. code: "",
  43319. line: 1,
  43320. column: 0
  43321. };
  43322. var map = new SourceMapGenerator(aArgs);
  43323. var sourceMappingActive = false;
  43324. var lastOriginalSource = null;
  43325. var lastOriginalLine = null;
  43326. var lastOriginalColumn = null;
  43327. var lastOriginalName = null;
  43328. this.walk(function (chunk, original) {
  43329. generated.code += chunk;
  43330. if (original.source !== null
  43331. && original.line !== null
  43332. && original.column !== null) {
  43333. if(lastOriginalSource !== original.source
  43334. || lastOriginalLine !== original.line
  43335. || lastOriginalColumn !== original.column
  43336. || lastOriginalName !== original.name) {
  43337. map.addMapping({
  43338. source: original.source,
  43339. original: {
  43340. line: original.line,
  43341. column: original.column
  43342. },
  43343. generated: {
  43344. line: generated.line,
  43345. column: generated.column
  43346. },
  43347. name: original.name
  43348. });
  43349. }
  43350. lastOriginalSource = original.source;
  43351. lastOriginalLine = original.line;
  43352. lastOriginalColumn = original.column;
  43353. lastOriginalName = original.name;
  43354. sourceMappingActive = true;
  43355. } else if (sourceMappingActive) {
  43356. map.addMapping({
  43357. generated: {
  43358. line: generated.line,
  43359. column: generated.column
  43360. }
  43361. });
  43362. lastOriginalSource = null;
  43363. sourceMappingActive = false;
  43364. }
  43365. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  43366. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  43367. generated.line++;
  43368. generated.column = 0;
  43369. // Mappings end at eol
  43370. if (idx + 1 === length) {
  43371. lastOriginalSource = null;
  43372. sourceMappingActive = false;
  43373. } else if (sourceMappingActive) {
  43374. map.addMapping({
  43375. source: original.source,
  43376. original: {
  43377. line: original.line,
  43378. column: original.column
  43379. },
  43380. generated: {
  43381. line: generated.line,
  43382. column: generated.column
  43383. },
  43384. name: original.name
  43385. });
  43386. }
  43387. } else {
  43388. generated.column++;
  43389. }
  43390. }
  43391. });
  43392. this.walkSourceContents(function (sourceFile, sourceContent) {
  43393. map.setSourceContent(sourceFile, sourceContent);
  43394. });
  43395. return { code: generated.code, map: map };
  43396. };
  43397. sourceNode.SourceNode = SourceNode;
  43398. return sourceNode;
  43399. }
  43400. /*
  43401. * Copyright 2009-2011 Mozilla Foundation and contributors
  43402. * Licensed under the New BSD license. See LICENSE.txt or:
  43403. * http://opensource.org/licenses/BSD-3-Clause
  43404. */
  43405. var hasRequiredSourceMap;
  43406. function requireSourceMap () {
  43407. if (hasRequiredSourceMap) return sourceMap;
  43408. hasRequiredSourceMap = 1;
  43409. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  43410. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  43411. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  43412. return sourceMap;
  43413. }
  43414. var mergeSourceMap;
  43415. var hasRequiredMergeSourceMap;
  43416. function requireMergeSourceMap () {
  43417. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  43418. hasRequiredMergeSourceMap = 1;
  43419. var sourceMap = /*@__PURE__*/ requireSourceMap();
  43420. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  43421. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  43422. mergeSourceMap = merge;
  43423. /**
  43424. * Merge old source map and new source map and return merged.
  43425. * If old or new source map value is falsy, return another one as it is.
  43426. *
  43427. * @param {object|string} [oldMap] old source map object
  43428. * @param {object|string} [newmap] new source map object
  43429. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  43430. */
  43431. function merge(oldMap, newMap) {
  43432. if (!oldMap) return newMap
  43433. if (!newMap) return oldMap
  43434. var oldMapConsumer = new SourceMapConsumer(oldMap);
  43435. var newMapConsumer = new SourceMapConsumer(newMap);
  43436. var mergedMapGenerator = new SourceMapGenerator();
  43437. // iterate on new map and overwrite original position of new map with one of old map
  43438. newMapConsumer.eachMapping(function(m) {
  43439. // pass when `originalLine` is null.
  43440. // It occurs in case that the node does not have origin in original code.
  43441. if (m.originalLine == null) return
  43442. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  43443. line: m.originalLine,
  43444. column: m.originalColumn
  43445. });
  43446. if (origPosInOldMap.source == null) return
  43447. mergedMapGenerator.addMapping({
  43448. original: {
  43449. line: origPosInOldMap.line,
  43450. column: origPosInOldMap.column
  43451. },
  43452. generated: {
  43453. line: m.generatedLine,
  43454. column: m.generatedColumn
  43455. },
  43456. source: origPosInOldMap.source,
  43457. name: origPosInOldMap.name
  43458. });
  43459. });
  43460. var consumers = [oldMapConsumer, newMapConsumer];
  43461. consumers.forEach(function(consumer) {
  43462. consumer.sources.forEach(function(sourceFile) {
  43463. mergedMapGenerator._sources.add(sourceFile);
  43464. var sourceContent = consumer.sourceContentFor(sourceFile);
  43465. if (sourceContent != null) {
  43466. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  43467. }
  43468. });
  43469. });
  43470. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  43471. mergedMapGenerator._file = oldMap.file;
  43472. return JSON.parse(mergedMapGenerator.toString())
  43473. }
  43474. return mergeSourceMap;
  43475. }
  43476. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  43477. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  43478. var __defProp$5 = Object.defineProperty;
  43479. var __defProps$4 = Object.defineProperties;
  43480. var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
  43481. var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
  43482. var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
  43483. var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
  43484. var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  43485. var __spreadValues$5 = (a, b) => {
  43486. for (var prop in b || (b = {}))
  43487. if (__hasOwnProp$5.call(b, prop))
  43488. __defNormalProp$5(a, prop, b[prop]);
  43489. if (__getOwnPropSymbols$5)
  43490. for (var prop of __getOwnPropSymbols$5(b)) {
  43491. if (__propIsEnum$5.call(b, prop))
  43492. __defNormalProp$5(a, prop, b[prop]);
  43493. }
  43494. return a;
  43495. };
  43496. var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
  43497. const scss = (source, map, options, load = require) => {
  43498. const nodeSass = load("sass");
  43499. const { compileString, renderSync } = nodeSass;
  43500. const data = getSource(source, options.filename, options.additionalData);
  43501. let css;
  43502. let dependencies;
  43503. let sourceMap;
  43504. try {
  43505. if (compileString) {
  43506. const { pathToFileURL, fileURLToPath } = load("url");
  43507. const result = compileString(data, __spreadProps$4(__spreadValues$5({}, options), {
  43508. url: pathToFileURL(options.filename),
  43509. sourceMap: !!map
  43510. }));
  43511. css = result.css;
  43512. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  43513. sourceMap = map ? result.sourceMap : void 0;
  43514. } else {
  43515. const result = renderSync(__spreadProps$4(__spreadValues$5({}, options), {
  43516. data,
  43517. file: options.filename,
  43518. outFile: options.filename,
  43519. sourceMap: !!map
  43520. }));
  43521. css = result.css.toString();
  43522. dependencies = result.stats.includedFiles;
  43523. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  43524. }
  43525. if (map) {
  43526. return {
  43527. code: css,
  43528. errors: [],
  43529. dependencies,
  43530. map: merge(map, sourceMap)
  43531. };
  43532. }
  43533. return { code: css, errors: [], dependencies };
  43534. } catch (e) {
  43535. return { code: "", errors: [e], dependencies: [] };
  43536. }
  43537. };
  43538. const sass = (source, map, options, load) => scss(
  43539. source,
  43540. map,
  43541. __spreadProps$4(__spreadValues$5({}, options), {
  43542. indentedSyntax: true
  43543. }),
  43544. load
  43545. );
  43546. const less = (source, map, options, load = require) => {
  43547. const nodeLess = load("less");
  43548. let result;
  43549. let error = null;
  43550. nodeLess.render(
  43551. getSource(source, options.filename, options.additionalData),
  43552. __spreadProps$4(__spreadValues$5({}, options), { syncImport: true }),
  43553. (err, output) => {
  43554. error = err;
  43555. result = output;
  43556. }
  43557. );
  43558. if (error) return { code: "", errors: [error], dependencies: [] };
  43559. const dependencies = result.imports;
  43560. if (map) {
  43561. return {
  43562. code: result.css.toString(),
  43563. map: merge(map, result.map),
  43564. errors: [],
  43565. dependencies
  43566. };
  43567. }
  43568. return {
  43569. code: result.css.toString(),
  43570. errors: [],
  43571. dependencies
  43572. };
  43573. };
  43574. const styl = (source, map, options, load = require) => {
  43575. const nodeStylus = load("stylus");
  43576. try {
  43577. const ref = nodeStylus(source, options);
  43578. if (map) ref.set("sourcemap", { inline: false, comment: false });
  43579. const result = ref.render();
  43580. const dependencies = ref.deps();
  43581. if (map) {
  43582. return {
  43583. code: result,
  43584. map: merge(map, ref.sourcemap),
  43585. errors: [],
  43586. dependencies
  43587. };
  43588. }
  43589. return { code: result, errors: [], dependencies };
  43590. } catch (e) {
  43591. return { code: "", errors: [e], dependencies: [] };
  43592. }
  43593. };
  43594. function getSource(source, filename, additionalData) {
  43595. if (!additionalData) return source;
  43596. if (isFunction$1(additionalData)) {
  43597. return additionalData(source, filename);
  43598. }
  43599. return additionalData + source;
  43600. }
  43601. const processors = {
  43602. less,
  43603. sass,
  43604. scss,
  43605. styl,
  43606. stylus: styl
  43607. };
  43608. var __defProp$4 = Object.defineProperty;
  43609. var __defProps$3 = Object.defineProperties;
  43610. var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
  43611. var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
  43612. var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
  43613. var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
  43614. var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  43615. var __spreadValues$4 = (a, b) => {
  43616. for (var prop in b || (b = {}))
  43617. if (__hasOwnProp$4.call(b, prop))
  43618. __defNormalProp$4(a, prop, b[prop]);
  43619. if (__getOwnPropSymbols$4)
  43620. for (var prop of __getOwnPropSymbols$4(b)) {
  43621. if (__propIsEnum$4.call(b, prop))
  43622. __defNormalProp$4(a, prop, b[prop]);
  43623. }
  43624. return a;
  43625. };
  43626. var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
  43627. function compileStyle(options) {
  43628. return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), {
  43629. isAsync: false
  43630. }));
  43631. }
  43632. function compileStyleAsync(options) {
  43633. return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), {
  43634. isAsync: true
  43635. }));
  43636. }
  43637. function doCompileStyle(options) {
  43638. const {
  43639. filename,
  43640. id,
  43641. scoped = false,
  43642. trim = true,
  43643. isProd = false,
  43644. modules = false,
  43645. modulesOptions = {},
  43646. preprocessLang,
  43647. postcssOptions,
  43648. postcssPlugins
  43649. } = options;
  43650. const preprocessor = preprocessLang && processors[preprocessLang];
  43651. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  43652. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  43653. const source = preProcessedSource ? preProcessedSource.code : options.source;
  43654. const shortId = id.replace(/^data-v-/, "");
  43655. const longId = `data-v-${shortId}`;
  43656. const plugins = (postcssPlugins || []).slice();
  43657. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  43658. if (trim) {
  43659. plugins.push(trimPlugin());
  43660. }
  43661. if (scoped) {
  43662. plugins.push(scopedPlugin(longId));
  43663. }
  43664. let cssModules;
  43665. if (modules) {
  43666. {
  43667. throw new Error(
  43668. "[@vue/compiler-sfc] `modules` option is not supported in the browser build."
  43669. );
  43670. }
  43671. }
  43672. const postCSSOptions = __spreadProps$3(__spreadValues$4({}, postcssOptions), {
  43673. to: filename,
  43674. from: filename
  43675. });
  43676. if (map) {
  43677. postCSSOptions.map = {
  43678. inline: false,
  43679. annotation: false,
  43680. prev: map
  43681. };
  43682. }
  43683. let result;
  43684. let code;
  43685. let outMap;
  43686. const dependencies = new Set(
  43687. preProcessedSource ? preProcessedSource.dependencies : []
  43688. );
  43689. dependencies.delete(filename);
  43690. const errors = [];
  43691. if (preProcessedSource && preProcessedSource.errors.length) {
  43692. errors.push(...preProcessedSource.errors);
  43693. }
  43694. const recordPlainCssDependencies = (messages) => {
  43695. messages.forEach((msg) => {
  43696. if (msg.type === "dependency") {
  43697. dependencies.add(msg.file);
  43698. }
  43699. });
  43700. return dependencies;
  43701. };
  43702. try {
  43703. result = postcss(plugins).process(source, postCSSOptions);
  43704. if (options.isAsync) {
  43705. return result.then((result2) => ({
  43706. code: result2.css || "",
  43707. map: result2.map && result2.map.toJSON(),
  43708. errors,
  43709. modules: cssModules,
  43710. rawResult: result2,
  43711. dependencies: recordPlainCssDependencies(result2.messages)
  43712. })).catch((error) => ({
  43713. code: "",
  43714. map: void 0,
  43715. errors: [...errors, error],
  43716. rawResult: void 0,
  43717. dependencies
  43718. }));
  43719. }
  43720. recordPlainCssDependencies(result.messages);
  43721. code = result.css;
  43722. outMap = result.map;
  43723. } catch (e) {
  43724. errors.push(e);
  43725. }
  43726. return {
  43727. code: code || ``,
  43728. map: outMap && outMap.toJSON(),
  43729. errors,
  43730. rawResult: result,
  43731. dependencies
  43732. };
  43733. }
  43734. function preprocess(options, preprocessor) {
  43735. if (!options.preprocessCustomRequire) {
  43736. throw new Error(
  43737. `[@vue/compiler-sfc] Style preprocessing in the browser build must provide the \`preprocessCustomRequire\` option to return the in-browser version of the preprocessor.`
  43738. );
  43739. }
  43740. return preprocessor(
  43741. options.source,
  43742. options.inMap || options.map,
  43743. __spreadValues$4({
  43744. filename: options.filename
  43745. }, options.preprocessOptions),
  43746. options.preprocessCustomRequire
  43747. );
  43748. }
  43749. const UNKNOWN_TYPE = "Unknown";
  43750. function resolveObjectKey(node, computed) {
  43751. switch (node.type) {
  43752. case "StringLiteral":
  43753. case "NumericLiteral":
  43754. return String(node.value);
  43755. case "Identifier":
  43756. if (!computed) return node.name;
  43757. }
  43758. return void 0;
  43759. }
  43760. function concatStrings(strs) {
  43761. return strs.filter((s) => !!s).join(", ");
  43762. }
  43763. function isLiteralNode(node) {
  43764. return node.type.endsWith("Literal");
  43765. }
  43766. function isCallOf(node, test) {
  43767. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  43768. }
  43769. function toRuntimeTypeString(types) {
  43770. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  43771. }
  43772. function getImportedName(specifier) {
  43773. if (specifier.type === "ImportSpecifier")
  43774. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  43775. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  43776. return "default";
  43777. }
  43778. function getId(node) {
  43779. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  43780. }
  43781. function getStringLiteralKey(node) {
  43782. return node.computed ? node.key.type === "TemplateLiteral" && !node.key.expressions.length ? node.key.quasis.map((q) => q.value.cooked).join("") : null : node.key.type === "Identifier" ? node.key.name : node.key.type === "StringLiteral" ? node.key.value : node.key.type === "NumericLiteral" ? String(node.key.value) : null;
  43783. }
  43784. const normalize = (path.posix || path).normalize;
  43785. const windowsSlashRE = /\\/g;
  43786. function normalizePath(p) {
  43787. return normalize(p.replace(windowsSlashRE, "/"));
  43788. }
  43789. const joinPaths = (path.posix || path).join;
  43790. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  43791. function getEscapedPropName(key) {
  43792. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  43793. }
  43794. const isJS = (...langs) => langs.some((lang) => lang === "js" || lang === "jsx");
  43795. const isTS = (...langs) => langs.some((lang) => lang === "ts" || lang === "tsx");
  43796. function analyzeScriptBindings(ast) {
  43797. for (const node of ast) {
  43798. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  43799. return analyzeBindingsFromOptions(node.declaration);
  43800. }
  43801. }
  43802. return {};
  43803. }
  43804. function analyzeBindingsFromOptions(node) {
  43805. const bindings = {};
  43806. Object.defineProperty(bindings, "__isScriptSetup", {
  43807. enumerable: false,
  43808. value: false
  43809. });
  43810. for (const property of node.properties) {
  43811. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  43812. if (property.key.name === "props") {
  43813. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  43814. bindings[key] = "props";
  43815. }
  43816. } else if (property.key.name === "inject") {
  43817. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  43818. bindings[key] = "options";
  43819. }
  43820. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  43821. for (const key of getObjectExpressionKeys(property.value)) {
  43822. bindings[key] = "options";
  43823. }
  43824. }
  43825. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  43826. for (const bodyItem of property.body.body) {
  43827. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  43828. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  43829. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  43830. }
  43831. }
  43832. }
  43833. }
  43834. }
  43835. return bindings;
  43836. }
  43837. function getObjectExpressionKeys(node) {
  43838. const keys = [];
  43839. for (const prop of node.properties) {
  43840. if (prop.type === "SpreadElement") continue;
  43841. const key = resolveObjectKey(prop.key, prop.computed);
  43842. if (key) keys.push(String(key));
  43843. }
  43844. return keys;
  43845. }
  43846. function getArrayExpressionKeys(node) {
  43847. const keys = [];
  43848. for (const element of node.elements) {
  43849. if (element && element.type === "StringLiteral") {
  43850. keys.push(element.value);
  43851. }
  43852. }
  43853. return keys;
  43854. }
  43855. function getObjectOrArrayExpressionKeys(value) {
  43856. if (value.type === "ArrayExpression") {
  43857. return getArrayExpressionKeys(value);
  43858. }
  43859. if (value.type === "ObjectExpression") {
  43860. return getObjectExpressionKeys(value);
  43861. }
  43862. return [];
  43863. }
  43864. // src/vlq.ts
  43865. var comma = ",".charCodeAt(0);
  43866. var semicolon = ";".charCodeAt(0);
  43867. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  43868. var intToChar = new Uint8Array(64);
  43869. var charToInt = new Uint8Array(128);
  43870. for (let i = 0; i < chars.length; i++) {
  43871. const c = chars.charCodeAt(i);
  43872. intToChar[i] = c;
  43873. charToInt[c] = i;
  43874. }
  43875. function encodeInteger(builder, num, relative) {
  43876. let delta = num - relative;
  43877. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  43878. do {
  43879. let clamped = delta & 31;
  43880. delta >>>= 5;
  43881. if (delta > 0) clamped |= 32;
  43882. builder.write(intToChar[clamped]);
  43883. } while (delta > 0);
  43884. return num;
  43885. }
  43886. // src/strings.ts
  43887. var bufLength = 1024 * 16;
  43888. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
  43889. decode(buf) {
  43890. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  43891. return out.toString();
  43892. }
  43893. } : {
  43894. decode(buf) {
  43895. let out = "";
  43896. for (let i = 0; i < buf.length; i++) {
  43897. out += String.fromCharCode(buf[i]);
  43898. }
  43899. return out;
  43900. }
  43901. };
  43902. var StringWriter = class {
  43903. constructor() {
  43904. this.pos = 0;
  43905. this.out = "";
  43906. this.buffer = new Uint8Array(bufLength);
  43907. }
  43908. write(v) {
  43909. const { buffer } = this;
  43910. buffer[this.pos++] = v;
  43911. if (this.pos === bufLength) {
  43912. this.out += td.decode(buffer);
  43913. this.pos = 0;
  43914. }
  43915. }
  43916. flush() {
  43917. const { buffer, out, pos } = this;
  43918. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  43919. }
  43920. };
  43921. function encode(decoded) {
  43922. const writer = new StringWriter();
  43923. let sourcesIndex = 0;
  43924. let sourceLine = 0;
  43925. let sourceColumn = 0;
  43926. let namesIndex = 0;
  43927. for (let i = 0; i < decoded.length; i++) {
  43928. const line = decoded[i];
  43929. if (i > 0) writer.write(semicolon);
  43930. if (line.length === 0) continue;
  43931. let genColumn = 0;
  43932. for (let j = 0; j < line.length; j++) {
  43933. const segment = line[j];
  43934. if (j > 0) writer.write(comma);
  43935. genColumn = encodeInteger(writer, segment[0], genColumn);
  43936. if (segment.length === 1) continue;
  43937. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  43938. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  43939. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  43940. if (segment.length === 4) continue;
  43941. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  43942. }
  43943. }
  43944. return writer.flush();
  43945. }
  43946. class BitSet {
  43947. constructor(arg) {
  43948. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  43949. }
  43950. add(n) {
  43951. this.bits[n >> 5] |= 1 << (n & 31);
  43952. }
  43953. has(n) {
  43954. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  43955. }
  43956. }
  43957. class Chunk {
  43958. constructor(start, end, content) {
  43959. this.start = start;
  43960. this.end = end;
  43961. this.original = content;
  43962. this.intro = '';
  43963. this.outro = '';
  43964. this.content = content;
  43965. this.storeName = false;
  43966. this.edited = false;
  43967. {
  43968. this.previous = null;
  43969. this.next = null;
  43970. }
  43971. }
  43972. appendLeft(content) {
  43973. this.outro += content;
  43974. }
  43975. appendRight(content) {
  43976. this.intro = this.intro + content;
  43977. }
  43978. clone() {
  43979. const chunk = new Chunk(this.start, this.end, this.original);
  43980. chunk.intro = this.intro;
  43981. chunk.outro = this.outro;
  43982. chunk.content = this.content;
  43983. chunk.storeName = this.storeName;
  43984. chunk.edited = this.edited;
  43985. return chunk;
  43986. }
  43987. contains(index) {
  43988. return this.start < index && index < this.end;
  43989. }
  43990. eachNext(fn) {
  43991. let chunk = this;
  43992. while (chunk) {
  43993. fn(chunk);
  43994. chunk = chunk.next;
  43995. }
  43996. }
  43997. eachPrevious(fn) {
  43998. let chunk = this;
  43999. while (chunk) {
  44000. fn(chunk);
  44001. chunk = chunk.previous;
  44002. }
  44003. }
  44004. edit(content, storeName, contentOnly) {
  44005. this.content = content;
  44006. if (!contentOnly) {
  44007. this.intro = '';
  44008. this.outro = '';
  44009. }
  44010. this.storeName = storeName;
  44011. this.edited = true;
  44012. return this;
  44013. }
  44014. prependLeft(content) {
  44015. this.outro = content + this.outro;
  44016. }
  44017. prependRight(content) {
  44018. this.intro = content + this.intro;
  44019. }
  44020. reset() {
  44021. this.intro = '';
  44022. this.outro = '';
  44023. if (this.edited) {
  44024. this.content = this.original;
  44025. this.storeName = false;
  44026. this.edited = false;
  44027. }
  44028. }
  44029. split(index) {
  44030. const sliceIndex = index - this.start;
  44031. const originalBefore = this.original.slice(0, sliceIndex);
  44032. const originalAfter = this.original.slice(sliceIndex);
  44033. this.original = originalBefore;
  44034. const newChunk = new Chunk(index, this.end, originalAfter);
  44035. newChunk.outro = this.outro;
  44036. this.outro = '';
  44037. this.end = index;
  44038. if (this.edited) {
  44039. // after split we should save the edit content record into the correct chunk
  44040. // to make sure sourcemap correct
  44041. // For example:
  44042. // ' test'.trim()
  44043. // split -> ' ' + 'test'
  44044. // ✔️ edit -> '' + 'test'
  44045. // ✖️ edit -> 'test' + ''
  44046. // TODO is this block necessary?...
  44047. newChunk.edit('', false);
  44048. this.content = '';
  44049. } else {
  44050. this.content = originalBefore;
  44051. }
  44052. newChunk.next = this.next;
  44053. if (newChunk.next) newChunk.next.previous = newChunk;
  44054. newChunk.previous = this;
  44055. this.next = newChunk;
  44056. return newChunk;
  44057. }
  44058. toString() {
  44059. return this.intro + this.content + this.outro;
  44060. }
  44061. trimEnd(rx) {
  44062. this.outro = this.outro.replace(rx, '');
  44063. if (this.outro.length) return true;
  44064. const trimmed = this.content.replace(rx, '');
  44065. if (trimmed.length) {
  44066. if (trimmed !== this.content) {
  44067. this.split(this.start + trimmed.length).edit('', undefined, true);
  44068. if (this.edited) {
  44069. // save the change, if it has been edited
  44070. this.edit(trimmed, this.storeName, true);
  44071. }
  44072. }
  44073. return true;
  44074. } else {
  44075. this.edit('', undefined, true);
  44076. this.intro = this.intro.replace(rx, '');
  44077. if (this.intro.length) return true;
  44078. }
  44079. }
  44080. trimStart(rx) {
  44081. this.intro = this.intro.replace(rx, '');
  44082. if (this.intro.length) return true;
  44083. const trimmed = this.content.replace(rx, '');
  44084. if (trimmed.length) {
  44085. if (trimmed !== this.content) {
  44086. const newChunk = this.split(this.end - trimmed.length);
  44087. if (this.edited) {
  44088. // save the change, if it has been edited
  44089. newChunk.edit(trimmed, this.storeName, true);
  44090. }
  44091. this.edit('', undefined, true);
  44092. }
  44093. return true;
  44094. } else {
  44095. this.edit('', undefined, true);
  44096. this.outro = this.outro.replace(rx, '');
  44097. if (this.outro.length) return true;
  44098. }
  44099. }
  44100. }
  44101. function getBtoa() {
  44102. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  44103. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  44104. } else if (typeof Buffer === 'function') {
  44105. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  44106. } else {
  44107. return () => {
  44108. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  44109. };
  44110. }
  44111. }
  44112. const btoa = /*#__PURE__*/ getBtoa();
  44113. class SourceMap {
  44114. constructor(properties) {
  44115. this.version = 3;
  44116. this.file = properties.file;
  44117. this.sources = properties.sources;
  44118. this.sourcesContent = properties.sourcesContent;
  44119. this.names = properties.names;
  44120. this.mappings = encode(properties.mappings);
  44121. if (typeof properties.x_google_ignoreList !== 'undefined') {
  44122. this.x_google_ignoreList = properties.x_google_ignoreList;
  44123. }
  44124. if (typeof properties.debugId !== 'undefined') {
  44125. this.debugId = properties.debugId;
  44126. }
  44127. }
  44128. toString() {
  44129. return JSON.stringify(this);
  44130. }
  44131. toUrl() {
  44132. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  44133. }
  44134. }
  44135. function guessIndent(code) {
  44136. const lines = code.split('\n');
  44137. const tabbed = lines.filter((line) => /^\t+/.test(line));
  44138. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  44139. if (tabbed.length === 0 && spaced.length === 0) {
  44140. return null;
  44141. }
  44142. // More lines tabbed than spaced? Assume tabs, and
  44143. // default to tabs in the case of a tie (or nothing
  44144. // to go on)
  44145. if (tabbed.length >= spaced.length) {
  44146. return '\t';
  44147. }
  44148. // Otherwise, we need to guess the multiple
  44149. const min = spaced.reduce((previous, current) => {
  44150. const numSpaces = /^ +/.exec(current)[0].length;
  44151. return Math.min(numSpaces, previous);
  44152. }, Infinity);
  44153. return new Array(min + 1).join(' ');
  44154. }
  44155. function getRelativePath(from, to) {
  44156. const fromParts = from.split(/[/\\]/);
  44157. const toParts = to.split(/[/\\]/);
  44158. fromParts.pop(); // get dirname
  44159. while (fromParts[0] === toParts[0]) {
  44160. fromParts.shift();
  44161. toParts.shift();
  44162. }
  44163. if (fromParts.length) {
  44164. let i = fromParts.length;
  44165. while (i--) fromParts[i] = '..';
  44166. }
  44167. return fromParts.concat(toParts).join('/');
  44168. }
  44169. const toString = Object.prototype.toString;
  44170. function isObject(thing) {
  44171. return toString.call(thing) === '[object Object]';
  44172. }
  44173. function getLocator(source) {
  44174. const originalLines = source.split('\n');
  44175. const lineOffsets = [];
  44176. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  44177. lineOffsets.push(pos);
  44178. pos += originalLines[i].length + 1;
  44179. }
  44180. return function locate(index) {
  44181. let i = 0;
  44182. let j = lineOffsets.length;
  44183. while (i < j) {
  44184. const m = (i + j) >> 1;
  44185. if (index < lineOffsets[m]) {
  44186. j = m;
  44187. } else {
  44188. i = m + 1;
  44189. }
  44190. }
  44191. const line = i - 1;
  44192. const column = index - lineOffsets[line];
  44193. return { line, column };
  44194. };
  44195. }
  44196. const wordRegex = /\w/;
  44197. class Mappings {
  44198. constructor(hires) {
  44199. this.hires = hires;
  44200. this.generatedCodeLine = 0;
  44201. this.generatedCodeColumn = 0;
  44202. this.raw = [];
  44203. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  44204. this.pending = null;
  44205. }
  44206. addEdit(sourceIndex, content, loc, nameIndex) {
  44207. if (content.length) {
  44208. const contentLengthMinusOne = content.length - 1;
  44209. let contentLineEnd = content.indexOf('\n', 0);
  44210. let previousContentLineEnd = -1;
  44211. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  44212. // else code afterwards would fill one line too many
  44213. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  44214. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  44215. if (nameIndex >= 0) {
  44216. segment.push(nameIndex);
  44217. }
  44218. this.rawSegments.push(segment);
  44219. this.generatedCodeLine += 1;
  44220. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  44221. this.generatedCodeColumn = 0;
  44222. previousContentLineEnd = contentLineEnd;
  44223. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  44224. }
  44225. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  44226. if (nameIndex >= 0) {
  44227. segment.push(nameIndex);
  44228. }
  44229. this.rawSegments.push(segment);
  44230. this.advance(content.slice(previousContentLineEnd + 1));
  44231. } else if (this.pending) {
  44232. this.rawSegments.push(this.pending);
  44233. this.advance(content);
  44234. }
  44235. this.pending = null;
  44236. }
  44237. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  44238. let originalCharIndex = chunk.start;
  44239. let first = true;
  44240. // when iterating each char, check if it's in a word boundary
  44241. let charInHiresBoundary = false;
  44242. while (originalCharIndex < chunk.end) {
  44243. if (original[originalCharIndex] === '\n') {
  44244. loc.line += 1;
  44245. loc.column = 0;
  44246. this.generatedCodeLine += 1;
  44247. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  44248. this.generatedCodeColumn = 0;
  44249. first = true;
  44250. charInHiresBoundary = false;
  44251. } else {
  44252. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  44253. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  44254. if (this.hires === 'boundary') {
  44255. // in hires "boundary", group segments per word boundary than per char
  44256. if (wordRegex.test(original[originalCharIndex])) {
  44257. // for first char in the boundary found, start the boundary by pushing a segment
  44258. if (!charInHiresBoundary) {
  44259. this.rawSegments.push(segment);
  44260. charInHiresBoundary = true;
  44261. }
  44262. } else {
  44263. // for non-word char, end the boundary by pushing a segment
  44264. this.rawSegments.push(segment);
  44265. charInHiresBoundary = false;
  44266. }
  44267. } else {
  44268. this.rawSegments.push(segment);
  44269. }
  44270. }
  44271. loc.column += 1;
  44272. this.generatedCodeColumn += 1;
  44273. first = false;
  44274. }
  44275. originalCharIndex += 1;
  44276. }
  44277. this.pending = null;
  44278. }
  44279. advance(str) {
  44280. if (!str) return;
  44281. const lines = str.split('\n');
  44282. if (lines.length > 1) {
  44283. for (let i = 0; i < lines.length - 1; i++) {
  44284. this.generatedCodeLine++;
  44285. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  44286. }
  44287. this.generatedCodeColumn = 0;
  44288. }
  44289. this.generatedCodeColumn += lines[lines.length - 1].length;
  44290. }
  44291. }
  44292. const n = '\n';
  44293. const warned = {
  44294. insertLeft: false,
  44295. insertRight: false,
  44296. storeName: false,
  44297. };
  44298. class MagicString {
  44299. constructor(string, options = {}) {
  44300. const chunk = new Chunk(0, string.length, string);
  44301. Object.defineProperties(this, {
  44302. original: { writable: true, value: string },
  44303. outro: { writable: true, value: '' },
  44304. intro: { writable: true, value: '' },
  44305. firstChunk: { writable: true, value: chunk },
  44306. lastChunk: { writable: true, value: chunk },
  44307. lastSearchedChunk: { writable: true, value: chunk },
  44308. byStart: { writable: true, value: {} },
  44309. byEnd: { writable: true, value: {} },
  44310. filename: { writable: true, value: options.filename },
  44311. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  44312. sourcemapLocations: { writable: true, value: new BitSet() },
  44313. storedNames: { writable: true, value: {} },
  44314. indentStr: { writable: true, value: undefined },
  44315. ignoreList: { writable: true, value: options.ignoreList },
  44316. offset: { writable: true, value: options.offset || 0 },
  44317. });
  44318. this.byStart[0] = chunk;
  44319. this.byEnd[string.length] = chunk;
  44320. }
  44321. addSourcemapLocation(char) {
  44322. this.sourcemapLocations.add(char);
  44323. }
  44324. append(content) {
  44325. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  44326. this.outro += content;
  44327. return this;
  44328. }
  44329. appendLeft(index, content) {
  44330. index = index + this.offset;
  44331. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  44332. this._split(index);
  44333. const chunk = this.byEnd[index];
  44334. if (chunk) {
  44335. chunk.appendLeft(content);
  44336. } else {
  44337. this.intro += content;
  44338. }
  44339. return this;
  44340. }
  44341. appendRight(index, content) {
  44342. index = index + this.offset;
  44343. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  44344. this._split(index);
  44345. const chunk = this.byStart[index];
  44346. if (chunk) {
  44347. chunk.appendRight(content);
  44348. } else {
  44349. this.outro += content;
  44350. }
  44351. return this;
  44352. }
  44353. clone() {
  44354. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  44355. let originalChunk = this.firstChunk;
  44356. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  44357. while (originalChunk) {
  44358. cloned.byStart[clonedChunk.start] = clonedChunk;
  44359. cloned.byEnd[clonedChunk.end] = clonedChunk;
  44360. const nextOriginalChunk = originalChunk.next;
  44361. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  44362. if (nextClonedChunk) {
  44363. clonedChunk.next = nextClonedChunk;
  44364. nextClonedChunk.previous = clonedChunk;
  44365. clonedChunk = nextClonedChunk;
  44366. }
  44367. originalChunk = nextOriginalChunk;
  44368. }
  44369. cloned.lastChunk = clonedChunk;
  44370. if (this.indentExclusionRanges) {
  44371. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  44372. }
  44373. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  44374. cloned.intro = this.intro;
  44375. cloned.outro = this.outro;
  44376. return cloned;
  44377. }
  44378. generateDecodedMap(options) {
  44379. options = options || {};
  44380. const sourceIndex = 0;
  44381. const names = Object.keys(this.storedNames);
  44382. const mappings = new Mappings(options.hires);
  44383. const locate = getLocator(this.original);
  44384. if (this.intro) {
  44385. mappings.advance(this.intro);
  44386. }
  44387. this.firstChunk.eachNext((chunk) => {
  44388. const loc = locate(chunk.start);
  44389. if (chunk.intro.length) mappings.advance(chunk.intro);
  44390. if (chunk.edited) {
  44391. mappings.addEdit(
  44392. sourceIndex,
  44393. chunk.content,
  44394. loc,
  44395. chunk.storeName ? names.indexOf(chunk.original) : -1,
  44396. );
  44397. } else {
  44398. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  44399. }
  44400. if (chunk.outro.length) mappings.advance(chunk.outro);
  44401. });
  44402. if (this.outro) {
  44403. mappings.advance(this.outro);
  44404. }
  44405. return {
  44406. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  44407. sources: [
  44408. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  44409. ],
  44410. sourcesContent: options.includeContent ? [this.original] : undefined,
  44411. names,
  44412. mappings: mappings.raw,
  44413. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  44414. };
  44415. }
  44416. generateMap(options) {
  44417. return new SourceMap(this.generateDecodedMap(options));
  44418. }
  44419. _ensureindentStr() {
  44420. if (this.indentStr === undefined) {
  44421. this.indentStr = guessIndent(this.original);
  44422. }
  44423. }
  44424. _getRawIndentString() {
  44425. this._ensureindentStr();
  44426. return this.indentStr;
  44427. }
  44428. getIndentString() {
  44429. this._ensureindentStr();
  44430. return this.indentStr === null ? '\t' : this.indentStr;
  44431. }
  44432. indent(indentStr, options) {
  44433. const pattern = /^[^\r\n]/gm;
  44434. if (isObject(indentStr)) {
  44435. options = indentStr;
  44436. indentStr = undefined;
  44437. }
  44438. if (indentStr === undefined) {
  44439. this._ensureindentStr();
  44440. indentStr = this.indentStr || '\t';
  44441. }
  44442. if (indentStr === '') return this; // noop
  44443. options = options || {};
  44444. // Process exclusion ranges
  44445. const isExcluded = {};
  44446. if (options.exclude) {
  44447. const exclusions =
  44448. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  44449. exclusions.forEach((exclusion) => {
  44450. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  44451. isExcluded[i] = true;
  44452. }
  44453. });
  44454. }
  44455. let shouldIndentNextCharacter = options.indentStart !== false;
  44456. const replacer = (match) => {
  44457. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  44458. shouldIndentNextCharacter = true;
  44459. return match;
  44460. };
  44461. this.intro = this.intro.replace(pattern, replacer);
  44462. let charIndex = 0;
  44463. let chunk = this.firstChunk;
  44464. while (chunk) {
  44465. const end = chunk.end;
  44466. if (chunk.edited) {
  44467. if (!isExcluded[charIndex]) {
  44468. chunk.content = chunk.content.replace(pattern, replacer);
  44469. if (chunk.content.length) {
  44470. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  44471. }
  44472. }
  44473. } else {
  44474. charIndex = chunk.start;
  44475. while (charIndex < end) {
  44476. if (!isExcluded[charIndex]) {
  44477. const char = this.original[charIndex];
  44478. if (char === '\n') {
  44479. shouldIndentNextCharacter = true;
  44480. } else if (char !== '\r' && shouldIndentNextCharacter) {
  44481. shouldIndentNextCharacter = false;
  44482. if (charIndex === chunk.start) {
  44483. chunk.prependRight(indentStr);
  44484. } else {
  44485. this._splitChunk(chunk, charIndex);
  44486. chunk = chunk.next;
  44487. chunk.prependRight(indentStr);
  44488. }
  44489. }
  44490. }
  44491. charIndex += 1;
  44492. }
  44493. }
  44494. charIndex = chunk.end;
  44495. chunk = chunk.next;
  44496. }
  44497. this.outro = this.outro.replace(pattern, replacer);
  44498. return this;
  44499. }
  44500. insert() {
  44501. throw new Error(
  44502. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  44503. );
  44504. }
  44505. insertLeft(index, content) {
  44506. if (!warned.insertLeft) {
  44507. console.warn(
  44508. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  44509. );
  44510. warned.insertLeft = true;
  44511. }
  44512. return this.appendLeft(index, content);
  44513. }
  44514. insertRight(index, content) {
  44515. if (!warned.insertRight) {
  44516. console.warn(
  44517. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  44518. );
  44519. warned.insertRight = true;
  44520. }
  44521. return this.prependRight(index, content);
  44522. }
  44523. move(start, end, index) {
  44524. start = start + this.offset;
  44525. end = end + this.offset;
  44526. index = index + this.offset;
  44527. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  44528. this._split(start);
  44529. this._split(end);
  44530. this._split(index);
  44531. const first = this.byStart[start];
  44532. const last = this.byEnd[end];
  44533. const oldLeft = first.previous;
  44534. const oldRight = last.next;
  44535. const newRight = this.byStart[index];
  44536. if (!newRight && last === this.lastChunk) return this;
  44537. const newLeft = newRight ? newRight.previous : this.lastChunk;
  44538. if (oldLeft) oldLeft.next = oldRight;
  44539. if (oldRight) oldRight.previous = oldLeft;
  44540. if (newLeft) newLeft.next = first;
  44541. if (newRight) newRight.previous = last;
  44542. if (!first.previous) this.firstChunk = last.next;
  44543. if (!last.next) {
  44544. this.lastChunk = first.previous;
  44545. this.lastChunk.next = null;
  44546. }
  44547. first.previous = newLeft;
  44548. last.next = newRight || null;
  44549. if (!newLeft) this.firstChunk = first;
  44550. if (!newRight) this.lastChunk = last;
  44551. return this;
  44552. }
  44553. overwrite(start, end, content, options) {
  44554. options = options || {};
  44555. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  44556. }
  44557. update(start, end, content, options) {
  44558. start = start + this.offset;
  44559. end = end + this.offset;
  44560. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  44561. if (this.original.length !== 0) {
  44562. while (start < 0) start += this.original.length;
  44563. while (end < 0) end += this.original.length;
  44564. }
  44565. if (end > this.original.length) throw new Error('end is out of bounds');
  44566. if (start === end)
  44567. throw new Error(
  44568. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  44569. );
  44570. this._split(start);
  44571. this._split(end);
  44572. if (options === true) {
  44573. if (!warned.storeName) {
  44574. console.warn(
  44575. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  44576. );
  44577. warned.storeName = true;
  44578. }
  44579. options = { storeName: true };
  44580. }
  44581. const storeName = options !== undefined ? options.storeName : false;
  44582. const overwrite = options !== undefined ? options.overwrite : false;
  44583. if (storeName) {
  44584. const original = this.original.slice(start, end);
  44585. Object.defineProperty(this.storedNames, original, {
  44586. writable: true,
  44587. value: true,
  44588. enumerable: true,
  44589. });
  44590. }
  44591. const first = this.byStart[start];
  44592. const last = this.byEnd[end];
  44593. if (first) {
  44594. let chunk = first;
  44595. while (chunk !== last) {
  44596. if (chunk.next !== this.byStart[chunk.end]) {
  44597. throw new Error('Cannot overwrite across a split point');
  44598. }
  44599. chunk = chunk.next;
  44600. chunk.edit('', false);
  44601. }
  44602. first.edit(content, storeName, !overwrite);
  44603. } else {
  44604. // must be inserting at the end
  44605. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  44606. // TODO last chunk in the array may not be the last chunk, if it's moved...
  44607. last.next = newChunk;
  44608. newChunk.previous = last;
  44609. }
  44610. return this;
  44611. }
  44612. prepend(content) {
  44613. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  44614. this.intro = content + this.intro;
  44615. return this;
  44616. }
  44617. prependLeft(index, content) {
  44618. index = index + this.offset;
  44619. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  44620. this._split(index);
  44621. const chunk = this.byEnd[index];
  44622. if (chunk) {
  44623. chunk.prependLeft(content);
  44624. } else {
  44625. this.intro = content + this.intro;
  44626. }
  44627. return this;
  44628. }
  44629. prependRight(index, content) {
  44630. index = index + this.offset;
  44631. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  44632. this._split(index);
  44633. const chunk = this.byStart[index];
  44634. if (chunk) {
  44635. chunk.prependRight(content);
  44636. } else {
  44637. this.outro = content + this.outro;
  44638. }
  44639. return this;
  44640. }
  44641. remove(start, end) {
  44642. start = start + this.offset;
  44643. end = end + this.offset;
  44644. if (this.original.length !== 0) {
  44645. while (start < 0) start += this.original.length;
  44646. while (end < 0) end += this.original.length;
  44647. }
  44648. if (start === end) return this;
  44649. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  44650. if (start > end) throw new Error('end must be greater than start');
  44651. this._split(start);
  44652. this._split(end);
  44653. let chunk = this.byStart[start];
  44654. while (chunk) {
  44655. chunk.intro = '';
  44656. chunk.outro = '';
  44657. chunk.edit('');
  44658. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  44659. }
  44660. return this;
  44661. }
  44662. reset(start, end) {
  44663. start = start + this.offset;
  44664. end = end + this.offset;
  44665. if (this.original.length !== 0) {
  44666. while (start < 0) start += this.original.length;
  44667. while (end < 0) end += this.original.length;
  44668. }
  44669. if (start === end) return this;
  44670. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  44671. if (start > end) throw new Error('end must be greater than start');
  44672. this._split(start);
  44673. this._split(end);
  44674. let chunk = this.byStart[start];
  44675. while (chunk) {
  44676. chunk.reset();
  44677. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  44678. }
  44679. return this;
  44680. }
  44681. lastChar() {
  44682. if (this.outro.length) return this.outro[this.outro.length - 1];
  44683. let chunk = this.lastChunk;
  44684. do {
  44685. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  44686. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  44687. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  44688. } while ((chunk = chunk.previous));
  44689. if (this.intro.length) return this.intro[this.intro.length - 1];
  44690. return '';
  44691. }
  44692. lastLine() {
  44693. let lineIndex = this.outro.lastIndexOf(n);
  44694. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  44695. let lineStr = this.outro;
  44696. let chunk = this.lastChunk;
  44697. do {
  44698. if (chunk.outro.length > 0) {
  44699. lineIndex = chunk.outro.lastIndexOf(n);
  44700. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  44701. lineStr = chunk.outro + lineStr;
  44702. }
  44703. if (chunk.content.length > 0) {
  44704. lineIndex = chunk.content.lastIndexOf(n);
  44705. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  44706. lineStr = chunk.content + lineStr;
  44707. }
  44708. if (chunk.intro.length > 0) {
  44709. lineIndex = chunk.intro.lastIndexOf(n);
  44710. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  44711. lineStr = chunk.intro + lineStr;
  44712. }
  44713. } while ((chunk = chunk.previous));
  44714. lineIndex = this.intro.lastIndexOf(n);
  44715. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  44716. return this.intro + lineStr;
  44717. }
  44718. slice(start = 0, end = this.original.length - this.offset) {
  44719. start = start + this.offset;
  44720. end = end + this.offset;
  44721. if (this.original.length !== 0) {
  44722. while (start < 0) start += this.original.length;
  44723. while (end < 0) end += this.original.length;
  44724. }
  44725. let result = '';
  44726. // find start chunk
  44727. let chunk = this.firstChunk;
  44728. while (chunk && (chunk.start > start || chunk.end <= start)) {
  44729. // found end chunk before start
  44730. if (chunk.start < end && chunk.end >= end) {
  44731. return result;
  44732. }
  44733. chunk = chunk.next;
  44734. }
  44735. if (chunk && chunk.edited && chunk.start !== start)
  44736. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  44737. const startChunk = chunk;
  44738. while (chunk) {
  44739. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  44740. result += chunk.intro;
  44741. }
  44742. const containsEnd = chunk.start < end && chunk.end >= end;
  44743. if (containsEnd && chunk.edited && chunk.end !== end)
  44744. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  44745. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  44746. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  44747. result += chunk.content.slice(sliceStart, sliceEnd);
  44748. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  44749. result += chunk.outro;
  44750. }
  44751. if (containsEnd) {
  44752. break;
  44753. }
  44754. chunk = chunk.next;
  44755. }
  44756. return result;
  44757. }
  44758. // TODO deprecate this? not really very useful
  44759. snip(start, end) {
  44760. const clone = this.clone();
  44761. clone.remove(0, start);
  44762. clone.remove(end, clone.original.length);
  44763. return clone;
  44764. }
  44765. _split(index) {
  44766. if (this.byStart[index] || this.byEnd[index]) return;
  44767. let chunk = this.lastSearchedChunk;
  44768. let previousChunk = chunk;
  44769. const searchForward = index > chunk.end;
  44770. while (chunk) {
  44771. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  44772. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  44773. // Prevent infinite loop (e.g. via empty chunks, where start === end)
  44774. if (chunk === previousChunk) return;
  44775. previousChunk = chunk;
  44776. }
  44777. }
  44778. _splitChunk(chunk, index) {
  44779. if (chunk.edited && chunk.content.length) {
  44780. // zero-length edited chunks are a special case (overlapping replacements)
  44781. const loc = getLocator(this.original)(index);
  44782. throw new Error(
  44783. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  44784. );
  44785. }
  44786. const newChunk = chunk.split(index);
  44787. this.byEnd[index] = chunk;
  44788. this.byStart[index] = newChunk;
  44789. this.byEnd[newChunk.end] = newChunk;
  44790. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  44791. this.lastSearchedChunk = chunk;
  44792. return true;
  44793. }
  44794. toString() {
  44795. let str = this.intro;
  44796. let chunk = this.firstChunk;
  44797. while (chunk) {
  44798. str += chunk.toString();
  44799. chunk = chunk.next;
  44800. }
  44801. return str + this.outro;
  44802. }
  44803. isEmpty() {
  44804. let chunk = this.firstChunk;
  44805. do {
  44806. if (
  44807. (chunk.intro.length && chunk.intro.trim()) ||
  44808. (chunk.content.length && chunk.content.trim()) ||
  44809. (chunk.outro.length && chunk.outro.trim())
  44810. )
  44811. return false;
  44812. } while ((chunk = chunk.next));
  44813. return true;
  44814. }
  44815. length() {
  44816. let chunk = this.firstChunk;
  44817. let length = 0;
  44818. do {
  44819. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  44820. } while ((chunk = chunk.next));
  44821. return length;
  44822. }
  44823. trimLines() {
  44824. return this.trim('[\\r\\n]');
  44825. }
  44826. trim(charType) {
  44827. return this.trimStart(charType).trimEnd(charType);
  44828. }
  44829. trimEndAborted(charType) {
  44830. const rx = new RegExp((charType || '\\s') + '+$');
  44831. this.outro = this.outro.replace(rx, '');
  44832. if (this.outro.length) return true;
  44833. let chunk = this.lastChunk;
  44834. do {
  44835. const end = chunk.end;
  44836. const aborted = chunk.trimEnd(rx);
  44837. // if chunk was trimmed, we have a new lastChunk
  44838. if (chunk.end !== end) {
  44839. if (this.lastChunk === chunk) {
  44840. this.lastChunk = chunk.next;
  44841. }
  44842. this.byEnd[chunk.end] = chunk;
  44843. this.byStart[chunk.next.start] = chunk.next;
  44844. this.byEnd[chunk.next.end] = chunk.next;
  44845. }
  44846. if (aborted) return true;
  44847. chunk = chunk.previous;
  44848. } while (chunk);
  44849. return false;
  44850. }
  44851. trimEnd(charType) {
  44852. this.trimEndAborted(charType);
  44853. return this;
  44854. }
  44855. trimStartAborted(charType) {
  44856. const rx = new RegExp('^' + (charType || '\\s') + '+');
  44857. this.intro = this.intro.replace(rx, '');
  44858. if (this.intro.length) return true;
  44859. let chunk = this.firstChunk;
  44860. do {
  44861. const end = chunk.end;
  44862. const aborted = chunk.trimStart(rx);
  44863. if (chunk.end !== end) {
  44864. // special case...
  44865. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  44866. this.byEnd[chunk.end] = chunk;
  44867. this.byStart[chunk.next.start] = chunk.next;
  44868. this.byEnd[chunk.next.end] = chunk.next;
  44869. }
  44870. if (aborted) return true;
  44871. chunk = chunk.next;
  44872. } while (chunk);
  44873. return false;
  44874. }
  44875. trimStart(charType) {
  44876. this.trimStartAborted(charType);
  44877. return this;
  44878. }
  44879. hasChanged() {
  44880. return this.original !== this.toString();
  44881. }
  44882. _replaceRegexp(searchValue, replacement) {
  44883. function getReplacement(match, str) {
  44884. if (typeof replacement === 'string') {
  44885. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  44886. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  44887. if (i === '$') return '$';
  44888. if (i === '&') return match[0];
  44889. const num = +i;
  44890. if (num < match.length) return match[+i];
  44891. return `$${i}`;
  44892. });
  44893. } else {
  44894. return replacement(...match, match.index, str, match.groups);
  44895. }
  44896. }
  44897. function matchAll(re, str) {
  44898. let match;
  44899. const matches = [];
  44900. while ((match = re.exec(str))) {
  44901. matches.push(match);
  44902. }
  44903. return matches;
  44904. }
  44905. if (searchValue.global) {
  44906. const matches = matchAll(searchValue, this.original);
  44907. matches.forEach((match) => {
  44908. if (match.index != null) {
  44909. const replacement = getReplacement(match, this.original);
  44910. if (replacement !== match[0]) {
  44911. this.overwrite(match.index, match.index + match[0].length, replacement);
  44912. }
  44913. }
  44914. });
  44915. } else {
  44916. const match = this.original.match(searchValue);
  44917. if (match && match.index != null) {
  44918. const replacement = getReplacement(match, this.original);
  44919. if (replacement !== match[0]) {
  44920. this.overwrite(match.index, match.index + match[0].length, replacement);
  44921. }
  44922. }
  44923. }
  44924. return this;
  44925. }
  44926. _replaceString(string, replacement) {
  44927. const { original } = this;
  44928. const index = original.indexOf(string);
  44929. if (index !== -1) {
  44930. if (typeof replacement === 'function') {
  44931. replacement = replacement(string, index, original);
  44932. }
  44933. if (string !== replacement) {
  44934. this.overwrite(index, index + string.length, replacement);
  44935. }
  44936. }
  44937. return this;
  44938. }
  44939. replace(searchValue, replacement) {
  44940. if (typeof searchValue === 'string') {
  44941. return this._replaceString(searchValue, replacement);
  44942. }
  44943. return this._replaceRegexp(searchValue, replacement);
  44944. }
  44945. _replaceAllString(string, replacement) {
  44946. const { original } = this;
  44947. const stringLength = string.length;
  44948. for (
  44949. let index = original.indexOf(string);
  44950. index !== -1;
  44951. index = original.indexOf(string, index + stringLength)
  44952. ) {
  44953. const previous = original.slice(index, index + stringLength);
  44954. let _replacement = replacement;
  44955. if (typeof replacement === 'function') {
  44956. _replacement = replacement(previous, index, original);
  44957. }
  44958. if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
  44959. }
  44960. return this;
  44961. }
  44962. replaceAll(searchValue, replacement) {
  44963. if (typeof searchValue === 'string') {
  44964. return this._replaceAllString(searchValue, replacement);
  44965. }
  44966. if (!searchValue.global) {
  44967. throw new TypeError(
  44968. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  44969. );
  44970. }
  44971. return this._replaceRegexp(searchValue, replacement);
  44972. }
  44973. }
  44974. var _a, _b;
  44975. class ScriptCompileContext {
  44976. constructor(descriptor, options) {
  44977. this.descriptor = descriptor;
  44978. this.options = options;
  44979. this.isCE = false;
  44980. this.source = this.descriptor.source;
  44981. this.filename = this.descriptor.filename;
  44982. this.s = new MagicString(this.source);
  44983. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  44984. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  44985. this.userImports = /* @__PURE__ */ Object.create(null);
  44986. // macros presence check
  44987. this.hasDefinePropsCall = false;
  44988. this.hasDefineEmitCall = false;
  44989. this.hasDefineExposeCall = false;
  44990. this.hasDefaultExportName = false;
  44991. this.hasDefaultExportRender = false;
  44992. this.hasDefineOptionsCall = false;
  44993. this.hasDefineSlotsCall = false;
  44994. this.hasDefineModelCall = false;
  44995. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  44996. // defineModel
  44997. this.modelDecls = /* @__PURE__ */ Object.create(null);
  44998. // codegen
  44999. this.bindingMetadata = {};
  45000. this.helperImports = /* @__PURE__ */ new Set();
  45001. const { script, scriptSetup } = descriptor;
  45002. const scriptLang = script && script.lang;
  45003. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  45004. this.isJS = isJS(scriptLang, scriptSetupLang);
  45005. this.isTS = isTS(scriptLang, scriptSetupLang);
  45006. const customElement = options.customElement;
  45007. const filename = this.descriptor.filename;
  45008. if (customElement) {
  45009. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  45010. }
  45011. const plugins = resolveParserPlugins(
  45012. scriptLang || scriptSetupLang,
  45013. options.babelParserPlugins
  45014. );
  45015. function parse(input, offset) {
  45016. try {
  45017. return libExports.parse(input, {
  45018. plugins,
  45019. sourceType: "module"
  45020. }).program;
  45021. } catch (e) {
  45022. e.message = `[vue/compiler-sfc] ${e.message}
  45023. ${descriptor.filename}
  45024. ${generateCodeFrame(
  45025. descriptor.source,
  45026. e.pos + offset,
  45027. e.pos + offset + 1
  45028. )}`;
  45029. throw e;
  45030. }
  45031. }
  45032. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  45033. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  45034. }
  45035. helper(key) {
  45036. this.helperImports.add(key);
  45037. return `_${key}`;
  45038. }
  45039. getString(node, scriptSetup = true) {
  45040. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  45041. return block.content.slice(node.start, node.end);
  45042. }
  45043. warn(msg, node, scope) {
  45044. warn(generateError(msg, node, this, scope));
  45045. }
  45046. error(msg, node, scope) {
  45047. throw new Error(
  45048. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  45049. );
  45050. }
  45051. }
  45052. function generateError(msg, node, ctx, scope) {
  45053. const offset = scope ? scope.offset : ctx.startOffset;
  45054. return `${msg}
  45055. ${(scope || ctx.descriptor).filename}
  45056. ${generateCodeFrame(
  45057. (scope || ctx.descriptor).source,
  45058. node.start + offset,
  45059. node.end + offset
  45060. )}`;
  45061. }
  45062. function resolveParserPlugins(lang, userPlugins, dts = false) {
  45063. const plugins = [];
  45064. if (!userPlugins || !userPlugins.some(
  45065. (p) => p === "importAssertions" || p === "importAttributes" || isArray$3(p) && p[0] === "importAttributes"
  45066. )) {
  45067. plugins.push("importAttributes");
  45068. }
  45069. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  45070. plugins.push("jsx");
  45071. } else if (userPlugins) {
  45072. userPlugins = userPlugins.filter((p) => p !== "jsx");
  45073. }
  45074. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "cts" || lang === "mtsx") {
  45075. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  45076. if (!userPlugins || !userPlugins.includes("decorators")) {
  45077. plugins.push("decorators-legacy");
  45078. }
  45079. }
  45080. if (userPlugins) {
  45081. plugins.push(...userPlugins);
  45082. }
  45083. return plugins;
  45084. }
  45085. function rewriteDefault(input, as, parserPlugins) {
  45086. const ast = libExports.parse(input, {
  45087. sourceType: "module",
  45088. plugins: resolveParserPlugins("js", parserPlugins)
  45089. }).program.body;
  45090. const s = new MagicString(input);
  45091. rewriteDefaultAST(ast, s, as);
  45092. return s.toString();
  45093. }
  45094. function rewriteDefaultAST(ast, s, as) {
  45095. if (!hasDefaultExport(ast)) {
  45096. s.append(`
  45097. const ${as} = {}`);
  45098. return;
  45099. }
  45100. ast.forEach((node) => {
  45101. if (node.type === "ExportDefaultDeclaration") {
  45102. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  45103. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  45104. s.overwrite(start, node.declaration.id.start, ` class `);
  45105. s.append(`
  45106. const ${as} = ${node.declaration.id.name}`);
  45107. } else {
  45108. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  45109. }
  45110. } else if (node.type === "ExportNamedDeclaration") {
  45111. for (const specifier of node.specifiers) {
  45112. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  45113. if (node.source) {
  45114. if (specifier.local.name === "default") {
  45115. s.prepend(
  45116. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  45117. `
  45118. );
  45119. const end2 = specifierEnd(s, specifier.local.end, node.end);
  45120. s.remove(specifier.start, end2);
  45121. s.append(`
  45122. const ${as} = __VUE_DEFAULT__`);
  45123. continue;
  45124. } else {
  45125. s.prepend(
  45126. `import { ${s.slice(
  45127. specifier.local.start,
  45128. specifier.local.end
  45129. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  45130. `
  45131. );
  45132. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  45133. s.remove(specifier.start, end2);
  45134. s.append(`
  45135. const ${as} = __VUE_DEFAULT__`);
  45136. continue;
  45137. }
  45138. }
  45139. const end = specifierEnd(s, specifier.end, node.end);
  45140. s.remove(specifier.start, end);
  45141. s.append(`
  45142. const ${as} = ${specifier.local.name}`);
  45143. }
  45144. }
  45145. }
  45146. });
  45147. }
  45148. function hasDefaultExport(ast) {
  45149. for (const stmt of ast) {
  45150. if (stmt.type === "ExportDefaultDeclaration") {
  45151. return true;
  45152. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  45153. (spec) => spec.exported.name === "default"
  45154. )) {
  45155. return true;
  45156. }
  45157. }
  45158. return false;
  45159. }
  45160. function specifierEnd(s, end, nodeEnd) {
  45161. let hasCommas = false;
  45162. let oldEnd = end;
  45163. while (end < nodeEnd) {
  45164. if (/\s/.test(s.slice(end, end + 1))) {
  45165. end++;
  45166. } else if (s.slice(end, end + 1) === ",") {
  45167. end++;
  45168. hasCommas = true;
  45169. break;
  45170. } else if (s.slice(end, end + 1) === "}") {
  45171. break;
  45172. }
  45173. }
  45174. return hasCommas ? end : oldEnd;
  45175. }
  45176. var __defProp$3 = Object.defineProperty;
  45177. var __defProps$2 = Object.defineProperties;
  45178. var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
  45179. var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
  45180. var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
  45181. var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
  45182. var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  45183. var __spreadValues$3 = (a, b) => {
  45184. for (var prop in b || (b = {}))
  45185. if (__hasOwnProp$3.call(b, prop))
  45186. __defNormalProp$3(a, prop, b[prop]);
  45187. if (__getOwnPropSymbols$3)
  45188. for (var prop of __getOwnPropSymbols$3(b)) {
  45189. if (__propIsEnum$3.call(b, prop))
  45190. __defNormalProp$3(a, prop, b[prop]);
  45191. }
  45192. return a;
  45193. };
  45194. var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
  45195. const normalScriptDefaultVar = `__default__`;
  45196. function processNormalScript(ctx, scopeId) {
  45197. var _a;
  45198. const script = ctx.descriptor.script;
  45199. try {
  45200. let content = script.content;
  45201. let map = script.map;
  45202. const scriptAst = ctx.scriptAst;
  45203. const bindings = analyzeScriptBindings(scriptAst.body);
  45204. const { cssVars } = ctx.descriptor;
  45205. const { genDefaultAs, isProd } = ctx.options;
  45206. if (cssVars.length || genDefaultAs) {
  45207. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  45208. const s = new MagicString(content);
  45209. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  45210. content = s.toString();
  45211. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  45212. content += genNormalScriptCssVarsCode(
  45213. cssVars,
  45214. bindings,
  45215. scopeId,
  45216. !!isProd,
  45217. defaultVar
  45218. );
  45219. }
  45220. if (!genDefaultAs) {
  45221. content += `
  45222. export default ${defaultVar}`;
  45223. }
  45224. }
  45225. return __spreadProps$2(__spreadValues$3({}, script), {
  45226. content,
  45227. map,
  45228. bindings,
  45229. scriptAst: scriptAst.body
  45230. });
  45231. } catch (e) {
  45232. return script;
  45233. }
  45234. }
  45235. var __defProp$2 = Object.defineProperty;
  45236. var __defProps$1 = Object.defineProperties;
  45237. var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
  45238. var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
  45239. var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
  45240. var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
  45241. var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  45242. var __spreadValues$2 = (a, b) => {
  45243. for (var prop in b || (b = {}))
  45244. if (__hasOwnProp$2.call(b, prop))
  45245. __defNormalProp$2(a, prop, b[prop]);
  45246. if (__getOwnPropSymbols$2)
  45247. for (var prop of __getOwnPropSymbols$2(b)) {
  45248. if (__propIsEnum$2.call(b, prop))
  45249. __defNormalProp$2(a, prop, b[prop]);
  45250. }
  45251. return a;
  45252. };
  45253. var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
  45254. class TypeScope {
  45255. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  45256. this.filename = filename;
  45257. this.source = source;
  45258. this.offset = offset;
  45259. this.imports = imports;
  45260. this.types = types;
  45261. this.declares = declares;
  45262. this.isGenericScope = false;
  45263. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  45264. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  45265. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  45266. }
  45267. }
  45268. function recordScopeDep(ctx, scope) {
  45269. if (scope && scope.filename !== ctx.filename) {
  45270. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(scope.filename);
  45271. }
  45272. }
  45273. function recordResolvedElementDeps(ctx, { props }) {
  45274. for (const key in props) {
  45275. recordScopeDep(ctx, props[key]._ownerScope);
  45276. }
  45277. }
  45278. function resolveTypeElements(ctx, node, scope, typeParameters) {
  45279. const canCache = !typeParameters;
  45280. if (canCache && node._resolvedElements) {
  45281. recordResolvedElementDeps(ctx, node._resolvedElements);
  45282. return node._resolvedElements;
  45283. }
  45284. const resolved = innerResolveTypeElements(
  45285. ctx,
  45286. node,
  45287. node._ownerScope || scope || ctxToScope(ctx),
  45288. typeParameters
  45289. );
  45290. return canCache ? node._resolvedElements = resolved : resolved;
  45291. }
  45292. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  45293. var _a, _b;
  45294. if (hasVueIgnore(node)) {
  45295. if ((node.type === "TSIntersectionType" || node.type === "TSUnionType") && node.types.length > 1) {
  45296. return mergeElements(
  45297. [
  45298. { props: {} },
  45299. ...node.types.slice(1).map((t) => resolveTypeElements(ctx, t, scope, typeParameters))
  45300. ],
  45301. node.type
  45302. );
  45303. }
  45304. return { props: {} };
  45305. }
  45306. switch (node.type) {
  45307. case "TSTypeLiteral":
  45308. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  45309. case "TSInterfaceDeclaration":
  45310. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  45311. case "TSTypeAliasDeclaration":
  45312. case "TSTypeAnnotation":
  45313. case "TSParenthesizedType":
  45314. return resolveTypeElements(
  45315. ctx,
  45316. node.typeAnnotation,
  45317. scope,
  45318. typeParameters
  45319. );
  45320. case "TSFunctionType": {
  45321. return { props: {}, calls: [node] };
  45322. }
  45323. case "TSUnionType":
  45324. case "TSIntersectionType":
  45325. return mergeElements(
  45326. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  45327. node.type
  45328. );
  45329. case "TSMappedType":
  45330. return resolveMappedType(ctx, node, scope, typeParameters);
  45331. case "TSIndexedAccessType": {
  45332. const types = resolveIndexType(ctx, node, scope);
  45333. return mergeElements(
  45334. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  45335. "TSUnionType"
  45336. );
  45337. }
  45338. case "TSExpressionWithTypeArguments":
  45339. // referenced by interface extends
  45340. case "TSTypeReference": {
  45341. const typeName = getReferenceName(node);
  45342. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  45343. return resolveExtractPropTypes(
  45344. resolveTypeElements(
  45345. ctx,
  45346. node.typeParameters.params[0],
  45347. scope,
  45348. typeParameters
  45349. ),
  45350. scope
  45351. );
  45352. }
  45353. const resolved = resolveTypeReference(ctx, node, scope);
  45354. if (resolved) {
  45355. let typeParams;
  45356. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  45357. typeParams = /* @__PURE__ */ Object.create(null);
  45358. resolved.typeParameters.params.forEach((p, i) => {
  45359. let param = typeParameters && typeParameters[p.name];
  45360. if (!param) param = node.typeParameters.params[i];
  45361. typeParams[p.name] = param;
  45362. });
  45363. }
  45364. return resolveTypeElements(
  45365. ctx,
  45366. resolved,
  45367. resolved._ownerScope,
  45368. typeParams
  45369. );
  45370. } else {
  45371. if (typeof typeName === "string") {
  45372. if (typeParameters && typeParameters[typeName]) {
  45373. return resolveTypeElements(
  45374. ctx,
  45375. typeParameters[typeName],
  45376. scope,
  45377. typeParameters
  45378. );
  45379. }
  45380. if (
  45381. // @ts-expect-error
  45382. SupportedBuiltinsSet.has(typeName)
  45383. ) {
  45384. return resolveBuiltin(
  45385. ctx,
  45386. node,
  45387. typeName,
  45388. scope,
  45389. typeParameters
  45390. );
  45391. } else if (typeName === "ReturnType" && node.typeParameters) {
  45392. const ret = resolveReturnType(
  45393. ctx,
  45394. node.typeParameters.params[0],
  45395. scope
  45396. );
  45397. if (ret) {
  45398. return resolveTypeElements(ctx, ret, scope);
  45399. }
  45400. }
  45401. }
  45402. return ctx.error(
  45403. `Unresolvable type reference or unsupported built-in utility type`,
  45404. node,
  45405. scope
  45406. );
  45407. }
  45408. }
  45409. case "TSImportType": {
  45410. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  45411. return resolveExtractPropTypes(
  45412. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  45413. scope
  45414. );
  45415. }
  45416. const sourceScope = importSourceToScope(
  45417. ctx,
  45418. node.argument,
  45419. scope,
  45420. node.argument.value
  45421. );
  45422. const resolved = resolveTypeReference(ctx, node, sourceScope);
  45423. if (resolved) {
  45424. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  45425. }
  45426. break;
  45427. }
  45428. case "TSTypeQuery":
  45429. {
  45430. const resolved = resolveTypeReference(ctx, node, scope);
  45431. if (resolved) {
  45432. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  45433. }
  45434. }
  45435. break;
  45436. }
  45437. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  45438. }
  45439. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  45440. const res = { props: {} };
  45441. for (const e of elements) {
  45442. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  45443. if (typeParameters) {
  45444. scope = createChildScope(scope);
  45445. scope.isGenericScope = true;
  45446. Object.assign(scope.types, typeParameters);
  45447. }
  45448. e._ownerScope = scope;
  45449. const name = getStringLiteralKey(e);
  45450. if (name !== null) {
  45451. res.props[name] = e;
  45452. } else {
  45453. ctx.error(
  45454. `Unsupported computed key in type referenced by a macro`,
  45455. e.key,
  45456. scope
  45457. );
  45458. }
  45459. } else if (e.type === "TSCallSignatureDeclaration") {
  45460. (res.calls || (res.calls = [])).push(e);
  45461. }
  45462. }
  45463. return res;
  45464. }
  45465. function hasVueIgnore(node) {
  45466. return !!(node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore")));
  45467. }
  45468. function mergeElements(maps, type) {
  45469. if (maps.length === 1) return maps[0];
  45470. const res = { props: {} };
  45471. const { props: baseProps } = res;
  45472. for (const { props, calls } of maps) {
  45473. for (const key in props) {
  45474. if (!hasOwn(baseProps, key)) {
  45475. baseProps[key] = props[key];
  45476. } else {
  45477. baseProps[key] = createProperty(
  45478. baseProps[key].key,
  45479. {
  45480. type,
  45481. // @ts-expect-error
  45482. types: [baseProps[key], props[key]]
  45483. },
  45484. baseProps[key]._ownerScope,
  45485. baseProps[key].optional || props[key].optional
  45486. );
  45487. }
  45488. }
  45489. if (calls) {
  45490. (res.calls || (res.calls = [])).push(...calls);
  45491. }
  45492. }
  45493. return res;
  45494. }
  45495. function createProperty(key, typeAnnotation, scope, optional) {
  45496. return {
  45497. type: "TSPropertySignature",
  45498. key,
  45499. kind: "get",
  45500. optional,
  45501. typeAnnotation: {
  45502. type: "TSTypeAnnotation",
  45503. typeAnnotation
  45504. },
  45505. _ownerScope: scope
  45506. };
  45507. }
  45508. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  45509. const base = typeElementsToMap(
  45510. ctx,
  45511. node.body.body,
  45512. node._ownerScope,
  45513. typeParameters
  45514. );
  45515. if (node.extends) {
  45516. for (const ext of node.extends) {
  45517. try {
  45518. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  45519. for (const key in props) {
  45520. if (!hasOwn(base.props, key)) {
  45521. base.props[key] = props[key];
  45522. }
  45523. }
  45524. if (calls) {
  45525. ;
  45526. (base.calls || (base.calls = [])).push(...calls);
  45527. }
  45528. } catch (e) {
  45529. if (!ctx.silentOnExtendsFailure) {
  45530. ctx.error(
  45531. `Failed to resolve extends base type.
  45532. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  45533. interface Props extends /* @vue-ignore */ Base {}
  45534. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  45535. ext,
  45536. scope
  45537. );
  45538. }
  45539. }
  45540. }
  45541. }
  45542. return base;
  45543. }
  45544. function resolveMappedType(ctx, node, scope, typeParameters) {
  45545. const res = { props: {} };
  45546. let keys;
  45547. if (node.nameType) {
  45548. const { name, constraint } = node.typeParameter;
  45549. scope = createChildScope(scope);
  45550. Object.assign(scope.types, __spreadProps$1(__spreadValues$2({}, typeParameters), { [name]: constraint }));
  45551. keys = resolveStringType(ctx, node.nameType, scope);
  45552. } else {
  45553. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  45554. }
  45555. for (const key of keys) {
  45556. res.props[key] = createProperty(
  45557. {
  45558. type: "Identifier",
  45559. name: key
  45560. },
  45561. node.typeAnnotation,
  45562. scope,
  45563. !!node.optional
  45564. );
  45565. }
  45566. return res;
  45567. }
  45568. function resolveIndexType(ctx, node, scope) {
  45569. var _a, _b;
  45570. if (node.indexType.type === "TSNumberKeyword") {
  45571. return resolveArrayElementType(ctx, node.objectType, scope);
  45572. }
  45573. const { indexType, objectType } = node;
  45574. const types = [];
  45575. let keys;
  45576. let resolved;
  45577. if (indexType.type === "TSStringKeyword") {
  45578. resolved = resolveTypeElements(ctx, objectType, scope);
  45579. keys = Object.keys(resolved.props);
  45580. } else {
  45581. keys = resolveStringType(ctx, indexType, scope);
  45582. resolved = resolveTypeElements(ctx, objectType, scope);
  45583. }
  45584. for (const key of keys) {
  45585. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  45586. if (targetType) {
  45587. targetType._ownerScope = resolved.props[key]._ownerScope;
  45588. types.push(targetType);
  45589. }
  45590. }
  45591. return types;
  45592. }
  45593. function resolveArrayElementType(ctx, node, scope) {
  45594. if (node.type === "TSArrayType") {
  45595. return [node.elementType];
  45596. }
  45597. if (node.type === "TSTupleType") {
  45598. return node.elementTypes.map(
  45599. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  45600. );
  45601. }
  45602. if (node.type === "TSTypeReference") {
  45603. if (getReferenceName(node) === "Array" && node.typeParameters) {
  45604. return node.typeParameters.params;
  45605. } else {
  45606. const resolved = resolveTypeReference(ctx, node, scope);
  45607. if (resolved) {
  45608. return resolveArrayElementType(ctx, resolved, scope);
  45609. }
  45610. }
  45611. }
  45612. return ctx.error(
  45613. "Failed to resolve element type from target type",
  45614. node,
  45615. scope
  45616. );
  45617. }
  45618. function resolveStringType(ctx, node, scope, typeParameters) {
  45619. switch (node.type) {
  45620. case "StringLiteral":
  45621. return [node.value];
  45622. case "TSLiteralType":
  45623. return resolveStringType(ctx, node.literal, scope, typeParameters);
  45624. case "TSUnionType":
  45625. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  45626. case "TemplateLiteral": {
  45627. return resolveTemplateKeys(ctx, node, scope);
  45628. }
  45629. case "TSTypeReference": {
  45630. const resolved = resolveTypeReference(ctx, node, scope);
  45631. if (resolved) {
  45632. return resolveStringType(ctx, resolved, scope, typeParameters);
  45633. }
  45634. if (node.typeName.type === "Identifier") {
  45635. const name = node.typeName.name;
  45636. if (typeParameters && typeParameters[name]) {
  45637. return resolveStringType(
  45638. ctx,
  45639. typeParameters[name],
  45640. scope,
  45641. typeParameters
  45642. );
  45643. }
  45644. const getParam = (index = 0) => resolveStringType(
  45645. ctx,
  45646. node.typeParameters.params[index],
  45647. scope,
  45648. typeParameters
  45649. );
  45650. switch (name) {
  45651. case "Extract":
  45652. return getParam(1);
  45653. case "Exclude": {
  45654. const excluded = getParam(1);
  45655. return getParam().filter((s) => !excluded.includes(s));
  45656. }
  45657. case "Uppercase":
  45658. return getParam().map((s) => s.toUpperCase());
  45659. case "Lowercase":
  45660. return getParam().map((s) => s.toLowerCase());
  45661. case "Capitalize":
  45662. return getParam().map(capitalize);
  45663. case "Uncapitalize":
  45664. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  45665. default:
  45666. ctx.error(
  45667. "Unsupported type when resolving index type",
  45668. node.typeName,
  45669. scope
  45670. );
  45671. }
  45672. }
  45673. }
  45674. }
  45675. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  45676. }
  45677. function resolveTemplateKeys(ctx, node, scope) {
  45678. if (!node.expressions.length) {
  45679. return [node.quasis[0].value.raw];
  45680. }
  45681. const res = [];
  45682. const e = node.expressions[0];
  45683. const q = node.quasis[0];
  45684. const leading = q ? q.value.raw : ``;
  45685. const resolved = resolveStringType(ctx, e, scope);
  45686. const restResolved = resolveTemplateKeys(
  45687. ctx,
  45688. __spreadProps$1(__spreadValues$2({}, node), {
  45689. expressions: node.expressions.slice(1),
  45690. quasis: q ? node.quasis.slice(1) : node.quasis
  45691. }),
  45692. scope
  45693. );
  45694. for (const r of resolved) {
  45695. for (const rr of restResolved) {
  45696. res.push(leading + r + rr);
  45697. }
  45698. }
  45699. return res;
  45700. }
  45701. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  45702. "Partial",
  45703. "Required",
  45704. "Readonly",
  45705. "Pick",
  45706. "Omit"
  45707. ]);
  45708. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  45709. const t = resolveTypeElements(
  45710. ctx,
  45711. node.typeParameters.params[0],
  45712. scope,
  45713. typeParameters
  45714. );
  45715. switch (name) {
  45716. case "Partial": {
  45717. const res2 = { props: {}, calls: t.calls };
  45718. Object.keys(t.props).forEach((key) => {
  45719. res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: true });
  45720. });
  45721. return res2;
  45722. }
  45723. case "Required": {
  45724. const res2 = { props: {}, calls: t.calls };
  45725. Object.keys(t.props).forEach((key) => {
  45726. res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: false });
  45727. });
  45728. return res2;
  45729. }
  45730. case "Readonly":
  45731. return t;
  45732. case "Pick": {
  45733. const picked = resolveStringType(
  45734. ctx,
  45735. node.typeParameters.params[1],
  45736. scope,
  45737. typeParameters
  45738. );
  45739. const res2 = { props: {}, calls: t.calls };
  45740. for (const key of picked) {
  45741. res2.props[key] = t.props[key];
  45742. }
  45743. return res2;
  45744. }
  45745. case "Omit":
  45746. const omitted = resolveStringType(
  45747. ctx,
  45748. node.typeParameters.params[1],
  45749. scope,
  45750. typeParameters
  45751. );
  45752. const res = { props: {}, calls: t.calls };
  45753. for (const key in t.props) {
  45754. if (!omitted.includes(key)) {
  45755. res.props[key] = t.props[key];
  45756. }
  45757. }
  45758. return res;
  45759. }
  45760. }
  45761. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  45762. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  45763. if (canCache && node._resolvedReference) {
  45764. recordScopeDep(ctx, node._resolvedReference._ownerScope);
  45765. return node._resolvedReference;
  45766. }
  45767. const resolved = innerResolveTypeReference(
  45768. ctx,
  45769. scope || ctxToScope(ctx),
  45770. name || getReferenceName(node),
  45771. node,
  45772. onlyExported
  45773. );
  45774. return canCache ? node._resolvedReference = resolved : resolved;
  45775. }
  45776. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  45777. if (typeof name === "string") {
  45778. if (scope.imports[name]) {
  45779. return resolveTypeFromImport(ctx, node, name, scope);
  45780. } else {
  45781. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  45782. if (lookupSource[name]) {
  45783. return lookupSource[name];
  45784. } else {
  45785. const globalScopes = resolveGlobalScope(ctx);
  45786. if (globalScopes) {
  45787. for (const s of globalScopes) {
  45788. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  45789. if (src[name]) {
  45790. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  45791. const resolved = src[name];
  45792. if (resolved._ownerScope && resolved._ownerScope !== s) {
  45793. ctx.deps.add(resolved._ownerScope.filename);
  45794. }
  45795. return resolved;
  45796. }
  45797. }
  45798. }
  45799. }
  45800. }
  45801. } else {
  45802. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  45803. if (ns) {
  45804. if (ns.type !== "TSModuleDeclaration") {
  45805. ns = ns._ns;
  45806. }
  45807. if (ns) {
  45808. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  45809. return innerResolveTypeReference(
  45810. ctx,
  45811. childScope,
  45812. name.length > 2 ? name.slice(1) : name[name.length - 1],
  45813. node,
  45814. !ns.declare
  45815. );
  45816. }
  45817. }
  45818. }
  45819. }
  45820. function getReferenceName(node) {
  45821. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  45822. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  45823. return ref.name;
  45824. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  45825. return qualifiedNameToPath(ref);
  45826. } else {
  45827. return "default";
  45828. }
  45829. }
  45830. function qualifiedNameToPath(node) {
  45831. if (node.type === "Identifier") {
  45832. return [node.name];
  45833. } else {
  45834. return [...qualifiedNameToPath(node.left), node.right.name];
  45835. }
  45836. }
  45837. function resolveGlobalScope(ctx) {
  45838. if (ctx.options.globalTypeFiles) {
  45839. const fs = resolveFS(ctx);
  45840. if (!fs) {
  45841. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  45842. }
  45843. return ctx.options.globalTypeFiles.map(
  45844. (file) => fileToScope(ctx, normalizePath(file), true)
  45845. );
  45846. }
  45847. }
  45848. let ts;
  45849. let loadTS;
  45850. function registerTS(_loadTS) {
  45851. loadTS = () => {
  45852. try {
  45853. return _loadTS();
  45854. } catch (err) {
  45855. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  45856. throw new Error(
  45857. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "TypeScript" is installed as a project dependency.'
  45858. );
  45859. } else {
  45860. throw new Error(
  45861. "Failed to load TypeScript for resolving imported types."
  45862. );
  45863. }
  45864. }
  45865. };
  45866. }
  45867. function resolveFS(ctx) {
  45868. if (ctx.fs) {
  45869. return ctx.fs;
  45870. }
  45871. if (!ts && loadTS) {
  45872. ts = loadTS();
  45873. }
  45874. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  45875. if (!fs) {
  45876. return;
  45877. }
  45878. return ctx.fs = {
  45879. fileExists(file) {
  45880. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  45881. file = file.replace(/\.ts$/, "");
  45882. }
  45883. return fs.fileExists(file);
  45884. },
  45885. readFile(file) {
  45886. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  45887. file = file.replace(/\.ts$/, "");
  45888. }
  45889. return fs.readFile(file);
  45890. },
  45891. realpath: fs.realpath
  45892. };
  45893. }
  45894. function resolveTypeFromImport(ctx, node, name, scope) {
  45895. const { source, imported } = scope.imports[name];
  45896. const sourceScope = importSourceToScope(ctx, node, scope, source);
  45897. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  45898. }
  45899. function importSourceToScope(ctx, node, scope, source, trackDep = true) {
  45900. let fs;
  45901. try {
  45902. fs = resolveFS(ctx);
  45903. } catch (err) {
  45904. return ctx.error(err.message, node, scope);
  45905. }
  45906. if (!fs) {
  45907. return ctx.error(
  45908. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  45909. node,
  45910. scope
  45911. );
  45912. }
  45913. let resolved = scope.resolvedImportSources[source];
  45914. if (!resolved) {
  45915. if (source.startsWith("..")) {
  45916. const osSpecificJoinFn = joinPaths;
  45917. const filename = osSpecificJoinFn(dirname(scope.filename), source);
  45918. resolved = resolveExt(filename, fs);
  45919. } else if (source[0] === ".") {
  45920. const filename = joinPaths(dirname(scope.filename), source);
  45921. resolved = resolveExt(filename, fs);
  45922. } else {
  45923. {
  45924. return ctx.error(
  45925. `Type import from non-relative sources is not supported in the browser build.`,
  45926. node,
  45927. scope
  45928. );
  45929. }
  45930. }
  45931. if (!resolved && source[0] === "." && false) {
  45932. if (!ts) {
  45933. if (loadTS) ts = loadTS();
  45934. }
  45935. if (ts) {
  45936. resolved = resolveWithTS(scope.filename);
  45937. }
  45938. }
  45939. if (resolved) {
  45940. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  45941. }
  45942. }
  45943. if (resolved) {
  45944. if (trackDep) {
  45945. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  45946. }
  45947. return fileToScope(ctx, resolved);
  45948. } else {
  45949. return ctx.error(
  45950. `Failed to resolve import source ${JSON.stringify(source)}.`,
  45951. node,
  45952. scope
  45953. );
  45954. }
  45955. }
  45956. function resolveExt(filename, fs) {
  45957. let moduleType = "u";
  45958. if (filename.endsWith(".mjs")) {
  45959. moduleType = "m";
  45960. } else if (filename.endsWith(".cjs")) {
  45961. moduleType = "c";
  45962. }
  45963. filename = filename.replace(/\.[cm]?jsx?$/, "");
  45964. const tryResolve = (filename2) => {
  45965. if (fs.fileExists(filename2)) return filename2;
  45966. };
  45967. const resolveTs = () => tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`);
  45968. const resolveMts = () => tryResolve(filename + `.mts`) || tryResolve(filename + `.d.mts`);
  45969. const resolveCts = () => tryResolve(filename + `.cts`) || tryResolve(filename + `.d.cts`);
  45970. return tryResolve(filename) || // For explicit .mjs/.cjs imports, prefer .mts/.cts declarations first.
  45971. (moduleType === "m" ? resolveMts() || resolveTs() : moduleType === "c" ? resolveCts() || resolveTs() : resolveTs() || resolveMts() || resolveCts()) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.tsx`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  45972. }
  45973. const tsConfigCache = createCache();
  45974. const tsConfigRefMap = /* @__PURE__ */ new Map();
  45975. function resolveWithTS(containingFile, source, ts2, fs) {
  45976. return;
  45977. }
  45978. const fileToScopeCache = createCache();
  45979. const fileToGlobalScopeCache = createCache();
  45980. function invalidateTypeCache(filename) {
  45981. filename = normalizePath(filename);
  45982. fileToScopeCache.delete(filename);
  45983. fileToGlobalScopeCache.delete(filename);
  45984. tsConfigCache.delete(filename);
  45985. const affectedConfig = tsConfigRefMap.get(filename);
  45986. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  45987. }
  45988. function fileToScope(ctx, filename, asGlobal = false) {
  45989. const cache = asGlobal ? fileToGlobalScopeCache : fileToScopeCache;
  45990. const cached = cache.get(filename);
  45991. if (cached) {
  45992. return cached;
  45993. }
  45994. const fs = resolveFS(ctx);
  45995. const source = fs.readFile(filename) || "";
  45996. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  45997. const scope = new TypeScope(filename, source, 0, recordImports(body));
  45998. recordTypes(ctx, body, scope, asGlobal);
  45999. cache.set(filename, scope);
  46000. return scope;
  46001. }
  46002. function parseFile(filename, content, fs, parserPlugins) {
  46003. const ext = extname(filename);
  46004. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".cts" || ext === ".mtsx") {
  46005. return libExports.parse(content, {
  46006. plugins: resolveParserPlugins(
  46007. ext.slice(1),
  46008. parserPlugins,
  46009. /\.d\.[cm]?ts$/.test(filename)
  46010. ),
  46011. sourceType: "module"
  46012. }).program.body;
  46013. }
  46014. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  46015. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  46016. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  46017. if (hasArbitraryTypeDeclaration) {
  46018. return libExports.parse(fs.readFile(arbitraryTypeSource), {
  46019. plugins: resolveParserPlugins("ts", parserPlugins, true),
  46020. sourceType: "module"
  46021. }).program.body;
  46022. }
  46023. if (ext === ".vue") {
  46024. const {
  46025. descriptor: { script, scriptSetup }
  46026. } = parse$2(content);
  46027. if (!script && !scriptSetup) {
  46028. return [];
  46029. }
  46030. const scriptOffset = script ? script.loc.start.offset : Infinity;
  46031. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  46032. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  46033. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  46034. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  46035. if (secondBlock) {
  46036. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  46037. }
  46038. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  46039. return libExports.parse(scriptContent, {
  46040. plugins: resolveParserPlugins(lang, parserPlugins),
  46041. sourceType: "module"
  46042. }).program.body;
  46043. }
  46044. return [];
  46045. }
  46046. function ctxToScope(ctx) {
  46047. if (ctx.scope) {
  46048. return ctx.scope;
  46049. }
  46050. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  46051. const scope = new TypeScope(
  46052. ctx.filename,
  46053. ctx.source,
  46054. "startOffset" in ctx ? ctx.startOffset : 0,
  46055. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  46056. );
  46057. recordTypes(ctx, body, scope);
  46058. return ctx.scope = scope;
  46059. }
  46060. function moduleDeclToScope(ctx, node, parentScope) {
  46061. if (node._resolvedChildScope) {
  46062. return node._resolvedChildScope;
  46063. }
  46064. const scope = createChildScope(parentScope);
  46065. if (node.body.type === "TSModuleDeclaration") {
  46066. const decl = node.body;
  46067. decl._ownerScope = scope;
  46068. const id = getId(decl.id);
  46069. scope.types[id] = scope.exportedTypes[id] = decl;
  46070. } else {
  46071. recordTypes(ctx, node.body.body, scope);
  46072. }
  46073. return node._resolvedChildScope = scope;
  46074. }
  46075. function createChildScope(parentScope) {
  46076. return new TypeScope(
  46077. parentScope.filename,
  46078. parentScope.source,
  46079. parentScope.offset,
  46080. Object.create(parentScope.imports),
  46081. Object.create(parentScope.types),
  46082. Object.create(parentScope.declares)
  46083. );
  46084. }
  46085. const importExportRE = /^Import|^Export/;
  46086. function recordTypes(ctx, body, scope, asGlobal = false) {
  46087. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  46088. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  46089. for (const stmt of body) {
  46090. if (asGlobal) {
  46091. if (isAmbient) {
  46092. if (stmt.declare) {
  46093. recordType(stmt, types, declares);
  46094. }
  46095. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  46096. for (const s of stmt.body.body) {
  46097. if (s.type === "ExportNamedDeclaration") {
  46098. if (s.declaration) {
  46099. recordType(s.declaration, types, declares);
  46100. } else if (s.source) {
  46101. const sourceScope = importSourceToScope(
  46102. ctx,
  46103. s.source,
  46104. scope,
  46105. s.source.value,
  46106. false
  46107. );
  46108. for (const spec of s.specifiers) {
  46109. if (spec.type === "ExportSpecifier") {
  46110. const exported = getId(spec.exported);
  46111. const local = spec.local.name;
  46112. if (sourceScope.exportedTypes[local]) {
  46113. types[exported] = sourceScope.exportedTypes[local];
  46114. }
  46115. if (sourceScope.exportedDeclares[local]) {
  46116. declares[exported] = sourceScope.exportedDeclares[local];
  46117. }
  46118. }
  46119. }
  46120. }
  46121. } else if (s.type === "ExportAllDeclaration" && s.source) {
  46122. const sourceScope = importSourceToScope(
  46123. ctx,
  46124. s.source,
  46125. scope,
  46126. s.source.value,
  46127. false
  46128. );
  46129. Object.assign(types, sourceScope.exportedTypes);
  46130. Object.assign(declares, sourceScope.exportedDeclares);
  46131. } else {
  46132. recordType(s, types, declares);
  46133. }
  46134. }
  46135. }
  46136. } else {
  46137. recordType(stmt, types, declares);
  46138. }
  46139. }
  46140. if (!asGlobal) {
  46141. for (const stmt of body) {
  46142. if (stmt.type === "ExportNamedDeclaration") {
  46143. if (stmt.declaration) {
  46144. recordType(stmt.declaration, types, declares);
  46145. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  46146. } else {
  46147. for (const spec of stmt.specifiers) {
  46148. if (spec.type === "ExportSpecifier") {
  46149. const local = spec.local.name;
  46150. const exported = getId(spec.exported);
  46151. if (stmt.source) {
  46152. imports[exported] = {
  46153. source: stmt.source.value,
  46154. imported: local
  46155. };
  46156. exportedTypes[exported] = {
  46157. type: "TSTypeReference",
  46158. typeName: {
  46159. type: "Identifier",
  46160. name: local
  46161. },
  46162. _ownerScope: scope
  46163. };
  46164. } else if (types[local]) {
  46165. exportedTypes[exported] = types[local];
  46166. }
  46167. }
  46168. }
  46169. }
  46170. } else if (stmt.type === "ExportAllDeclaration") {
  46171. const sourceScope = importSourceToScope(
  46172. ctx,
  46173. stmt.source,
  46174. scope,
  46175. stmt.source.value
  46176. );
  46177. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  46178. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  46179. if (stmt.declaration.type !== "Identifier") {
  46180. recordType(stmt.declaration, types, declares, "default");
  46181. recordType(
  46182. stmt.declaration,
  46183. exportedTypes,
  46184. exportedDeclares,
  46185. "default"
  46186. );
  46187. } else if (types[stmt.declaration.name]) {
  46188. exportedTypes["default"] = types[stmt.declaration.name];
  46189. }
  46190. }
  46191. }
  46192. }
  46193. for (const key of Object.keys(types)) {
  46194. const node = types[key];
  46195. if (!node._ownerScope) node._ownerScope = scope;
  46196. if (node._ns && !node._ns._ownerScope) node._ns._ownerScope = scope;
  46197. }
  46198. for (const key of Object.keys(declares)) {
  46199. if (!declares[key]._ownerScope) declares[key]._ownerScope = scope;
  46200. }
  46201. }
  46202. function recordType(node, types, declares, overwriteId) {
  46203. switch (node.type) {
  46204. case "TSInterfaceDeclaration":
  46205. case "TSEnumDeclaration":
  46206. case "TSModuleDeclaration": {
  46207. if (node.type === "TSModuleDeclaration" && node.global) {
  46208. const body = node.body;
  46209. for (const s of body.body) {
  46210. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  46211. recordType(s.declaration, types, declares);
  46212. } else {
  46213. recordType(s, types, declares);
  46214. }
  46215. }
  46216. break;
  46217. }
  46218. const id = overwriteId || getId(node.id);
  46219. let existing = types[id];
  46220. if (existing) {
  46221. if (node.type === "TSModuleDeclaration") {
  46222. if (existing.type === "TSModuleDeclaration") {
  46223. mergeNamespaces(existing, node);
  46224. } else {
  46225. attachNamespace(existing, node);
  46226. }
  46227. break;
  46228. }
  46229. if (existing.type === "TSModuleDeclaration") {
  46230. types[id] = node;
  46231. attachNamespace(node, existing);
  46232. break;
  46233. }
  46234. if (existing.type !== node.type) {
  46235. break;
  46236. }
  46237. if (node.type === "TSInterfaceDeclaration") {
  46238. existing.body.body.push(...node.body.body);
  46239. } else {
  46240. existing.members.push(...node.members);
  46241. }
  46242. } else {
  46243. types[id] = node;
  46244. }
  46245. break;
  46246. }
  46247. case "ClassDeclaration":
  46248. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  46249. break;
  46250. case "TSTypeAliasDeclaration":
  46251. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  46252. break;
  46253. case "TSDeclareFunction":
  46254. if (node.id) declares[node.id.name] = node;
  46255. break;
  46256. case "VariableDeclaration": {
  46257. if (node.declare) {
  46258. for (const decl of node.declarations) {
  46259. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  46260. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  46261. }
  46262. }
  46263. }
  46264. break;
  46265. }
  46266. }
  46267. }
  46268. function mergeNamespaces(to, from) {
  46269. const toBody = to.body;
  46270. const fromBody = from.body;
  46271. if (toBody.type === "TSModuleDeclaration") {
  46272. if (fromBody.type === "TSModuleDeclaration") {
  46273. mergeNamespaces(toBody, fromBody);
  46274. } else {
  46275. fromBody.body.push({
  46276. type: "ExportNamedDeclaration",
  46277. declaration: toBody,
  46278. exportKind: "type",
  46279. specifiers: []
  46280. });
  46281. }
  46282. } else if (fromBody.type === "TSModuleDeclaration") {
  46283. toBody.body.push({
  46284. type: "ExportNamedDeclaration",
  46285. declaration: fromBody,
  46286. exportKind: "type",
  46287. specifiers: []
  46288. });
  46289. } else {
  46290. toBody.body.push(...fromBody.body);
  46291. }
  46292. }
  46293. function attachNamespace(to, ns) {
  46294. if (!to._ns) {
  46295. to._ns = ns;
  46296. } else {
  46297. mergeNamespaces(to._ns, ns);
  46298. }
  46299. }
  46300. function recordImports(body) {
  46301. const imports = /* @__PURE__ */ Object.create(null);
  46302. for (const s of body) {
  46303. recordImport(s, imports);
  46304. }
  46305. return imports;
  46306. }
  46307. function recordImport(node, imports) {
  46308. if (node.type !== "ImportDeclaration") {
  46309. return;
  46310. }
  46311. for (const s of node.specifiers) {
  46312. imports[s.local.name] = {
  46313. imported: getImportedName(s),
  46314. source: node.source.value
  46315. };
  46316. }
  46317. }
  46318. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, typeParameters) {
  46319. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  46320. return [UNKNOWN_TYPE];
  46321. }
  46322. const prevSilent = ctx.silentOnExtendsFailure;
  46323. ctx.silentOnExtendsFailure = true;
  46324. try {
  46325. switch (node.type) {
  46326. case "TSStringKeyword":
  46327. return ["String"];
  46328. case "TSNumberKeyword":
  46329. return ["Number"];
  46330. case "TSBooleanKeyword":
  46331. return ["Boolean"];
  46332. case "TSObjectKeyword":
  46333. return ["Object"];
  46334. case "TSNullKeyword":
  46335. return ["null"];
  46336. case "TSTypeLiteral":
  46337. case "TSInterfaceDeclaration": {
  46338. const types = /* @__PURE__ */ new Set();
  46339. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  46340. for (const m of members) {
  46341. if (isKeyOf) {
  46342. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  46343. types.add("Number");
  46344. } else if (m.type === "TSIndexSignature") {
  46345. const annotation = m.parameters[0].typeAnnotation;
  46346. if (annotation && annotation.type !== "Noop") {
  46347. const type = inferRuntimeType(
  46348. ctx,
  46349. annotation.typeAnnotation,
  46350. scope
  46351. )[0];
  46352. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  46353. types.add(type);
  46354. }
  46355. } else {
  46356. types.add("String");
  46357. }
  46358. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  46359. types.add("Function");
  46360. } else {
  46361. types.add("Object");
  46362. }
  46363. }
  46364. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  46365. }
  46366. case "TSPropertySignature":
  46367. if (node.typeAnnotation) {
  46368. return inferRuntimeType(
  46369. ctx,
  46370. node.typeAnnotation.typeAnnotation,
  46371. scope
  46372. );
  46373. }
  46374. break;
  46375. case "TSMethodSignature":
  46376. case "TSFunctionType":
  46377. return ["Function"];
  46378. case "TSArrayType":
  46379. case "TSTupleType":
  46380. return ["Array"];
  46381. case "TSLiteralType":
  46382. switch (node.literal.type) {
  46383. case "StringLiteral":
  46384. return ["String"];
  46385. case "BooleanLiteral":
  46386. return ["Boolean"];
  46387. case "NumericLiteral":
  46388. case "BigIntLiteral":
  46389. return ["Number"];
  46390. default:
  46391. return [UNKNOWN_TYPE];
  46392. }
  46393. case "TSTypeReference": {
  46394. let resolved;
  46395. try {
  46396. resolved = resolveTypeReference(ctx, node, scope);
  46397. } catch (e) {
  46398. }
  46399. if (resolved) {
  46400. if (resolved.type === "TSTypeAliasDeclaration") {
  46401. if (resolved.typeAnnotation.type === "TSFunctionType") {
  46402. return ["Function"];
  46403. }
  46404. if (node.typeParameters) {
  46405. const typeParams = /* @__PURE__ */ Object.create(null);
  46406. if (resolved.typeParameters) {
  46407. resolved.typeParameters.params.forEach((p, i) => {
  46408. typeParams[p.name] = node.typeParameters.params[i];
  46409. });
  46410. }
  46411. return inferRuntimeType(
  46412. ctx,
  46413. resolved.typeAnnotation,
  46414. resolved._ownerScope,
  46415. isKeyOf,
  46416. typeParams
  46417. );
  46418. }
  46419. }
  46420. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  46421. }
  46422. if (node.typeName.type === "Identifier") {
  46423. if (typeParameters && typeParameters[node.typeName.name]) {
  46424. return inferRuntimeType(
  46425. ctx,
  46426. typeParameters[node.typeName.name],
  46427. scope,
  46428. isKeyOf,
  46429. typeParameters
  46430. );
  46431. }
  46432. if (isKeyOf) {
  46433. switch (node.typeName.name) {
  46434. case "String":
  46435. case "Array":
  46436. case "ArrayLike":
  46437. case "Parameters":
  46438. case "ConstructorParameters":
  46439. case "ReadonlyArray":
  46440. return ["String", "Number"];
  46441. // TS built-in utility types
  46442. case "Record":
  46443. case "Partial":
  46444. case "Required":
  46445. case "Readonly":
  46446. if (node.typeParameters && node.typeParameters.params[0]) {
  46447. return inferRuntimeType(
  46448. ctx,
  46449. node.typeParameters.params[0],
  46450. scope,
  46451. true
  46452. );
  46453. }
  46454. break;
  46455. case "Pick":
  46456. case "Extract":
  46457. if (node.typeParameters && node.typeParameters.params[1]) {
  46458. return inferRuntimeType(
  46459. ctx,
  46460. node.typeParameters.params[1],
  46461. scope
  46462. );
  46463. }
  46464. break;
  46465. case "Function":
  46466. case "Object":
  46467. case "Set":
  46468. case "Map":
  46469. case "WeakSet":
  46470. case "WeakMap":
  46471. case "Date":
  46472. case "Promise":
  46473. case "Error":
  46474. case "Uppercase":
  46475. case "Lowercase":
  46476. case "Capitalize":
  46477. case "Uncapitalize":
  46478. case "ReadonlyMap":
  46479. case "ReadonlySet":
  46480. return ["String"];
  46481. }
  46482. } else {
  46483. switch (node.typeName.name) {
  46484. case "Array":
  46485. case "Function":
  46486. case "Object":
  46487. case "Set":
  46488. case "Map":
  46489. case "WeakSet":
  46490. case "WeakMap":
  46491. case "Date":
  46492. case "Promise":
  46493. case "Error":
  46494. return [node.typeName.name];
  46495. // TS built-in utility types
  46496. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  46497. case "Partial":
  46498. case "Required":
  46499. case "Readonly":
  46500. case "Record":
  46501. case "Pick":
  46502. case "Omit":
  46503. case "InstanceType":
  46504. return ["Object"];
  46505. case "Uppercase":
  46506. case "Lowercase":
  46507. case "Capitalize":
  46508. case "Uncapitalize":
  46509. return ["String"];
  46510. case "Parameters":
  46511. case "ConstructorParameters":
  46512. case "ReadonlyArray":
  46513. return ["Array"];
  46514. case "ReadonlyMap":
  46515. return ["Map"];
  46516. case "ReadonlySet":
  46517. return ["Set"];
  46518. // Vue ref wrapper types — handled here so that runtime type
  46519. // inference still works when `vue` types cannot be resolved
  46520. // (e.g. consumed as built artifacts in another package). #14729
  46521. case "Ref":
  46522. case "ShallowRef":
  46523. case "ComputedRef":
  46524. case "WritableComputedRef":
  46525. return ["Object"];
  46526. case "MaybeRef":
  46527. case "MaybeRefOrGetter": {
  46528. const types = /* @__PURE__ */ new Set(["Object"]);
  46529. if (node.typeName.name === "MaybeRefOrGetter") {
  46530. types.add("Function");
  46531. }
  46532. if (node.typeParameters && node.typeParameters.params[0]) {
  46533. for (const t of inferRuntimeType(
  46534. ctx,
  46535. node.typeParameters.params[0],
  46536. scope,
  46537. false,
  46538. typeParameters
  46539. )) {
  46540. types.add(t);
  46541. }
  46542. }
  46543. return Array.from(types);
  46544. }
  46545. case "NonNullable":
  46546. if (node.typeParameters && node.typeParameters.params[0]) {
  46547. return inferRuntimeType(
  46548. ctx,
  46549. node.typeParameters.params[0],
  46550. scope
  46551. ).filter((t) => t !== "null");
  46552. }
  46553. break;
  46554. case "Extract":
  46555. if (node.typeParameters && node.typeParameters.params[1]) {
  46556. return inferRuntimeType(
  46557. ctx,
  46558. node.typeParameters.params[1],
  46559. scope
  46560. );
  46561. }
  46562. break;
  46563. case "Exclude":
  46564. case "OmitThisParameter":
  46565. if (node.typeParameters && node.typeParameters.params[0]) {
  46566. return inferRuntimeType(
  46567. ctx,
  46568. node.typeParameters.params[0],
  46569. scope
  46570. );
  46571. }
  46572. break;
  46573. }
  46574. }
  46575. }
  46576. break;
  46577. }
  46578. case "TSParenthesizedType":
  46579. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  46580. case "TSUnionType":
  46581. return flattenTypes(ctx, node.types, scope, isKeyOf, typeParameters);
  46582. case "TSIntersectionType": {
  46583. return flattenTypes(
  46584. ctx,
  46585. node.types,
  46586. scope,
  46587. isKeyOf,
  46588. typeParameters
  46589. ).filter((t) => t !== UNKNOWN_TYPE);
  46590. }
  46591. case "TSMappedType": {
  46592. const { typeAnnotation, typeParameter } = node;
  46593. if (typeAnnotation && typeAnnotation.type === "TSIndexedAccessType" && typeParameter && typeParameter.constraint && typeParameters) {
  46594. const constraint = typeParameter.constraint;
  46595. if (constraint.type === "TSTypeOperator" && constraint.operator === "keyof" && constraint.typeAnnotation && constraint.typeAnnotation.type === "TSTypeReference" && constraint.typeAnnotation.typeName.type === "Identifier") {
  46596. const typeName = constraint.typeAnnotation.typeName.name;
  46597. const index = typeAnnotation.indexType;
  46598. const obj = typeAnnotation.objectType;
  46599. if (obj && obj.type === "TSTypeReference" && obj.typeName.type === "Identifier" && obj.typeName.name === typeName && index && index.type === "TSTypeReference" && index.typeName.type === "Identifier" && index.typeName.name === typeParameter.name) {
  46600. const targetType = typeParameters[typeName];
  46601. if (targetType) {
  46602. return inferRuntimeType(ctx, targetType, scope);
  46603. }
  46604. }
  46605. }
  46606. }
  46607. return [UNKNOWN_TYPE];
  46608. }
  46609. case "TSEnumDeclaration":
  46610. return inferEnumType(node);
  46611. case "TSSymbolKeyword":
  46612. return ["Symbol"];
  46613. case "TSIndexedAccessType": {
  46614. const types = resolveIndexType(ctx, node, scope);
  46615. return flattenTypes(ctx, types, scope, isKeyOf);
  46616. }
  46617. case "ClassDeclaration":
  46618. return ["Object"];
  46619. case "TSImportType": {
  46620. const sourceScope = importSourceToScope(
  46621. ctx,
  46622. node.argument,
  46623. scope,
  46624. node.argument.value
  46625. );
  46626. const resolved = resolveTypeReference(ctx, node, sourceScope);
  46627. if (resolved) {
  46628. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  46629. }
  46630. break;
  46631. }
  46632. case "TSTypeQuery": {
  46633. const id = node.exprName;
  46634. if (id.type === "Identifier") {
  46635. const matched = scope.declares[id.name];
  46636. if (matched) {
  46637. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  46638. }
  46639. }
  46640. break;
  46641. }
  46642. // e.g. readonly
  46643. case "TSTypeOperator": {
  46644. return inferRuntimeType(
  46645. ctx,
  46646. node.typeAnnotation,
  46647. scope,
  46648. node.operator === "keyof"
  46649. );
  46650. }
  46651. case "TSAnyKeyword": {
  46652. if (isKeyOf) {
  46653. return ["String", "Number", "Symbol"];
  46654. }
  46655. break;
  46656. }
  46657. }
  46658. } catch (e) {
  46659. } finally {
  46660. ctx.silentOnExtendsFailure = prevSilent;
  46661. }
  46662. return [UNKNOWN_TYPE];
  46663. }
  46664. function flattenTypes(ctx, types, scope, isKeyOf = false, typeParameters = void 0) {
  46665. if (types.length === 1) {
  46666. return inferRuntimeType(
  46667. ctx,
  46668. types[0],
  46669. types[0]._ownerScope || scope,
  46670. isKeyOf,
  46671. typeParameters
  46672. );
  46673. }
  46674. return [
  46675. ...new Set(
  46676. [].concat(
  46677. ...types.map(
  46678. (t) => inferRuntimeType(
  46679. ctx,
  46680. t,
  46681. t._ownerScope || scope,
  46682. isKeyOf,
  46683. typeParameters
  46684. )
  46685. )
  46686. )
  46687. )
  46688. ];
  46689. }
  46690. function inferEnumType(node) {
  46691. const types = /* @__PURE__ */ new Set();
  46692. for (const m of node.members) {
  46693. if (m.initializer) {
  46694. switch (m.initializer.type) {
  46695. case "StringLiteral":
  46696. types.add("String");
  46697. break;
  46698. case "NumericLiteral":
  46699. types.add("Number");
  46700. break;
  46701. }
  46702. }
  46703. }
  46704. return types.size ? [...types] : ["Number"];
  46705. }
  46706. function resolveExtractPropTypes({ props }, scope) {
  46707. const res = { props: {} };
  46708. for (const key in props) {
  46709. const raw = props[key];
  46710. res.props[key] = reverseInferType(
  46711. raw.key,
  46712. raw.typeAnnotation.typeAnnotation,
  46713. scope
  46714. );
  46715. }
  46716. return res;
  46717. }
  46718. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  46719. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  46720. const typeType = findStaticPropertyType(node, "type");
  46721. if (typeType) {
  46722. const requiredType = findStaticPropertyType(node, "required");
  46723. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  46724. return reverseInferType(key, typeType, scope, optional2, false);
  46725. }
  46726. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  46727. if (node.typeName.name.endsWith("Constructor")) {
  46728. return createProperty(
  46729. key,
  46730. ctorToType(node.typeName.name),
  46731. scope,
  46732. optional
  46733. );
  46734. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  46735. return createProperty(key, node.typeParameters.params[0], scope, optional);
  46736. }
  46737. }
  46738. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  46739. for (const t of node.typeParameters.params) {
  46740. const inferred = reverseInferType(key, t, scope, optional);
  46741. if (inferred) return inferred;
  46742. }
  46743. }
  46744. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  46745. }
  46746. function ctorToType(ctorType) {
  46747. const ctor = ctorType.slice(0, -11);
  46748. switch (ctor) {
  46749. case "String":
  46750. case "Number":
  46751. case "Boolean":
  46752. return { type: `TS${ctor}Keyword` };
  46753. case "Array":
  46754. case "Function":
  46755. case "Object":
  46756. case "Set":
  46757. case "Map":
  46758. case "WeakSet":
  46759. case "WeakMap":
  46760. case "Date":
  46761. case "Promise":
  46762. return {
  46763. type: "TSTypeReference",
  46764. typeName: { type: "Identifier", name: ctor }
  46765. };
  46766. }
  46767. return { type: `TSNullKeyword` };
  46768. }
  46769. function findStaticPropertyType(node, key) {
  46770. const prop = node.members.find(
  46771. (m) => m.type === "TSPropertySignature" && getStringLiteralKey(m) === key && m.typeAnnotation
  46772. );
  46773. return prop && prop.typeAnnotation.typeAnnotation;
  46774. }
  46775. function resolveReturnType(ctx, arg, scope) {
  46776. var _a;
  46777. let resolved = arg;
  46778. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  46779. resolved = resolveTypeReference(ctx, arg, scope);
  46780. }
  46781. if (!resolved) return;
  46782. if (resolved.type === "TSFunctionType") {
  46783. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  46784. }
  46785. if (resolved.type === "TSDeclareFunction") {
  46786. return resolved.returnType;
  46787. }
  46788. }
  46789. function resolveUnionType(ctx, node, scope) {
  46790. if (node.type === "TSTypeReference") {
  46791. const resolved = resolveTypeReference(ctx, node, scope);
  46792. if (resolved) node = resolved;
  46793. }
  46794. let types;
  46795. if (node.type === "TSUnionType") {
  46796. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  46797. } else {
  46798. types = [node];
  46799. }
  46800. return types;
  46801. }
  46802. const DEFINE_MODEL = "defineModel";
  46803. function processDefineModel(ctx, node, declId) {
  46804. if (!isCallOf(node, DEFINE_MODEL)) {
  46805. return false;
  46806. }
  46807. ctx.hasDefineModelCall = true;
  46808. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  46809. let modelName;
  46810. let options;
  46811. const arg0 = node.arguments[0] && unwrapTSNode(node.arguments[0]);
  46812. const hasName = arg0 && (arg0.type === "StringLiteral" || arg0.type === "TemplateLiteral" && arg0.expressions.length === 0);
  46813. if (hasName) {
  46814. modelName = arg0.type === "StringLiteral" ? arg0.value : arg0.quasis[0].value.cooked;
  46815. options = node.arguments[1];
  46816. } else {
  46817. modelName = "modelValue";
  46818. options = arg0;
  46819. }
  46820. if (ctx.modelDecls[modelName]) {
  46821. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  46822. }
  46823. let optionsString = options && ctx.getString(options);
  46824. let optionsRemoved = !options;
  46825. const runtimeOptionNodes = [];
  46826. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  46827. let removed = 0;
  46828. for (let i = options.properties.length - 1; i >= 0; i--) {
  46829. const p = options.properties[i];
  46830. const next = options.properties[i + 1];
  46831. const start = p.start;
  46832. const end = next ? next.start : options.end - 1;
  46833. 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"))) {
  46834. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  46835. } else {
  46836. removed++;
  46837. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  46838. runtimeOptionNodes.push(p);
  46839. }
  46840. }
  46841. if (removed === options.properties.length) {
  46842. optionsRemoved = true;
  46843. ctx.s.remove(
  46844. ctx.startOffset + (hasName ? arg0.end : options.start),
  46845. ctx.startOffset + options.end
  46846. );
  46847. }
  46848. }
  46849. ctx.modelDecls[modelName] = {
  46850. type,
  46851. options: optionsString,
  46852. runtimeOptionNodes,
  46853. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  46854. };
  46855. ctx.bindingMetadata[modelName] = "props";
  46856. ctx.s.overwrite(
  46857. ctx.startOffset + node.callee.start,
  46858. ctx.startOffset + node.callee.end,
  46859. ctx.helper("useModel")
  46860. );
  46861. ctx.s.appendLeft(
  46862. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  46863. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  46864. );
  46865. return true;
  46866. }
  46867. function genModelProps(ctx) {
  46868. if (!ctx.hasDefineModelCall) return;
  46869. const isProd = !!ctx.options.isProd;
  46870. let modelPropsDecl = "";
  46871. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  46872. ctx.modelDecls
  46873. )) {
  46874. let skipCheck = false;
  46875. let codegenOptions = ``;
  46876. let runtimeTypes = type && inferRuntimeType(ctx, type);
  46877. if (runtimeTypes) {
  46878. const hasBoolean = runtimeTypes.includes("Boolean");
  46879. const hasFunction = runtimeTypes.includes("Function");
  46880. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  46881. if (hasUnknownType) {
  46882. if (hasBoolean || hasFunction) {
  46883. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  46884. skipCheck = true;
  46885. } else {
  46886. runtimeTypes = ["null"];
  46887. }
  46888. }
  46889. if (!isProd) {
  46890. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  46891. } else if (hasBoolean || runtimeOptions && hasFunction) {
  46892. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  46893. } else ;
  46894. }
  46895. let decl;
  46896. if (codegenOptions && runtimeOptions) {
  46897. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  46898. } else if (codegenOptions) {
  46899. decl = `{ ${codegenOptions} }`;
  46900. } else if (runtimeOptions) {
  46901. decl = runtimeOptions;
  46902. } else {
  46903. decl = `{}`;
  46904. }
  46905. modelPropsDecl += `
  46906. ${JSON.stringify(name)}: ${decl},`;
  46907. const modifierPropName = JSON.stringify(
  46908. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  46909. );
  46910. modelPropsDecl += `
  46911. ${modifierPropName}: {},`;
  46912. }
  46913. return `{${modelPropsDecl}
  46914. }`;
  46915. }
  46916. const DEFINE_PROPS = "defineProps";
  46917. const WITH_DEFAULTS = "withDefaults";
  46918. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  46919. if (!isCallOf(node, DEFINE_PROPS)) {
  46920. return processWithDefaults(ctx, node, declId);
  46921. }
  46922. if (ctx.hasDefinePropsCall) {
  46923. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  46924. }
  46925. ctx.hasDefinePropsCall = true;
  46926. ctx.propsRuntimeDecl = node.arguments[0];
  46927. if (ctx.propsRuntimeDecl) {
  46928. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  46929. if (!(key in ctx.bindingMetadata)) {
  46930. ctx.bindingMetadata[key] = "props";
  46931. }
  46932. }
  46933. }
  46934. if (node.typeParameters) {
  46935. if (ctx.propsRuntimeDecl) {
  46936. ctx.error(
  46937. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  46938. node
  46939. );
  46940. }
  46941. ctx.propsTypeDecl = node.typeParameters.params[0];
  46942. }
  46943. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  46944. processPropsDestructure(ctx, declId);
  46945. }
  46946. ctx.propsCall = node;
  46947. ctx.propsDecl = declId;
  46948. return true;
  46949. }
  46950. function processWithDefaults(ctx, node, declId) {
  46951. if (!isCallOf(node, WITH_DEFAULTS)) {
  46952. return false;
  46953. }
  46954. if (!processDefineProps(
  46955. ctx,
  46956. node.arguments[0],
  46957. declId,
  46958. true
  46959. )) {
  46960. ctx.error(
  46961. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  46962. node.arguments[0] || node
  46963. );
  46964. }
  46965. if (ctx.propsRuntimeDecl) {
  46966. ctx.error(
  46967. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  46968. node
  46969. );
  46970. }
  46971. if (declId && declId.type === "ObjectPattern") {
  46972. ctx.warn(
  46973. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  46974. Reactive destructure will be disabled when using withDefaults().
  46975. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  46976. node.callee
  46977. );
  46978. }
  46979. ctx.propsRuntimeDefaults = node.arguments[1];
  46980. if (!ctx.propsRuntimeDefaults) {
  46981. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  46982. }
  46983. ctx.propsCall = node;
  46984. return true;
  46985. }
  46986. function genRuntimeProps(ctx) {
  46987. let propsDecls;
  46988. if (ctx.propsRuntimeDecl) {
  46989. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  46990. if (ctx.propsDestructureDecl) {
  46991. const defaults = [];
  46992. for (const key in ctx.propsDestructuredBindings) {
  46993. const d = genDestructuredDefaultValue(ctx, key);
  46994. const finalKey = getEscapedPropName(key);
  46995. if (d)
  46996. defaults.push(
  46997. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  46998. );
  46999. }
  47000. if (defaults.length) {
  47001. propsDecls = `/*@__PURE__*/${ctx.helper(
  47002. `mergeDefaults`
  47003. )}(${propsDecls}, {
  47004. ${defaults.join(",\n ")}
  47005. })`;
  47006. }
  47007. }
  47008. } else if (ctx.propsTypeDecl) {
  47009. propsDecls = extractRuntimeProps(ctx);
  47010. }
  47011. const modelsDecls = genModelProps(ctx);
  47012. if (propsDecls && modelsDecls) {
  47013. return `/*@__PURE__*/${ctx.helper(
  47014. "mergeModels"
  47015. )}(${propsDecls}, ${modelsDecls})`;
  47016. } else {
  47017. return modelsDecls || propsDecls;
  47018. }
  47019. }
  47020. function extractRuntimeProps(ctx) {
  47021. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  47022. if (!props.length) {
  47023. return;
  47024. }
  47025. const propStrings = [];
  47026. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  47027. for (const prop of props) {
  47028. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  47029. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  47030. ctx.bindingMetadata[prop.key] = "props";
  47031. }
  47032. }
  47033. let propsDecls = `{
  47034. ${propStrings.join(",\n ")}
  47035. }`;
  47036. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  47037. propsDecls = `/*@__PURE__*/${ctx.helper(
  47038. "mergeDefaults"
  47039. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  47040. }
  47041. return propsDecls;
  47042. }
  47043. function resolveRuntimePropsFromType(ctx, node) {
  47044. const props = [];
  47045. const elements = resolveTypeElements(ctx, node);
  47046. for (const key in elements.props) {
  47047. const e = elements.props[key];
  47048. let type = inferRuntimeType(ctx, e);
  47049. let skipCheck = false;
  47050. if (type.includes(UNKNOWN_TYPE)) {
  47051. if (type.includes("Boolean") || type.includes("Function")) {
  47052. type = type.filter((t) => t !== UNKNOWN_TYPE);
  47053. skipCheck = true;
  47054. } else {
  47055. type = ["null"];
  47056. }
  47057. }
  47058. props.push({
  47059. key,
  47060. required: !e.optional,
  47061. type: type || [`null`],
  47062. skipCheck
  47063. });
  47064. }
  47065. return props;
  47066. }
  47067. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  47068. let defaultString;
  47069. const destructured = genDestructuredDefaultValue(ctx, key, type);
  47070. if (destructured) {
  47071. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  47072. } else if (hasStaticDefaults) {
  47073. const prop = ctx.propsRuntimeDefaults.properties.find(
  47074. (node) => {
  47075. if (node.type === "SpreadElement") return false;
  47076. return resolveObjectKey(node.key, node.computed) === key;
  47077. }
  47078. );
  47079. if (prop) {
  47080. if (prop.type === "ObjectProperty") {
  47081. defaultString = `default: ${ctx.getString(prop.value)}`;
  47082. } else {
  47083. let paramsString = "";
  47084. if (prop.params.length) {
  47085. const start = prop.params[0].start;
  47086. const end = prop.params[prop.params.length - 1].end;
  47087. paramsString = ctx.getString({ start, end });
  47088. }
  47089. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default(${paramsString}) ${ctx.getString(prop.body)}`;
  47090. }
  47091. }
  47092. }
  47093. const finalKey = getEscapedPropName(key);
  47094. if (!ctx.options.isProd) {
  47095. return `${finalKey}: { ${concatStrings([
  47096. `type: ${toRuntimeTypeString(type)}`,
  47097. `required: ${required}`,
  47098. skipCheck && "skipCheck: true",
  47099. defaultString
  47100. ])} }`;
  47101. } else if (type.some(
  47102. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  47103. )) {
  47104. return `${finalKey}: { ${concatStrings([
  47105. `type: ${toRuntimeTypeString(type)}`,
  47106. defaultString
  47107. ])} }`;
  47108. } else {
  47109. if (ctx.isCE) {
  47110. if (defaultString) {
  47111. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  47112. type
  47113. )} }`}`;
  47114. } else {
  47115. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  47116. }
  47117. }
  47118. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  47119. }
  47120. }
  47121. function hasStaticWithDefaults(ctx) {
  47122. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  47123. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  47124. ));
  47125. }
  47126. function genDestructuredDefaultValue(ctx, key, inferredType) {
  47127. const destructured = ctx.propsDestructuredBindings[key];
  47128. const defaultVal = destructured && destructured.default;
  47129. if (defaultVal) {
  47130. const value = ctx.getString(defaultVal);
  47131. const unwrapped = unwrapTSNode(defaultVal);
  47132. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  47133. const valueType = inferValueType(unwrapped);
  47134. if (valueType && !inferredType.includes(valueType)) {
  47135. ctx.error(
  47136. `Default value of prop "${key}" does not match declared type.`,
  47137. unwrapped
  47138. );
  47139. }
  47140. }
  47141. const needSkipFactory = !inferredType && (isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  47142. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  47143. return {
  47144. valueString: needFactoryWrap ? `() => (${value})` : value,
  47145. needSkipFactory
  47146. };
  47147. }
  47148. }
  47149. function inferValueType(node) {
  47150. switch (node.type) {
  47151. case "StringLiteral":
  47152. return "String";
  47153. case "NumericLiteral":
  47154. return "Number";
  47155. case "BooleanLiteral":
  47156. return "Boolean";
  47157. case "ObjectExpression":
  47158. return "Object";
  47159. case "ArrayExpression":
  47160. return "Array";
  47161. case "FunctionExpression":
  47162. case "ArrowFunctionExpression":
  47163. return "Function";
  47164. }
  47165. }
  47166. function processPropsDestructure(ctx, declId) {
  47167. if (ctx.options.propsDestructure === "error") {
  47168. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  47169. } else if (ctx.options.propsDestructure === false) {
  47170. return;
  47171. }
  47172. ctx.propsDestructureDecl = declId;
  47173. const registerBinding = (key, local, defaultValue) => {
  47174. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  47175. if (local !== key) {
  47176. ctx.bindingMetadata[local] = "props-aliased";
  47177. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  47178. }
  47179. };
  47180. for (const prop of declId.properties) {
  47181. if (prop.type === "ObjectProperty") {
  47182. const propKey = resolveObjectKey(prop.key, prop.computed);
  47183. if (!propKey) {
  47184. ctx.error(
  47185. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  47186. prop.key
  47187. );
  47188. }
  47189. if (prop.value.type === "AssignmentPattern") {
  47190. const { left, right } = prop.value;
  47191. if (left.type !== "Identifier") {
  47192. ctx.error(
  47193. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  47194. left
  47195. );
  47196. }
  47197. registerBinding(propKey, left.name, right);
  47198. } else if (prop.value.type === "Identifier") {
  47199. registerBinding(propKey, prop.value.name);
  47200. } else {
  47201. ctx.error(
  47202. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  47203. prop.value
  47204. );
  47205. }
  47206. } else {
  47207. ctx.propsDestructureRestId = prop.argument.name;
  47208. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  47209. }
  47210. }
  47211. }
  47212. function transformDestructuredProps(ctx, vueImportAliases) {
  47213. if (ctx.options.propsDestructure === false) {
  47214. return;
  47215. }
  47216. const rootScope = /* @__PURE__ */ Object.create(null);
  47217. const scopeStack = [rootScope];
  47218. const functionScopeStack = [rootScope];
  47219. let currentScope = rootScope;
  47220. const excludedIds = /* @__PURE__ */ new WeakSet();
  47221. const parentStack = [];
  47222. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  47223. for (const key in ctx.propsDestructuredBindings) {
  47224. const { local } = ctx.propsDestructuredBindings[key];
  47225. rootScope[local] = true;
  47226. propsLocalToPublicMap[local] = key;
  47227. }
  47228. function pushScope(isFunctionScope = false) {
  47229. const scope = currentScope = Object.create(currentScope);
  47230. scopeStack.push(scope);
  47231. if (isFunctionScope) {
  47232. functionScopeStack.push(scope);
  47233. }
  47234. }
  47235. function popScope(isFunctionScope = false) {
  47236. scopeStack.pop();
  47237. if (isFunctionScope) {
  47238. functionScopeStack.pop();
  47239. }
  47240. currentScope = scopeStack[scopeStack.length - 1] || null;
  47241. }
  47242. function registerLocalBinding(id, scope = currentScope) {
  47243. excludedIds.add(id);
  47244. if (scope) {
  47245. scope[id.name] = false;
  47246. } else {
  47247. ctx.error(
  47248. "registerBinding called without active scope, something is wrong.",
  47249. id
  47250. );
  47251. }
  47252. }
  47253. function walkScope(node, isRoot = false) {
  47254. for (const stmt of node.body) {
  47255. if (stmt.type === "VariableDeclaration") {
  47256. walkVariableDeclaration(stmt, isRoot);
  47257. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  47258. if (stmt.declare || !stmt.id) continue;
  47259. registerLocalBinding(stmt.id);
  47260. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  47261. walkVariableDeclaration(stmt.declaration, isRoot);
  47262. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  47263. walkVariableDeclaration(stmt.body, isRoot);
  47264. }
  47265. }
  47266. }
  47267. function walkVariableDeclaration(stmt, isRoot = false, scope = stmt.kind === "var" ? functionScopeStack[functionScopeStack.length - 1] : currentScope) {
  47268. if (stmt.declare) {
  47269. return;
  47270. }
  47271. for (const decl of stmt.declarations) {
  47272. const isDefineProps = isRoot && decl.init && isCallOf(unwrapTSNode(decl.init), "defineProps");
  47273. for (const id of extractIdentifiers$1(decl.id)) {
  47274. if (isDefineProps) {
  47275. excludedIds.add(id);
  47276. } else {
  47277. registerLocalBinding(id, scope);
  47278. }
  47279. }
  47280. }
  47281. }
  47282. function walkFunctionScopeVarDeclarations(scopeNode, isRoot = false) {
  47283. const scope = functionScopeStack[functionScopeStack.length - 1];
  47284. walk$2(scopeNode, {
  47285. enter(node, parent) {
  47286. if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
  47287. return this.skip();
  47288. }
  47289. if (isFunctionType(node) || node.type === "ClassDeclaration" || node.type === "ClassExpression") {
  47290. return this.skip();
  47291. }
  47292. if (node.type === "VariableDeclaration" && node.kind === "var") {
  47293. walkVariableDeclaration(node, isRoot && parent === scopeNode, scope);
  47294. }
  47295. }
  47296. });
  47297. }
  47298. function rewriteId(id, parent, parentStack2) {
  47299. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  47300. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  47301. }
  47302. if (isStaticProperty(parent) && parent.shorthand) {
  47303. if (!parent.inPattern || isInDestructureAssignment(parent, parentStack2)) {
  47304. ctx.s.appendLeft(
  47305. id.end + ctx.startOffset,
  47306. `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  47307. );
  47308. }
  47309. } else {
  47310. ctx.s.overwrite(
  47311. id.start + ctx.startOffset,
  47312. id.end + ctx.startOffset,
  47313. genPropsAccessExp(propsLocalToPublicMap[id.name])
  47314. );
  47315. }
  47316. }
  47317. function checkUsage(node, method, alias = method) {
  47318. if (isCallOf(node, alias)) {
  47319. const arg = unwrapTSNode(node.arguments[0]);
  47320. if (arg.type === "Identifier" && currentScope[arg.name]) {
  47321. ctx.error(
  47322. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  47323. arg
  47324. );
  47325. }
  47326. }
  47327. }
  47328. const ast = ctx.scriptSetupAst;
  47329. walkFunctionScopeVarDeclarations(ast, true);
  47330. walkScope(ast, true);
  47331. walk$2(ast, {
  47332. enter(node, parent) {
  47333. parent && parentStack.push(parent);
  47334. if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
  47335. return this.skip();
  47336. }
  47337. checkUsage(node, "watch", vueImportAliases.watch);
  47338. checkUsage(node, "toRef", vueImportAliases.toRef);
  47339. if (isFunctionType(node)) {
  47340. pushScope(true);
  47341. walkFunctionParams(node, registerLocalBinding);
  47342. if (node.body.type === "BlockStatement") {
  47343. walkFunctionScopeVarDeclarations(node.body);
  47344. walkScope(node.body);
  47345. }
  47346. return;
  47347. }
  47348. if (node.type === "CatchClause") {
  47349. pushScope();
  47350. if (node.param && node.param.type === "Identifier") {
  47351. registerLocalBinding(node.param);
  47352. }
  47353. walkScope(node.body);
  47354. return;
  47355. }
  47356. if (node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  47357. pushScope();
  47358. const varDecl = node.type === "ForStatement" ? node.init : node.left;
  47359. if (varDecl && varDecl.type === "VariableDeclaration") {
  47360. walkVariableDeclaration(varDecl);
  47361. }
  47362. if (node.body.type === "BlockStatement") {
  47363. walkScope(node.body);
  47364. }
  47365. return;
  47366. }
  47367. if (node.type === "BlockStatement" && !isFunctionType(parent)) {
  47368. pushScope();
  47369. walkScope(node);
  47370. return;
  47371. }
  47372. if (node.type === "Identifier") {
  47373. if (isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  47374. if (currentScope[node.name]) {
  47375. rewriteId(node, parent, parentStack);
  47376. }
  47377. }
  47378. }
  47379. },
  47380. leave(node, parent) {
  47381. parent && parentStack.pop();
  47382. if (isFunctionType(node)) {
  47383. popScope(true);
  47384. } else if (node.type === "BlockStatement" && !isFunctionType(parent)) {
  47385. popScope();
  47386. } else if (node.type === "CatchClause" || node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  47387. popScope();
  47388. }
  47389. }
  47390. });
  47391. }
  47392. const DEFINE_EMITS = "defineEmits";
  47393. function processDefineEmits(ctx, node, declId) {
  47394. if (!isCallOf(node, DEFINE_EMITS)) {
  47395. return false;
  47396. }
  47397. if (ctx.hasDefineEmitCall) {
  47398. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  47399. }
  47400. ctx.hasDefineEmitCall = true;
  47401. ctx.emitsRuntimeDecl = node.arguments[0];
  47402. if (node.typeParameters) {
  47403. if (ctx.emitsRuntimeDecl) {
  47404. ctx.error(
  47405. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  47406. node
  47407. );
  47408. }
  47409. ctx.emitsTypeDecl = node.typeParameters.params[0];
  47410. }
  47411. ctx.emitDecl = declId;
  47412. return true;
  47413. }
  47414. function genRuntimeEmits(ctx) {
  47415. let emitsDecl = "";
  47416. if (ctx.emitsRuntimeDecl) {
  47417. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  47418. } else if (ctx.emitsTypeDecl) {
  47419. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  47420. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  47421. }
  47422. if (ctx.hasDefineModelCall) {
  47423. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  47424. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  47425. "mergeModels"
  47426. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  47427. }
  47428. return emitsDecl;
  47429. }
  47430. function extractRuntimeEmits(ctx) {
  47431. const emits = /* @__PURE__ */ new Set();
  47432. const node = ctx.emitsTypeDecl;
  47433. if (node.type === "TSFunctionType") {
  47434. extractEventNames(ctx, node.parameters[0], emits);
  47435. return emits;
  47436. }
  47437. const { props, calls } = resolveTypeElements(ctx, node);
  47438. let hasProperty = false;
  47439. for (const key in props) {
  47440. emits.add(key);
  47441. hasProperty = true;
  47442. }
  47443. if (calls) {
  47444. if (hasProperty) {
  47445. ctx.error(
  47446. `defineEmits() type cannot mixed call signature and property syntax.`,
  47447. node
  47448. );
  47449. }
  47450. for (const call of calls) {
  47451. extractEventNames(ctx, call.parameters[0], emits);
  47452. }
  47453. }
  47454. return emits;
  47455. }
  47456. function extractEventNames(ctx, eventName, emits) {
  47457. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  47458. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  47459. for (const type of types) {
  47460. if (type.type === "TSLiteralType") {
  47461. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  47462. emits.add(String(type.literal.value));
  47463. }
  47464. }
  47465. }
  47466. }
  47467. }
  47468. const DEFINE_EXPOSE = "defineExpose";
  47469. function processDefineExpose(ctx, node) {
  47470. if (isCallOf(node, DEFINE_EXPOSE)) {
  47471. if (ctx.hasDefineExposeCall) {
  47472. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  47473. }
  47474. ctx.hasDefineExposeCall = true;
  47475. return true;
  47476. }
  47477. return false;
  47478. }
  47479. const DEFINE_SLOTS = "defineSlots";
  47480. function processDefineSlots(ctx, node, declId) {
  47481. if (!isCallOf(node, DEFINE_SLOTS)) {
  47482. return false;
  47483. }
  47484. if (ctx.hasDefineSlotsCall) {
  47485. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  47486. }
  47487. ctx.hasDefineSlotsCall = true;
  47488. if (node.arguments.length > 0) {
  47489. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  47490. }
  47491. if (declId) {
  47492. ctx.s.overwrite(
  47493. ctx.startOffset + node.start,
  47494. ctx.startOffset + node.end,
  47495. `${ctx.helper("useSlots")}()`
  47496. );
  47497. }
  47498. return true;
  47499. }
  47500. const DEFINE_OPTIONS = "defineOptions";
  47501. function processDefineOptions(ctx, node) {
  47502. if (!isCallOf(node, DEFINE_OPTIONS)) {
  47503. return false;
  47504. }
  47505. if (ctx.hasDefineOptionsCall) {
  47506. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  47507. }
  47508. if (node.typeParameters) {
  47509. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  47510. }
  47511. if (!node.arguments[0]) return true;
  47512. ctx.hasDefineOptionsCall = true;
  47513. ctx.optionsRuntimeDecl = unwrapTSNode(node.arguments[0]);
  47514. let propsOption = void 0;
  47515. let emitsOption = void 0;
  47516. let exposeOption = void 0;
  47517. let slotsOption = void 0;
  47518. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  47519. for (const prop of ctx.optionsRuntimeDecl.properties) {
  47520. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  47521. switch (prop.key.name) {
  47522. case "props":
  47523. propsOption = prop;
  47524. break;
  47525. case "emits":
  47526. emitsOption = prop;
  47527. break;
  47528. case "expose":
  47529. exposeOption = prop;
  47530. break;
  47531. case "slots":
  47532. slotsOption = prop;
  47533. break;
  47534. }
  47535. }
  47536. }
  47537. }
  47538. if (propsOption) {
  47539. ctx.error(
  47540. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  47541. propsOption
  47542. );
  47543. }
  47544. if (emitsOption) {
  47545. ctx.error(
  47546. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  47547. emitsOption
  47548. );
  47549. }
  47550. if (exposeOption) {
  47551. ctx.error(
  47552. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  47553. exposeOption
  47554. );
  47555. }
  47556. if (slotsOption) {
  47557. ctx.error(
  47558. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  47559. slotsOption
  47560. );
  47561. }
  47562. return true;
  47563. }
  47564. function processAwait(ctx, node, needSemi, isStatement) {
  47565. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  47566. const startOffset = ctx.startOffset;
  47567. const argumentStr = ctx.descriptor.source.slice(
  47568. argumentStart + startOffset,
  47569. node.argument.end + startOffset
  47570. );
  47571. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  47572. ctx.s.overwrite(
  47573. node.start + startOffset,
  47574. argumentStart + startOffset,
  47575. `${needSemi ? `;` : ``}(
  47576. ([__temp,__restore] = ${ctx.helper(
  47577. `withAsyncContext`
  47578. )}(${containsNestedAwait ? `async ` : ``}() => `
  47579. );
  47580. ctx.s.appendLeft(
  47581. node.end + startOffset,
  47582. `)),
  47583. ${isStatement ? `` : `__temp = `}await __temp,
  47584. __restore()${isStatement ? `` : `,
  47585. __temp`}
  47586. )`
  47587. );
  47588. }
  47589. var __defProp$1 = Object.defineProperty;
  47590. var __defProps = Object.defineProperties;
  47591. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  47592. var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
  47593. var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
  47594. var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
  47595. var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  47596. var __spreadValues$1 = (a, b) => {
  47597. for (var prop in b || (b = {}))
  47598. if (__hasOwnProp$1.call(b, prop))
  47599. __defNormalProp$1(a, prop, b[prop]);
  47600. if (__getOwnPropSymbols$1)
  47601. for (var prop of __getOwnPropSymbols$1(b)) {
  47602. if (__propIsEnum$1.call(b, prop))
  47603. __defNormalProp$1(a, prop, b[prop]);
  47604. }
  47605. return a;
  47606. };
  47607. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  47608. const MACROS = [
  47609. DEFINE_PROPS,
  47610. DEFINE_EMITS,
  47611. DEFINE_EXPOSE,
  47612. DEFINE_OPTIONS,
  47613. DEFINE_SLOTS,
  47614. DEFINE_MODEL,
  47615. WITH_DEFAULTS
  47616. ];
  47617. function compileScript(sfc, options) {
  47618. var _a, _b, _c;
  47619. if (!options.id) {
  47620. warnOnce$1(
  47621. `compileScript now requires passing the \`id\` option.
  47622. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  47623. );
  47624. }
  47625. const { script, scriptSetup, source, filename } = sfc;
  47626. const hoistStatic = options.hoistStatic !== false && !script;
  47627. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  47628. const scriptLang = script && script.lang;
  47629. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  47630. const isJSOrTS = isJS(scriptLang, scriptSetupLang) || isTS(scriptLang, scriptSetupLang);
  47631. if (script && scriptSetup && scriptLang !== scriptSetupLang) {
  47632. throw new Error(
  47633. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  47634. );
  47635. }
  47636. if (!scriptSetup) {
  47637. if (!script) {
  47638. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  47639. }
  47640. if (script.lang && !isJSOrTS) {
  47641. return script;
  47642. }
  47643. const ctx2 = new ScriptCompileContext(sfc, options);
  47644. return processNormalScript(ctx2, scopeId);
  47645. }
  47646. if (scriptSetupLang && !isJSOrTS) {
  47647. return scriptSetup;
  47648. }
  47649. const ctx = new ScriptCompileContext(sfc, options);
  47650. const scriptBindings = /* @__PURE__ */ Object.create(null);
  47651. const setupBindings = /* @__PURE__ */ Object.create(null);
  47652. let defaultExport;
  47653. let hasAwait = false;
  47654. let hasInlinedSsrRenderFn = false;
  47655. const startOffset = ctx.startOffset;
  47656. const endOffset = ctx.endOffset;
  47657. const scriptStartOffset = script && script.loc.start.offset;
  47658. const scriptEndOffset = script && script.loc.end.offset;
  47659. function hoistNode(node) {
  47660. const start = node.start + startOffset;
  47661. let end = node.end + startOffset;
  47662. if (node.trailingComments && node.trailingComments.length > 0) {
  47663. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  47664. end = lastCommentNode.end + startOffset;
  47665. }
  47666. while (end <= source.length) {
  47667. if (!/\s/.test(source.charAt(end))) {
  47668. break;
  47669. }
  47670. end++;
  47671. }
  47672. ctx.s.move(start, end, 0);
  47673. }
  47674. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  47675. let isUsedInTemplate = needTemplateUsageCheck;
  47676. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  47677. isUsedInTemplate = isImportUsed(local, sfc);
  47678. }
  47679. ctx.userImports[local] = {
  47680. isType,
  47681. imported,
  47682. local,
  47683. source: source2,
  47684. isFromSetup,
  47685. isUsedInTemplate
  47686. };
  47687. }
  47688. function checkInvalidScopeReference(node, method) {
  47689. if (!node) return;
  47690. walkIdentifiers(node, (id) => {
  47691. const binding = setupBindings[id.name];
  47692. if (binding && binding !== "literal-const") {
  47693. ctx.error(
  47694. `\`${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.`,
  47695. id
  47696. );
  47697. }
  47698. });
  47699. }
  47700. const scriptAst = ctx.scriptAst;
  47701. const scriptSetupAst = ctx.scriptSetupAst;
  47702. if (scriptAst) {
  47703. for (const node of scriptAst.body) {
  47704. if (node.type === "ImportDeclaration") {
  47705. for (const specifier of node.specifiers) {
  47706. const imported = getImportedName(specifier);
  47707. registerUserImport(
  47708. node.source.value,
  47709. specifier.local.name,
  47710. imported,
  47711. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  47712. false,
  47713. !options.inlineTemplate
  47714. );
  47715. }
  47716. }
  47717. }
  47718. }
  47719. for (const node of scriptSetupAst.body) {
  47720. if (node.type === "ImportDeclaration") {
  47721. hoistNode(node);
  47722. let removed = 0;
  47723. const removeSpecifier = (i) => {
  47724. const removeLeft = i > removed;
  47725. removed++;
  47726. const current = node.specifiers[i];
  47727. const next = node.specifiers[i + 1];
  47728. ctx.s.remove(
  47729. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  47730. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  47731. );
  47732. };
  47733. for (let i = 0; i < node.specifiers.length; i++) {
  47734. const specifier = node.specifiers[i];
  47735. const local = specifier.local.name;
  47736. const imported = getImportedName(specifier);
  47737. const source2 = node.source.value;
  47738. const existing = ctx.userImports[local];
  47739. if (source2 === "vue" && MACROS.includes(imported)) {
  47740. if (local === imported) {
  47741. warnOnce$1(
  47742. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  47743. );
  47744. } else {
  47745. ctx.error(
  47746. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  47747. specifier
  47748. );
  47749. }
  47750. removeSpecifier(i);
  47751. } else if (existing) {
  47752. if (existing.source === source2 && existing.imported === imported) {
  47753. removeSpecifier(i);
  47754. } else {
  47755. ctx.error(
  47756. `different imports aliased to same local name.`,
  47757. specifier
  47758. );
  47759. }
  47760. } else {
  47761. registerUserImport(
  47762. source2,
  47763. local,
  47764. imported,
  47765. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  47766. true,
  47767. !options.inlineTemplate
  47768. );
  47769. }
  47770. }
  47771. if (node.specifiers.length && removed === node.specifiers.length) {
  47772. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  47773. }
  47774. }
  47775. }
  47776. const vueImportAliases = {};
  47777. for (const key in ctx.userImports) {
  47778. const { source: source2, imported, local } = ctx.userImports[key];
  47779. if (source2 === "vue") vueImportAliases[imported] = local;
  47780. }
  47781. if (script && scriptAst) {
  47782. for (const node of scriptAst.body) {
  47783. if (node.type === "ExportDefaultDeclaration") {
  47784. defaultExport = node;
  47785. let optionProperties;
  47786. if (defaultExport.declaration.type === "ObjectExpression") {
  47787. optionProperties = defaultExport.declaration.properties;
  47788. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  47789. optionProperties = defaultExport.declaration.arguments[0].properties;
  47790. }
  47791. if (optionProperties) {
  47792. for (const p of optionProperties) {
  47793. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  47794. ctx.hasDefaultExportName = true;
  47795. }
  47796. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  47797. ctx.hasDefaultExportRender = true;
  47798. }
  47799. }
  47800. }
  47801. const start = node.start + scriptStartOffset;
  47802. const end = node.declaration.start + scriptStartOffset;
  47803. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  47804. } else if (node.type === "ExportNamedDeclaration") {
  47805. const defaultSpecifier = node.specifiers.find(
  47806. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  47807. );
  47808. if (defaultSpecifier) {
  47809. defaultExport = node;
  47810. if (node.specifiers.length > 1) {
  47811. ctx.s.remove(
  47812. defaultSpecifier.start + scriptStartOffset,
  47813. defaultSpecifier.end + scriptStartOffset
  47814. );
  47815. } else {
  47816. ctx.s.remove(
  47817. node.start + scriptStartOffset,
  47818. node.end + scriptStartOffset
  47819. );
  47820. }
  47821. if (node.source) {
  47822. ctx.s.prepend(
  47823. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  47824. `
  47825. );
  47826. } else {
  47827. ctx.s.appendLeft(
  47828. scriptEndOffset,
  47829. `
  47830. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  47831. `
  47832. );
  47833. }
  47834. }
  47835. if (node.declaration) {
  47836. walkDeclaration(
  47837. "script",
  47838. node.declaration,
  47839. scriptBindings,
  47840. vueImportAliases,
  47841. hoistStatic
  47842. );
  47843. }
  47844. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  47845. walkDeclaration(
  47846. "script",
  47847. node,
  47848. scriptBindings,
  47849. vueImportAliases,
  47850. hoistStatic
  47851. );
  47852. }
  47853. }
  47854. if (scriptStartOffset > startOffset) {
  47855. if (!/\n$/.test(script.content.trim())) {
  47856. ctx.s.appendLeft(scriptEndOffset, `
  47857. `);
  47858. }
  47859. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  47860. }
  47861. }
  47862. for (const node of scriptSetupAst.body) {
  47863. if (node.type === "ExpressionStatement") {
  47864. const expr = unwrapTSNode(node.expression);
  47865. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  47866. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  47867. } else if (processDefineExpose(ctx, expr)) {
  47868. const callee = expr.callee;
  47869. ctx.s.overwrite(
  47870. callee.start + startOffset,
  47871. callee.end + startOffset,
  47872. "__expose"
  47873. );
  47874. } else {
  47875. processDefineModel(ctx, expr);
  47876. }
  47877. }
  47878. if (node.type === "VariableDeclaration" && !node.declare) {
  47879. const total = node.declarations.length;
  47880. let left = total;
  47881. let lastNonRemoved;
  47882. for (let i = 0; i < total; i++) {
  47883. const decl = node.declarations[i];
  47884. const init = decl.init && unwrapTSNode(decl.init);
  47885. if (init) {
  47886. if (processDefineOptions(ctx, init)) {
  47887. ctx.error(
  47888. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  47889. node
  47890. );
  47891. }
  47892. const isDefineProps = processDefineProps(ctx, init, decl.id);
  47893. if (ctx.propsDestructureRestId) {
  47894. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  47895. }
  47896. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  47897. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  47898. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  47899. if (left === 1) {
  47900. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  47901. } else {
  47902. let start = decl.start + startOffset;
  47903. let end = decl.end + startOffset;
  47904. if (i === total - 1) {
  47905. start = node.declarations[lastNonRemoved].end + startOffset;
  47906. } else {
  47907. end = node.declarations[i + 1].start + startOffset;
  47908. }
  47909. ctx.s.remove(start, end);
  47910. left--;
  47911. }
  47912. } else if (isDefineEmits) {
  47913. ctx.s.overwrite(
  47914. startOffset + init.start,
  47915. startOffset + init.end,
  47916. "__emit"
  47917. );
  47918. } else {
  47919. lastNonRemoved = i;
  47920. }
  47921. }
  47922. }
  47923. }
  47924. let isAllLiteral = false;
  47925. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  47926. isAllLiteral = walkDeclaration(
  47927. "scriptSetup",
  47928. node,
  47929. setupBindings,
  47930. vueImportAliases,
  47931. hoistStatic,
  47932. !!ctx.propsDestructureDecl
  47933. );
  47934. }
  47935. if (hoistStatic && isAllLiteral) {
  47936. hoistNode(node);
  47937. }
  47938. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  47939. const scope = [scriptSetupAst.body];
  47940. walk$2(node, {
  47941. enter(child, parent) {
  47942. if (isFunctionType(child)) {
  47943. this.skip();
  47944. }
  47945. if (child.type === "BlockStatement") {
  47946. scope.push(child.body);
  47947. }
  47948. if (child.type === "AwaitExpression") {
  47949. hasAwait = true;
  47950. const currentScope = scope[scope.length - 1];
  47951. const needsSemi = currentScope.some((n, i) => {
  47952. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  47953. });
  47954. processAwait(
  47955. ctx,
  47956. child,
  47957. needsSemi,
  47958. parent.type === "ExpressionStatement"
  47959. );
  47960. }
  47961. },
  47962. exit(node2) {
  47963. if (node2.type === "BlockStatement") scope.pop();
  47964. }
  47965. });
  47966. }
  47967. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  47968. ctx.error(
  47969. `<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.`,
  47970. node
  47971. );
  47972. }
  47973. if (ctx.isTS) {
  47974. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  47975. if (node.type !== "TSEnumDeclaration") {
  47976. hoistNode(node);
  47977. }
  47978. }
  47979. }
  47980. }
  47981. if (ctx.propsDestructureDecl) {
  47982. transformDestructuredProps(ctx, vueImportAliases);
  47983. }
  47984. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  47985. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  47986. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  47987. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  47988. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  47989. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  47990. for (const node of runtimeOptionNodes) {
  47991. checkInvalidScopeReference(node, DEFINE_MODEL);
  47992. }
  47993. }
  47994. if (script) {
  47995. if (startOffset < scriptStartOffset) {
  47996. ctx.s.remove(0, startOffset);
  47997. ctx.s.remove(endOffset, scriptStartOffset);
  47998. ctx.s.remove(scriptEndOffset, source.length);
  47999. } else {
  48000. ctx.s.remove(0, scriptStartOffset);
  48001. ctx.s.remove(scriptEndOffset, startOffset);
  48002. ctx.s.remove(endOffset, source.length);
  48003. }
  48004. } else {
  48005. ctx.s.remove(0, startOffset);
  48006. ctx.s.remove(endOffset, source.length);
  48007. }
  48008. if (scriptAst) {
  48009. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  48010. }
  48011. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  48012. ctx.userImports
  48013. )) {
  48014. if (isType) continue;
  48015. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  48016. }
  48017. for (const key in scriptBindings) {
  48018. ctx.bindingMetadata[key] = scriptBindings[key];
  48019. }
  48020. for (const key in setupBindings) {
  48021. ctx.bindingMetadata[key] = setupBindings[key];
  48022. }
  48023. if (sfc.template && !sfc.template.src && sfc.template.ast) {
  48024. const vModelIds = resolveTemplateVModelIdentifiers(sfc);
  48025. if (vModelIds.size) {
  48026. const toDemote = /* @__PURE__ */ new Set();
  48027. for (const id of vModelIds) {
  48028. if (setupBindings[id] === "setup-reactive-const") {
  48029. toDemote.add(id);
  48030. }
  48031. }
  48032. if (toDemote.size) {
  48033. for (const node of scriptSetupAst.body) {
  48034. if (node.type === "VariableDeclaration" && node.kind === "const" && !node.declare) {
  48035. const demotedInDecl = [];
  48036. for (const decl of node.declarations) {
  48037. if (decl.id.type === "Identifier" && toDemote.has(decl.id.name)) {
  48038. demotedInDecl.push(decl.id.name);
  48039. }
  48040. }
  48041. if (demotedInDecl.length) {
  48042. ctx.s.overwrite(
  48043. node.start + startOffset,
  48044. node.start + startOffset + "const".length,
  48045. "let"
  48046. );
  48047. for (const id of demotedInDecl) {
  48048. setupBindings[id] = "setup-let";
  48049. ctx.bindingMetadata[id] = "setup-let";
  48050. warnOnce$1(
  48051. `\`v-model\` cannot update a \`const\` reactive binding \`${id}\`. The compiler has transformed it to \`let\` to make the update work.`
  48052. );
  48053. }
  48054. }
  48055. }
  48056. }
  48057. }
  48058. }
  48059. }
  48060. if (sfc.cssVars.length && // no need to do this when targeting SSR
  48061. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  48062. ctx.helperImports.add(CSS_VARS_HELPER);
  48063. ctx.helperImports.add("unref");
  48064. ctx.s.prependLeft(
  48065. startOffset,
  48066. `
  48067. ${genCssVarsCode(
  48068. sfc.cssVars,
  48069. ctx.bindingMetadata,
  48070. scopeId,
  48071. !!options.isProd
  48072. )}
  48073. `
  48074. );
  48075. }
  48076. let args = `__props`;
  48077. if (ctx.propsTypeDecl) {
  48078. args += `: any`;
  48079. }
  48080. if (ctx.propsDecl) {
  48081. if (ctx.propsDestructureRestId) {
  48082. ctx.s.overwrite(
  48083. startOffset + ctx.propsCall.start,
  48084. startOffset + ctx.propsCall.end,
  48085. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  48086. Object.keys(ctx.propsDestructuredBindings)
  48087. )})`
  48088. );
  48089. ctx.s.overwrite(
  48090. startOffset + ctx.propsDestructureDecl.start,
  48091. startOffset + ctx.propsDestructureDecl.end,
  48092. ctx.propsDestructureRestId
  48093. );
  48094. } else if (!ctx.propsDestructureDecl) {
  48095. ctx.s.overwrite(
  48096. startOffset + ctx.propsCall.start,
  48097. startOffset + ctx.propsCall.end,
  48098. "__props"
  48099. );
  48100. }
  48101. }
  48102. if (hasAwait) {
  48103. const any = ctx.isTS ? `: any` : ``;
  48104. ctx.s.prependLeft(startOffset, `
  48105. let __temp${any}, __restore${any}
  48106. `);
  48107. }
  48108. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  48109. if (ctx.emitDecl) {
  48110. destructureElements.push(`emit: __emit`);
  48111. }
  48112. if (destructureElements.length) {
  48113. args += `, { ${destructureElements.join(", ")} }`;
  48114. }
  48115. let templateMap;
  48116. let returned;
  48117. const propsDecl = genRuntimeProps(ctx);
  48118. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  48119. const allBindings = __spreadValues$1(__spreadValues$1({}, scriptBindings), setupBindings);
  48120. for (const key in ctx.userImports) {
  48121. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  48122. allBindings[key] = true;
  48123. }
  48124. }
  48125. returned = `{ `;
  48126. for (const key in allBindings) {
  48127. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  48128. returned += `get ${key}() { return ${key} }, `;
  48129. } else if (ctx.bindingMetadata[key] === "setup-let") {
  48130. const setArg = key === "v" ? `_v` : `v`;
  48131. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  48132. } else {
  48133. returned += `${key}, `;
  48134. }
  48135. }
  48136. returned = returned.replace(/, $/, "") + ` }`;
  48137. } else {
  48138. if (sfc.template && !sfc.template.src) {
  48139. if (options.templateOptions && options.templateOptions.ssr) {
  48140. hasInlinedSsrRenderFn = true;
  48141. }
  48142. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate(__spreadProps(__spreadValues$1({
  48143. filename,
  48144. ast: sfc.template.ast,
  48145. source: sfc.template.content,
  48146. inMap: sfc.template.map
  48147. }, options.templateOptions), {
  48148. id: scopeId,
  48149. scoped: sfc.styles.some((s) => s.scoped),
  48150. isProd: options.isProd,
  48151. ssrCssVars: sfc.cssVars,
  48152. compilerOptions: __spreadProps(__spreadValues$1({}, options.templateOptions && options.templateOptions.compilerOptions), {
  48153. inline: true,
  48154. isTS: ctx.isTS,
  48155. bindingMetadata: ctx.bindingMetadata
  48156. })
  48157. }));
  48158. templateMap = map2;
  48159. if (tips.length) {
  48160. tips.forEach(warnOnce$1);
  48161. }
  48162. const err = errors[0];
  48163. if (typeof err === "string") {
  48164. throw new Error(err);
  48165. } else if (err) {
  48166. if (err.loc) {
  48167. err.message += `
  48168. ` + sfc.filename + "\n" + generateCodeFrame(
  48169. source,
  48170. err.loc.start.offset,
  48171. err.loc.end.offset
  48172. ) + `
  48173. `;
  48174. }
  48175. throw err;
  48176. }
  48177. if (preamble) {
  48178. ctx.s.prepend(preamble);
  48179. }
  48180. if (ast && ast.helpers.has(UNREF)) {
  48181. ctx.helperImports.delete("unref");
  48182. }
  48183. returned = code;
  48184. } else {
  48185. returned = `() => {}`;
  48186. }
  48187. }
  48188. if (!options.inlineTemplate && true) {
  48189. ctx.s.appendRight(
  48190. endOffset,
  48191. `
  48192. const __returned__ = ${returned}
  48193. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  48194. return __returned__
  48195. }
  48196. `
  48197. );
  48198. } else {
  48199. ctx.s.appendRight(endOffset, `
  48200. return ${returned}
  48201. }
  48202. `);
  48203. }
  48204. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  48205. let runtimeOptions = ``;
  48206. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  48207. const match = filename.match(/([^/\\]+)\.\w+$/);
  48208. if (match) {
  48209. runtimeOptions += `
  48210. __name: '${match[1]}',`;
  48211. }
  48212. }
  48213. if (hasInlinedSsrRenderFn) {
  48214. runtimeOptions += `
  48215. __ssrInlineRender: true,`;
  48216. }
  48217. if (propsDecl) runtimeOptions += `
  48218. props: ${propsDecl},`;
  48219. const emitsDecl = genRuntimeEmits(ctx);
  48220. if (emitsDecl) runtimeOptions += `
  48221. emits: ${emitsDecl},`;
  48222. let definedOptions = "";
  48223. if (ctx.optionsRuntimeDecl) {
  48224. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  48225. }
  48226. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  48227. `;
  48228. if (ctx.isTS) {
  48229. const def = (defaultExport ? `
  48230. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  48231. ...${definedOptions},` : "");
  48232. ctx.s.prependLeft(
  48233. startOffset,
  48234. `
  48235. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  48236. `defineComponent`
  48237. )}({${def}${runtimeOptions}
  48238. ${hasAwait ? `async ` : ``}setup(${args}) {
  48239. ${exposeCall}`
  48240. );
  48241. ctx.s.appendRight(endOffset, `})`);
  48242. } else {
  48243. if (defaultExport || definedOptions) {
  48244. ctx.s.prependLeft(
  48245. startOffset,
  48246. `
  48247. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  48248. ${hasAwait ? `async ` : ``}setup(${args}) {
  48249. ${exposeCall}`
  48250. );
  48251. ctx.s.appendRight(endOffset, `})`);
  48252. } else {
  48253. ctx.s.prependLeft(
  48254. startOffset,
  48255. `
  48256. ${genDefaultAs} {${runtimeOptions}
  48257. ${hasAwait ? `async ` : ``}setup(${args}) {
  48258. ${exposeCall}`
  48259. );
  48260. ctx.s.appendRight(endOffset, `}`);
  48261. }
  48262. }
  48263. if (ctx.helperImports.size > 0) {
  48264. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  48265. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  48266. ctx.s.prepend(
  48267. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  48268. `
  48269. );
  48270. }
  48271. const content = ctx.s.toString();
  48272. let map = options.sourceMap !== false ? ctx.s.generateMap({
  48273. source: filename,
  48274. hires: true,
  48275. includeContent: true
  48276. }) : void 0;
  48277. if (templateMap && map) {
  48278. const offset = content.indexOf(returned);
  48279. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  48280. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  48281. }
  48282. return __spreadProps(__spreadValues$1({}, scriptSetup), {
  48283. bindings: ctx.bindingMetadata,
  48284. imports: ctx.userImports,
  48285. content,
  48286. map,
  48287. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  48288. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  48289. deps: ctx.deps ? [...ctx.deps] : void 0
  48290. });
  48291. }
  48292. function registerBinding(bindings, node, type) {
  48293. bindings[node.name] = type;
  48294. }
  48295. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  48296. let isAllLiteral = false;
  48297. if (node.type === "VariableDeclaration") {
  48298. const isConst = node.kind === "const";
  48299. isAllLiteral = isConst && node.declarations.every(
  48300. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  48301. );
  48302. for (const { id, init: _init } of node.declarations) {
  48303. const init = _init && unwrapTSNode(_init);
  48304. const isConstMacroCall = isConst && isCallOf(
  48305. init,
  48306. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  48307. );
  48308. if (id.type === "Identifier") {
  48309. let bindingType;
  48310. const userReactiveBinding = userImportAliases["reactive"];
  48311. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  48312. bindingType = "literal-const";
  48313. } else if (isCallOf(init, userReactiveBinding)) {
  48314. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  48315. } else if (
  48316. // if a declaration is a const literal, we can mark it so that
  48317. // the generated render fn code doesn't need to unref() it
  48318. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  48319. ) {
  48320. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  48321. } else if (isConst) {
  48322. if (isCallOf(
  48323. init,
  48324. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  48325. )) {
  48326. bindingType = "setup-ref";
  48327. } else {
  48328. bindingType = "setup-maybe-ref";
  48329. }
  48330. } else {
  48331. bindingType = "setup-let";
  48332. }
  48333. registerBinding(bindings, id, bindingType);
  48334. } else {
  48335. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  48336. continue;
  48337. }
  48338. if (id.type === "ObjectPattern") {
  48339. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  48340. } else if (id.type === "ArrayPattern") {
  48341. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  48342. }
  48343. }
  48344. }
  48345. } else if (node.type === "TSEnumDeclaration") {
  48346. isAllLiteral = node.members.every(
  48347. (member) => !member.initializer || isStaticNode(member.initializer)
  48348. );
  48349. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  48350. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  48351. bindings[node.id.name] = "setup-const";
  48352. }
  48353. return isAllLiteral;
  48354. }
  48355. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  48356. for (const p of node.properties) {
  48357. if (p.type === "ObjectProperty") {
  48358. if (p.key.type === "Identifier" && p.key === p.value) {
  48359. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  48360. registerBinding(bindings, p.key, type);
  48361. } else {
  48362. walkPattern(p.value, bindings, isConst, isDefineCall);
  48363. }
  48364. } else {
  48365. const type = isConst ? "setup-const" : "setup-let";
  48366. registerBinding(bindings, p.argument, type);
  48367. }
  48368. }
  48369. }
  48370. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  48371. for (const e of node.elements) {
  48372. e && walkPattern(e, bindings, isConst, isDefineCall);
  48373. }
  48374. }
  48375. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  48376. if (node.type === "Identifier") {
  48377. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  48378. registerBinding(bindings, node, type);
  48379. } else if (node.type === "RestElement") {
  48380. const type = isConst ? "setup-const" : "setup-let";
  48381. registerBinding(bindings, node.argument, type);
  48382. } else if (node.type === "ObjectPattern") {
  48383. walkObjectPattern(node, bindings, isConst);
  48384. } else if (node.type === "ArrayPattern") {
  48385. walkArrayPattern(node, bindings, isConst);
  48386. } else if (node.type === "AssignmentPattern") {
  48387. if (node.left.type === "Identifier") {
  48388. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  48389. registerBinding(bindings, node.left, type);
  48390. } else {
  48391. walkPattern(node.left, bindings, isConst);
  48392. }
  48393. }
  48394. }
  48395. function canNeverBeRef(node, userReactiveImport) {
  48396. if (isCallOf(node, userReactiveImport)) {
  48397. return true;
  48398. }
  48399. switch (node.type) {
  48400. case "UnaryExpression":
  48401. case "BinaryExpression":
  48402. case "ArrayExpression":
  48403. case "ObjectExpression":
  48404. case "FunctionExpression":
  48405. case "ArrowFunctionExpression":
  48406. case "UpdateExpression":
  48407. case "ClassExpression":
  48408. case "TaggedTemplateExpression":
  48409. return true;
  48410. case "SequenceExpression":
  48411. return canNeverBeRef(
  48412. node.expressions[node.expressions.length - 1],
  48413. userReactiveImport
  48414. );
  48415. default:
  48416. if (isLiteralNode(node)) {
  48417. return true;
  48418. }
  48419. return false;
  48420. }
  48421. }
  48422. function isStaticNode(node) {
  48423. node = unwrapTSNode(node);
  48424. switch (node.type) {
  48425. case "UnaryExpression":
  48426. return isStaticNode(node.argument);
  48427. case "LogicalExpression":
  48428. // 1 > 2
  48429. case "BinaryExpression":
  48430. return isStaticNode(node.left) && isStaticNode(node.right);
  48431. case "ConditionalExpression": {
  48432. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  48433. }
  48434. case "SequenceExpression":
  48435. // (1, 2)
  48436. case "TemplateLiteral":
  48437. return node.expressions.every((expr) => isStaticNode(expr));
  48438. case "ParenthesizedExpression":
  48439. return isStaticNode(node.expression);
  48440. case "StringLiteral":
  48441. case "NumericLiteral":
  48442. case "BooleanLiteral":
  48443. case "NullLiteral":
  48444. case "BigIntLiteral":
  48445. return true;
  48446. }
  48447. return false;
  48448. }
  48449. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  48450. const generator = new sourceMapExports.SourceMapGenerator();
  48451. const addMapping = (map, lineOffset = 0) => {
  48452. const consumer = new sourceMapExports.SourceMapConsumer(map);
  48453. consumer.sources.forEach((sourceFile) => {
  48454. generator._sources.add(sourceFile);
  48455. const sourceContent = consumer.sourceContentFor(sourceFile);
  48456. if (sourceContent != null) {
  48457. generator.setSourceContent(sourceFile, sourceContent);
  48458. }
  48459. });
  48460. consumer.eachMapping((m) => {
  48461. if (m.originalLine == null) return;
  48462. generator.addMapping({
  48463. generated: {
  48464. line: m.generatedLine + lineOffset,
  48465. column: m.generatedColumn
  48466. },
  48467. original: {
  48468. line: m.originalLine,
  48469. column: m.originalColumn
  48470. },
  48471. source: m.source,
  48472. name: m.name
  48473. });
  48474. });
  48475. };
  48476. addMapping(scriptMap);
  48477. addMapping(templateMap, templateLineOffset);
  48478. generator._sourceRoot = scriptMap.sourceRoot;
  48479. generator._file = scriptMap.file;
  48480. return generator.toJSON();
  48481. }
  48482. var __defProp = Object.defineProperty;
  48483. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  48484. var __hasOwnProp = Object.prototype.hasOwnProperty;
  48485. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  48486. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  48487. var __spreadValues = (a, b) => {
  48488. for (var prop in b || (b = {}))
  48489. if (__hasOwnProp.call(b, prop))
  48490. __defNormalProp(a, prop, b[prop]);
  48491. if (__getOwnPropSymbols)
  48492. for (var prop of __getOwnPropSymbols(b)) {
  48493. if (__propIsEnum.call(b, prop))
  48494. __defNormalProp(a, prop, b[prop]);
  48495. }
  48496. return a;
  48497. };
  48498. const version = "3.5.38";
  48499. const parseCache = parseCache$1;
  48500. const errorMessages = __spreadValues(__spreadValues({}, errorMessages$1), DOMErrorMessages);
  48501. const walk = walk$2;
  48502. const shouldTransformRef = () => false;
  48503. var parse$4 = libExports.parse;
  48504. export { MagicString, parse$4 as babelParse, compileScript, compileStyle, compileStyleAsync, compileTemplate, errorMessages, extractIdentifiers$1 as extractIdentifiers, extractRuntimeEmits, extractRuntimeProps, generateCodeFrame, inferRuntimeType, invalidateTypeCache, isInDestructureAssignment, isStaticProperty, parse$2 as parse, parseCache, registerTS, resolveTypeElements, rewriteDefault, rewriteDefaultAST, shouldTransformRef, version, walk, walkIdentifiers };